From b55aa3608cd407ed89ceb163b4e2182b5f01f662 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Thu, 29 Oct 2026 23:29:10 +0000 Subject: [PATCH 01/11] ci(integration): run the integration lane through make recipes (M2 2/4, #920) The integration workflow built, started and tested gigapipe with raw commands. It now runs make build, make integration-start and make test-integration, and test/integration/run.sh runs the same make test-integration, so CI and local runs are the same commands. integration-start waits up to 60s for /api/v1/status/buildinfo and prints gigapipe.log if gigapipe never answers. --- .github/workflows/integration.yml | 19 +++---------------- Makefile | 23 ++++++++++++++++++++++- docs/contributing.md | 1 + test/integration/run.sh | 2 +- 4 files changed, 27 insertions(+), 18 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 05ce7344a..0b4615680 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -20,30 +20,17 @@ jobs: go-version-file: go.mod - name: Build gigapipe - run: go build -o gigapipe ./cmd/gigapipe + run: make build # The image version lives in the compose file, shared with run.sh. - name: Start ClickHouse run: docker compose -f test/integration/docker-compose.yml up -d --wait clickhouse - name: Start gigapipe - run: | - CLICKHOUSE_SERVER=localhost CLICKHOUSE_PORT=9000 PORT=3100 BULK_MAX_AGE_MS=100 \ - ./gigapipe > gigapipe.log 2>&1 & - echo $! > gigapipe.pid - - - name: Wait for gigapipe - run: | - for i in $(seq 1 60); do - if curl -sf http://localhost:3100/api/v1/status/buildinfo >/dev/null; then - echo "gigapipe ready"; exit 0 - fi - sleep 1 - done - echo "gigapipe never became ready; logs:"; cat gigapipe.log; exit 1 + run: make integration-start - name: Run integration tests - run: GIGAPIPE_URL=http://localhost:3100 go test -tags integration -count=1 -v ./test/integration/... + run: make test-integration - name: gigapipe logs on failure if: failure() diff --git a/Makefile b/Makefile index a9155fe05..af7471a8b 100644 --- a/Makefile +++ b/Makefile @@ -22,7 +22,7 @@ DURATION ?= 60s 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 + fmt-check build test-unit integration-start test-integration lint fuzz docker: docker build -t gigapipe . @@ -40,6 +40,27 @@ build: test-unit: go test -race ./... +# Start the binary built by `make build` in the background against the +# ClickHouse at CLICKHOUSE_SERVER:CLICKHOUSE_PORT and wait until it answers. +# Output goes to gigapipe.log. Used by the integration CI lane; locally, +# test/integration/run.sh starts ClickHouse and gigapipe in Docker instead. +integration-start: + CLICKHOUSE_SERVER=$${CLICKHOUSE_SERVER:-localhost} CLICKHOUSE_PORT=$${CLICKHOUSE_PORT:-9000} \ + PORT=$${PORT:-3100} BULK_MAX_AGE_MS=$${BULK_MAX_AGE_MS:-100} \ + ./gigapipe > gigapipe.log 2>&1 & echo $$! > gigapipe.pid + @for i in $$(seq 1 60); do \ + if curl -sf http://localhost:$${PORT:-3100}/api/v1/status/buildinfo >/dev/null; then \ + echo "gigapipe ready"; exit 0; \ + fi; \ + sleep 1; \ + done; \ + echo "gigapipe never became ready; logs:"; cat gigapipe.log; exit 1 + +# Run the Go integration tests against the gigapipe at GIGAPIPE_URL +# (default http://localhost:3100). +test-integration: + go test -tags integration -count=1 -v ./test/integration/... + # 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 diff --git a/docs/contributing.md b/docs/contributing.md index a5526c466..c8395c040 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -76,6 +76,7 @@ recipes), plus parser-fuzz helpers for the query transpilers: 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 test-integration # integration tests against GIGAPIPE_URL (see test/integration/run.sh) 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 ``` diff --git a/test/integration/run.sh b/test/integration/run.sh index bb5fe4bfe..0dba91604 100755 --- a/test/integration/run.sh +++ b/test/integration/run.sh @@ -25,4 +25,4 @@ $COMPOSE up -d --build echo "--- running integration tests against $GIGAPIPE_URL ---" cd ../.. -go test -tags integration -count=1 -v ./test/integration/... +make test-integration From f97bc11bd9a3a50223fbe325a627416a76440d36 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Thu, 29 Oct 2026 23:29:10 +0000 Subject: [PATCH 02/11] fix(test): tear down the integration stack from the right directory run.sh changed to the repository root before running the tests, but the EXIT trap runs `docker compose -f docker-compose.yml` with a relative path, so teardown failed (hidden by `|| true`) and left the gigapipe and ClickHouse containers running after every run. Run the tests in a subshell so the trap still runs from test/integration. --- test/integration/run.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/integration/run.sh b/test/integration/run.sh index 0dba91604..c9531bc94 100755 --- a/test/integration/run.sh +++ b/test/integration/run.sh @@ -24,5 +24,5 @@ echo "--- building + starting stack ---" $COMPOSE up -d --build echo "--- running integration tests against $GIGAPIPE_URL ---" -cd ../.. -make test-integration +# Subshell: cleanup must still run from this directory, where docker-compose.yml is. +(cd ../.. && make test-integration) From 52ce7b8a24cae1e0162a26a19a3e49d03c11d71c Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Thu, 29 Oct 2026 23:40:10 +0000 Subject: [PATCH 03/11] test(integration): seed package and write-read harness for logs (M2 2/4, #920) Add test/integration/seed, a deterministic declaration of the data the integration tests write: services and pods, from which every signal is derived. Logs are generated with a fixed random seed, so the same fixture always produces the same push body; Run only sets the m2_run label that keeps one run's data apart from earlier runs. TestLogsRoundTrip pushes the fixture through /loki/api/v1/push and checks what the Loki read APIs return against it, one named case each: every line per stream, a line filter, the json parser with a label filter, count_over_time per pod, labels, label values and series. The query_range, instant query, label values and series responses are also compared with pinned copies under testdata/logs/, since that JSON is what Grafana reads. Run-specific values (the run label, timestamps) are normalized before the comparison. The pins are maintained by hand; there is no regeneration mode. gigapipe's labels endpoint ignores the query parameter Loki uses to narrow it to a selector, so that case cannot be limited to one run; the series case covers the label sets. --- test/integration/logs_roundtrip_test.go | 488 ++++++++++++++++++ test/integration/seed/seed.go | 151 ++++++ test/integration/seed/seed_test.go | 78 +++ .../testdata/logs/label_pod_values.json | 8 + .../testdata/logs/query_count_by_pod.json | 48 ++ .../logs/query_range_json_filter.json | 116 +++++ .../testdata/logs/query_range_streams.json | 116 +++++ test/integration/testdata/logs/series.json | 29 ++ 8 files changed, 1034 insertions(+) create mode 100644 test/integration/logs_roundtrip_test.go create mode 100644 test/integration/seed/seed.go create mode 100644 test/integration/seed/seed_test.go create mode 100644 test/integration/testdata/logs/label_pod_values.json create mode 100644 test/integration/testdata/logs/query_count_by_pod.json create mode 100644 test/integration/testdata/logs/query_range_json_filter.json create mode 100644 test/integration/testdata/logs/query_range_streams.json create mode 100644 test/integration/testdata/logs/series.json diff --git a/test/integration/logs_roundtrip_test.go b/test/integration/logs_roundtrip_test.go new file mode 100644 index 000000000..4083e2ed2 --- /dev/null +++ b/test/integration/logs_roundtrip_test.go @@ -0,0 +1,488 @@ +//go:build integration + +// Write-read round trip for logs (M2, #920). The seed fixture is pushed through +// the Loki push API and read back through the Loki read APIs, and every check +// compares the answer with the fixture. A change to how logs are stored (for +// example the samples table split in #972) that changes what a query returns +// fails a named case. +// +// Some checks also compare the response with a pinned copy under +// testdata/logs/: that JSON is what Grafana reads, so it is a wire contract. +// The pins are maintained by hand. If one fails after an intended change, +// review the difference and edit the file; there is no regeneration mode. + +package integration + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "testing" + "time" + + "github.com/metrico/qryn/v5/test/integration/seed" +) + +func TestLogsRoundTrip(t *testing.T) { + run := fmt.Sprintf("logs-%d", time.Now().UnixNano()) + start := time.Now().Add(-10 * time.Minute).Truncate(time.Minute) + streams := seed.Default(run, start).Logs() + from, to := start.Add(-time.Minute), start.Add(5*time.Minute) + selector := fmt.Sprintf(`{%s=%q}`, seed.RunLabel, run) + + postJSON(t, "/loki/api/v1/push", seed.LokiPushJSON(streams)) + total := 0 + for _, s := range streams { + total += len(s.Lines) + } + waitForLogLines(t, selector, from, to, total) + + norm := normalizer{run: run, start: start} + + t.Run("all lines come back per stream", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/query_range", rangeParams(selector, from, to)) + assertStreams(t, raw, expectedStreams(streams, func(seed.LogLine) bool { return true })) + assertPinned(t, "logs/query_range_streams.json", norm.streams(t, raw)) + }) + + t.Run("line filter keeps only error lines", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/query_range", rangeParams(selector+` |= "\"level\":\"error\""`, from, to)) + assertStreams(t, raw, expectedStreams(streams, func(l seed.LogLine) bool { return l.Level == "error" })) + }) + + t.Run("json parser and label filter keep only error lines", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/query_range", rangeParams(selector+` | json | level="error"`, from, to)) + var got []string + for _, r := range decodeStreams(t, raw) { + if r.Stream["level"] != "error" { + t.Errorf("stream %v: level label = %q, want \"error\"", r.Stream, r.Stream["level"]) + } + for _, v := range r.Values { + got = append(got, r.Stream["app"]+"/"+r.Stream["pod"]+" "+v[1]) + } + } + var want []string + for _, s := range streams { + for _, l := range s.Lines { + if l.Level == "error" { + want = append(want, s.Labels["app"]+"/"+s.Labels["pod"]+" "+l.Text) + } + } + } + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("lines:\n got %q\nwant %q", got, want) + } + assertPinned(t, "logs/query_range_json_filter.json", norm.streams(t, raw)) + }) + + t.Run("count_over_time per app and pod", func(t *testing.T) { + q := fmt.Sprintf("sum by (app, pod) (count_over_time(%s[1h]))", selector) + raw := apiGet(t, "/loki/api/v1/query", url.Values{"query": {q}, "time": {nanos(to)}}) + var resp struct { + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Value [2]any `json:"value"` + } `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + if resp.Data.ResultType != "vector" { + t.Fatalf("resultType = %q, want vector", resp.Data.ResultType) + } + got := map[string]string{} + for _, r := range resp.Data.Result { + got[r.Metric["app"]+"/"+r.Metric["pod"]] = fmt.Sprint(r.Value[1]) + } + want := map[string]string{} + for _, s := range streams { + want[s.Labels["app"]+"/"+s.Labels["pod"]] = strconv.Itoa(len(s.Lines)) + } + if !mapsEqual(got, want) { + t.Errorf("counts = %v, want %v", got, want) + } + assertPinned(t, "logs/query_count_by_pod.json", norm.vector(t, raw, to)) + }) + + // gigapipe's labels endpoint ignores the query parameter that Loki uses to + // narrow it to a selector, so this cannot be limited to this run's data: + // it shows the names are listed, not that this run wrote them. The series + // case below is limited to this run and covers the label sets. + t.Run("labels lists every label written", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/labels", url.Values{"start": {nanos(from)}, "end": {nanos(to)}}) + var resp struct { + Data []string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + for _, name := range []string{seed.RunLabel, "app", "pod", "service_name"} { + if !slices.Contains(resp.Data, name) { + t.Errorf("labels %v do not include %q", resp.Data, name) + } + } + }) + + t.Run("label values of pod", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/label/pod/values", + url.Values{"query": {selector}, "start": {nanos(from)}, "end": {nanos(to)}}) + var resp struct { + Data []string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + var want []string + for _, s := range streams { + if !slices.Contains(want, s.Labels["pod"]) { + want = append(want, s.Labels["pod"]) + } + } + got := slices.Clone(resp.Data) + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("pod values = %v, want %v", got, want) + } + assertPinned(t, "logs/label_pod_values.json", norm.generic(t, raw)) + }) + + t.Run("series lists every stream", func(t *testing.T) { + raw := apiGet(t, "/loki/api/v1/series", + url.Values{"match[]": {selector}, "start": {nanos(from)}, "end": {nanos(to)}}) + var resp struct { + Data []map[string]string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + var got, want []string + for _, s := range resp.Data { + got = append(got, labelKey(s)) + } + for _, s := range streams { + want = append(want, labelKey(withServiceName(s.Labels))) + } + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("series:\n got %q\nwant %q", got, want) + } + assertPinned(t, "logs/series.json", norm.series(t, raw)) + }) +} + +// withServiceName returns the labels gigapipe stores for a stream it was sent +// with these labels: it adds service_name, copied from app. +func withServiceName(labels map[string]string) map[string]string { + out := map[string]string{"service_name": labels["app"]} + for k, v := range labels { + out[k] = v + } + return out +} + +// expectedStreams returns, keyed by label set, the [timestamp, line] values a +// query over the fixture should return when it keeps the lines keep accepts. +// Streams with no kept line are absent, as in a Loki response. +func expectedStreams(streams []seed.LogStream, keep func(seed.LogLine) bool) map[string][][2]string { + out := map[string][][2]string{} + for _, s := range streams { + var values [][2]string + for _, l := range s.Lines { + if keep(l) { + values = append(values, [2]string{nanos(l.Time), l.Text}) + } + } + if len(values) > 0 { + out[labelKey(withServiceName(s.Labels))] = values + } + } + return out +} + +type lokiStream struct { + Stream map[string]string `json:"stream"` + Values [][2]string `json:"values"` +} + +func decodeStreams(t *testing.T, raw []byte) []lokiStream { + t.Helper() + var resp struct { + Data struct { + ResultType string `json:"resultType"` + Result []lokiStream `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + if resp.Data.ResultType != "streams" { + t.Fatalf("resultType = %q, want streams", resp.Data.ResultType) + } + return resp.Data.Result +} + +// assertStreams compares a streams response with want, by label set, with the +// lines of each stream in time order (the request uses direction=forward). +func assertStreams(t *testing.T, raw []byte, want map[string][][2]string) { + t.Helper() + got := map[string][][2]string{} + for _, r := range decodeStreams(t, raw) { + key := labelKey(r.Stream) + if _, dup := got[key]; dup { + t.Errorf("stream %s returned twice", key) + } + got[key] = r.Values + } + for key, values := range want { + if !slices.Equal(got[key], values) { + t.Errorf("stream %s:\n got %q\nwant %q", key, got[key], values) + } + } + for key := range got { + if _, ok := want[key]; !ok { + t.Errorf("unexpected stream %s: %q", key, got[key]) + } + } +} + +// waitForLogLines polls until the query returns want lines in total, since +// ingestion is flushed asynchronously. On timeout it only logs, so the named +// checks that follow still run and report what is wrong. +func waitForLogLines(t *testing.T, selector string, from, to time.Time, want int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := 0 + for _, r := range decodeStreams(t, apiGet(t, "/loki/api/v1/query_range", rangeParams(selector, from, to))) { + got += len(r.Values) + } + if got == want { + return + } + if time.Now().After(deadline) { + t.Logf("after 30s the query returns %d lines, want %d; checking anyway", got, want) + return + } + time.Sleep(500 * time.Millisecond) + } +} + +func rangeParams(query string, from, to time.Time) url.Values { + return url.Values{ + "query": {query}, + "start": {nanos(from)}, + "end": {nanos(to)}, + "direction": {"forward"}, + "limit": {"1000"}, + } +} + +func nanos(t time.Time) string { return strconv.FormatInt(t.UnixNano(), 10) } + +// labelKey renders a label set in a fixed order, for comparisons. +func labelKey(labels map[string]string) string { + keys := make([]string, 0, len(labels)) + for k := range labels { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, len(keys)) + for i, k := range keys { + parts[i] = fmt.Sprintf("%s=%q", k, labels[k]) + } + return "{" + strings.Join(parts, ", ") + "}" +} + +func mapsEqual(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if bv, ok := b[k]; !ok || bv != v { + return false + } + } + return true +} + +func apiGet(t *testing.T, path string, params url.Values) []byte { + t.Helper() + resp, err := http.Get(baseURL() + path + "?" + params.Encode()) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET %s: status %d, body %q", path, resp.StatusCode, raw) + } + return raw +} + +func postJSON(t *testing.T, path string, body []byte) { + t.Helper() + resp, err := http.Post(baseURL()+path, "application/json", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("POST %s: status %d, body %q", path, resp.StatusCode, raw) + } +} + +func mustUnmarshal(t *testing.T, raw []byte, v any) { + t.Helper() + if err := json.Unmarshal(raw, v); err != nil { + t.Fatalf("decode %q: %v", raw, err) + } +} + +// normalizer replaces the values that differ between runs with fixed ones, so +// a response can be compared with its pinned copy: the run label value becomes +// "RUN" and timestamps become offsets from the fixture start, such as "+10s". +// Result order, which the APIs do not define, is sorted. +type normalizer struct { + run string + start time.Time +} + +func (n normalizer) offset(ts time.Time) string { + return fmt.Sprintf("%+ds", int64(ts.Sub(n.start)/time.Second)) +} + +func (n normalizer) labels(labels map[string]string) map[string]string { + out := map[string]string{} + for k, v := range labels { + if v == n.run { + v = "RUN" + } + out[k] = v + } + return out +} + +// streams normalizes a query_range streams response. +func (n normalizer) streams(t *testing.T, raw []byte) any { + t.Helper() + var resp struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []lokiStream `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + for i, r := range resp.Data.Result { + r.Stream = n.labels(r.Stream) + for j, v := range r.Values { + ns, err := strconv.ParseInt(v[0], 10, 64) + if err != nil { + t.Fatalf("timestamp %q: %v", v[0], err) + } + r.Values[j][0] = n.offset(time.Unix(0, ns)) + } + resp.Data.Result[i] = r + } + sort.Slice(resp.Data.Result, func(i, j int) bool { + return labelKey(resp.Data.Result[i].Stream) < labelKey(resp.Data.Result[j].Stream) + }) + return resp +} + +// vector normalizes an instant query vector response evaluated at evalTime. +func (n normalizer) vector(t *testing.T, raw []byte, evalTime time.Time) any { + t.Helper() + var resp struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Value [2]any `json:"value"` + } `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + for i, r := range resp.Data.Result { + ts, ok := r.Value[0].(float64) + if !ok { + t.Fatalf("sample time %v is not a number", r.Value[0]) + } + if int64(ts) != evalTime.Unix() { + t.Errorf("sample time %v, want the evaluation time %d", ts, evalTime.Unix()) + } + r.Metric = n.labels(r.Metric) + r.Value[0] = n.offset(time.Unix(int64(ts), 0)) + resp.Data.Result[i] = r + } + sort.Slice(resp.Data.Result, func(i, j int) bool { + return labelKey(resp.Data.Result[i].Metric) < labelKey(resp.Data.Result[j].Metric) + }) + return resp +} + +// series normalizes a series response. +func (n normalizer) series(t *testing.T, raw []byte) any { + t.Helper() + var resp struct { + Status string `json:"status"` + Data []map[string]string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + for i, s := range resp.Data { + resp.Data[i] = n.labels(s) + } + sort.Slice(resp.Data, func(i, j int) bool { return labelKey(resp.Data[i]) < labelKey(resp.Data[j]) }) + return resp +} + +// generic decodes a response that has no run-specific values. +func (n normalizer) generic(t *testing.T, raw []byte) any { + t.Helper() + var v any + mustUnmarshal(t, raw, &v) + return v +} + +// assertPinned compares got, once encoded as JSON, with the pinned file under +// testdata/. Both sides are decoded and re-encoded, so key order and +// formatting do not matter. +func assertPinned(t *testing.T, name string, got any) { + t.Helper() + gotJSON := canonicalJSON(t, got) + path := filepath.Join("testdata", name) + pinned, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read pinned response %s: %v\nresponse:\n%s", path, err, gotJSON) + } + var pinnedValue any + mustUnmarshal(t, pinned, &pinnedValue) + if want := canonicalJSON(t, pinnedValue); want != gotJSON { + t.Errorf("response differs from %s (edit the file by hand if the change is intended)\n got:\n%s\nwant:\n%s", path, gotJSON, want) + } +} + +func canonicalJSON(t *testing.T, v any) string { + t.Helper() + // Round-trip through any so struct field order and map key order are the + // same on both sides. + raw, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + var generic any + mustUnmarshal(t, raw, &generic) + out, err := json.MarshalIndent(generic, "", " ") + if err != nil { + t.Fatal(err) + } + return string(out) +} diff --git a/test/integration/seed/seed.go b/test/integration/seed/seed.go new file mode 100644 index 000000000..8fb3de7a1 --- /dev/null +++ b/test/integration/seed/seed.go @@ -0,0 +1,151 @@ +// Package seed declares the data the integration tests write through +// gigapipe's public ingestion APIs. One declaration (Default) lists every +// service and pod, and each signal is derived from it, so query results can be +// checked against numbers known in advance. +// +// Generation is deterministic: the same Fixture always produces the same +// bytes. Run is the value of the RunLabel label on everything written; it keeps +// one test run's data apart from earlier runs against the same ClickHouse. +// Start anchors the timestamps, which are fixed offsets from it. +package seed + +import ( + "encoding/json" + "fmt" + "math/rand/v2" + "strconv" + "time" +) + +// RunLabel is the label carrying Fixture.Run on every series written. +const RunLabel = "m2_run" + +// LineInterval is the time between consecutive log lines of a stream. +const LineInterval = 10 * time.Second + +// Fixture is one declaration of the data written by a test run. +type Fixture struct { + Run string + Start time.Time + Services []Service +} + +// Service is one application, sent as the "app" label. +type Service struct { + Name string + Pods []Pod +} + +// Pod is one log stream of a service: Lines lines, ErrorLines of them at +// level "error" and the rest at level "info". +type Pod struct { + Name string + Lines int + ErrorLines int +} + +// Default returns the standard fixture used by the integration tests. +func Default(run string, start time.Time) Fixture { + return Fixture{ + Run: run, + Start: start, + Services: []Service{ + {Name: "checkout", Pods: []Pod{ + {Name: "p1", Lines: 4, ErrorLines: 1}, + {Name: "p2", Lines: 7, ErrorLines: 3}, + {Name: "p3", Lines: 1, ErrorLines: 0}, + }}, + {Name: "payments", Pods: []Pod{ + {Name: "p1", Lines: 5, ErrorLines: 2}, + }}, + }, + } +} + +// LogStream is one stream as sent to gigapipe. +type LogStream struct { + Labels map[string]string + Lines []LogLine +} + +// LogLine is one log line. Text is a JSON object with level, msg, latency_ms +// and seq (the line's index in its stream). +type LogLine struct { + Time time.Time + Level string + Text string +} + +var ( + infoMessages = []string{"order created", "cart updated", "item reserved", "request served"} + errorMessages = []string{"payment declined", "inventory timeout", "card rejected"} +) + +// Logs returns one stream per pod, in declaration order. Line i of a stream is +// at Start + i*LineInterval. +func (f Fixture) Logs() []LogStream { + // A fixed seed: the content does not depend on Run or Start, so every run + // writes the same lines. + rng := rand.New(rand.NewPCG(920, 2)) + var streams []LogStream + for _, svc := range f.Services { + for _, pod := range svc.Pods { + if pod.ErrorLines > pod.Lines { + panic(fmt.Sprintf("seed: pod %s/%s has more error lines than lines", svc.Name, pod.Name)) + } + isError := make([]bool, pod.Lines) + for i := range pod.ErrorLines { + isError[i] = true + } + rng.Shuffle(len(isError), func(i, j int) { isError[i], isError[j] = isError[j], isError[i] }) + + stream := LogStream{Labels: map[string]string{RunLabel: f.Run, "app": svc.Name, "pod": pod.Name}} + for i := range pod.Lines { + level, messages := "info", infoMessages + if isError[i] { + level, messages = "error", errorMessages + } + text, err := json.Marshal(struct { + Level string `json:"level"` + Msg string `json:"msg"` + LatencyMs int `json:"latency_ms"` + Seq int `json:"seq"` + }{level, messages[rng.IntN(len(messages))], 10 + rng.IntN(990), i}) + if err != nil { + panic(err) + } + stream.Lines = append(stream.Lines, LogLine{ + Time: f.Start.Add(time.Duration(i) * LineInterval), + Level: level, + Text: string(text), + }) + } + streams = append(streams, stream) + } + } + return streams +} + +// LokiPushJSON encodes streams as a Loki push request body +// (POST /loki/api/v1/push, application/json). +func LokiPushJSON(streams []LogStream) []byte { + type pushStream struct { + Stream map[string]string `json:"stream"` + Values [][2]string `json:"values"` + } + body := struct { + Streams []pushStream `json:"streams"` + }{} + for _, s := range streams { + ps := pushStream{Stream: s.Labels} + for _, l := range s.Lines { + ps.Values = append(ps.Values, [2]string{strconv.FormatInt(l.Time.UnixNano(), 10), l.Text}) + } + body.Streams = append(body.Streams, ps) + } + out, err := json.Marshal(body) + if err != nil { + panic(err) + } + return out +} diff --git a/test/integration/seed/seed_test.go b/test/integration/seed/seed_test.go new file mode 100644 index 000000000..b76a20756 --- /dev/null +++ b/test/integration/seed/seed_test.go @@ -0,0 +1,78 @@ +package seed + +import ( + "bytes" + "encoding/json" + "testing" + "time" +) + +var testStart = time.Date(2026, 1, 2, 3, 4, 0, 0, time.UTC) + +// TestLogsAreDeterministic checks that generating the same fixture twice gives +// byte-identical push bodies, and that Run only changes the run label. +func TestLogsAreDeterministic(t *testing.T) { + first := LokiPushJSON(Default("r1", testStart).Logs()) + second := LokiPushJSON(Default("r1", testStart).Logs()) + if !bytes.Equal(first, second) { + t.Fatal("the same fixture produced different push bodies") + } + + other := LokiPushJSON(Default("r2", testStart).Logs()) + if !bytes.Equal(bytes.ReplaceAll(other, []byte(`"r2"`), []byte(`"r1"`)), first) { + t.Fatal("changing Run changed more than the run label") + } +} + +// TestLogsMatchDeclaration checks every stream against its Pod declaration: +// labels, line count, error count, timestamps and line content. +func TestLogsMatchDeclaration(t *testing.T) { + f := Default("r1", testStart) + streams := f.Logs() + + i := 0 + for _, svc := range f.Services { + for _, pod := range svc.Pods { + s := streams[i] + i++ + want := map[string]string{RunLabel: "r1", "app": svc.Name, "pod": pod.Name} + if len(s.Labels) != len(want) { + t.Errorf("%s/%s: labels = %v, want %v", svc.Name, pod.Name, s.Labels, want) + } + for k, v := range want { + if s.Labels[k] != v { + t.Errorf("%s/%s: label %s = %q, want %q", svc.Name, pod.Name, k, s.Labels[k], v) + } + } + if len(s.Lines) != pod.Lines { + t.Fatalf("%s/%s: %d lines, want %d", svc.Name, pod.Name, len(s.Lines), pod.Lines) + } + errors := 0 + for n, l := range s.Lines { + if wantTime := testStart.Add(time.Duration(n) * LineInterval); !l.Time.Equal(wantTime) { + t.Errorf("%s/%s line %d: time %v, want %v", svc.Name, pod.Name, n, l.Time, wantTime) + } + var body struct { + Level string `json:"level"` + Msg string `json:"msg"` + Seq int `json:"seq"` + } + if err := json.Unmarshal([]byte(l.Text), &body); err != nil { + t.Fatalf("%s/%s line %d is not JSON: %v", svc.Name, pod.Name, n, err) + } + if body.Level != l.Level || body.Seq != n || body.Msg == "" { + t.Errorf("%s/%s line %d: body %+v does not match level %q, seq %d", svc.Name, pod.Name, n, body, l.Level, n) + } + if l.Level == "error" { + errors++ + } + } + if errors != pod.ErrorLines { + t.Errorf("%s/%s: %d error lines, want %d", svc.Name, pod.Name, errors, pod.ErrorLines) + } + } + } + if i != len(streams) { + t.Errorf("%d streams, want %d", len(streams), i) + } +} diff --git a/test/integration/testdata/logs/label_pod_values.json b/test/integration/testdata/logs/label_pod_values.json new file mode 100644 index 000000000..59a4fba03 --- /dev/null +++ b/test/integration/testdata/logs/label_pod_values.json @@ -0,0 +1,8 @@ +{ + "data": [ + "p1", + "p2", + "p3" + ], + "status": "success" +} diff --git a/test/integration/testdata/logs/query_count_by_pod.json b/test/integration/testdata/logs/query_count_by_pod.json new file mode 100644 index 000000000..ebe9af10e --- /dev/null +++ b/test/integration/testdata/logs/query_count_by_pod.json @@ -0,0 +1,48 @@ +{ + "data": { + "result": [ + { + "metric": { + "app": "checkout", + "pod": "p1" + }, + "value": [ + "+300s", + "4" + ] + }, + { + "metric": { + "app": "checkout", + "pod": "p2" + }, + "value": [ + "+300s", + "7" + ] + }, + { + "metric": { + "app": "checkout", + "pod": "p3" + }, + "value": [ + "+300s", + "1" + ] + }, + { + "metric": { + "app": "payments", + "pod": "p1" + }, + "value": [ + "+300s", + "5" + ] + } + ], + "resultType": "vector" + }, + "status": "success" +} diff --git a/test/integration/testdata/logs/query_range_json_filter.json b/test/integration/testdata/logs/query_range_json_filter.json new file mode 100644 index 000000000..4eceedf02 --- /dev/null +++ b/test/integration/testdata/logs/query_range_json_filter.json @@ -0,0 +1,116 @@ +{ + "data": { + "result": [ + { + "stream": { + "app": "checkout", + "latency_ms": "524", + "level": "error", + "m2_run": "RUN", + "msg": "payment declined", + "pod": "p2", + "seq": "6", + "service_name": "checkout" + }, + "values": [ + [ + "+60s", + "{\"level\":\"error\",\"msg\":\"payment declined\",\"latency_ms\":524,\"seq\":6}" + ] + ] + }, + { + "stream": { + "app": "checkout", + "latency_ms": "573", + "level": "error", + "m2_run": "RUN", + "msg": "inventory timeout", + "pod": "p2", + "seq": "2", + "service_name": "checkout" + }, + "values": [ + [ + "+20s", + "{\"level\":\"error\",\"msg\":\"inventory timeout\",\"latency_ms\":573,\"seq\":2}" + ] + ] + }, + { + "stream": { + "app": "checkout", + "latency_ms": "907", + "level": "error", + "m2_run": "RUN", + "msg": "card rejected", + "pod": "p2", + "seq": "3", + "service_name": "checkout" + }, + "values": [ + [ + "+30s", + "{\"level\":\"error\",\"msg\":\"card rejected\",\"latency_ms\":907,\"seq\":3}" + ] + ] + }, + { + "stream": { + "app": "checkout", + "latency_ms": "980", + "level": "error", + "m2_run": "RUN", + "msg": "payment declined", + "pod": "p1", + "seq": "0", + "service_name": "checkout" + }, + "values": [ + [ + "+0s", + "{\"level\":\"error\",\"msg\":\"payment declined\",\"latency_ms\":980,\"seq\":0}" + ] + ] + }, + { + "stream": { + "app": "payments", + "latency_ms": "130", + "level": "error", + "m2_run": "RUN", + "msg": "card rejected", + "pod": "p1", + "seq": "2", + "service_name": "payments" + }, + "values": [ + [ + "+20s", + "{\"level\":\"error\",\"msg\":\"card rejected\",\"latency_ms\":130,\"seq\":2}" + ] + ] + }, + { + "stream": { + "app": "payments", + "latency_ms": "446", + "level": "error", + "m2_run": "RUN", + "msg": "inventory timeout", + "pod": "p1", + "seq": "4", + "service_name": "payments" + }, + "values": [ + [ + "+40s", + "{\"level\":\"error\",\"msg\":\"inventory timeout\",\"latency_ms\":446,\"seq\":4}" + ] + ] + } + ], + "resultType": "streams" + }, + "status": "success" +} diff --git a/test/integration/testdata/logs/query_range_streams.json b/test/integration/testdata/logs/query_range_streams.json new file mode 100644 index 000000000..4036228e6 --- /dev/null +++ b/test/integration/testdata/logs/query_range_streams.json @@ -0,0 +1,116 @@ +{ + "data": { + "result": [ + { + "stream": { + "app": "checkout", + "m2_run": "RUN", + "pod": "p1", + "service_name": "checkout" + }, + "values": [ + [ + "+0s", + "{\"level\":\"error\",\"msg\":\"payment declined\",\"latency_ms\":980,\"seq\":0}" + ], + [ + "+10s", + "{\"level\":\"info\",\"msg\":\"item reserved\",\"latency_ms\":81,\"seq\":1}" + ], + [ + "+20s", + "{\"level\":\"info\",\"msg\":\"order created\",\"latency_ms\":237,\"seq\":2}" + ], + [ + "+30s", + "{\"level\":\"info\",\"msg\":\"item reserved\",\"latency_ms\":348,\"seq\":3}" + ] + ] + }, + { + "stream": { + "app": "checkout", + "m2_run": "RUN", + "pod": "p2", + "service_name": "checkout" + }, + "values": [ + [ + "+0s", + "{\"level\":\"info\",\"msg\":\"order created\",\"latency_ms\":503,\"seq\":0}" + ], + [ + "+10s", + "{\"level\":\"info\",\"msg\":\"cart updated\",\"latency_ms\":187,\"seq\":1}" + ], + [ + "+20s", + "{\"level\":\"error\",\"msg\":\"inventory timeout\",\"latency_ms\":573,\"seq\":2}" + ], + [ + "+30s", + "{\"level\":\"error\",\"msg\":\"card rejected\",\"latency_ms\":907,\"seq\":3}" + ], + [ + "+40s", + "{\"level\":\"info\",\"msg\":\"request served\",\"latency_ms\":199,\"seq\":4}" + ], + [ + "+50s", + "{\"level\":\"info\",\"msg\":\"cart updated\",\"latency_ms\":403,\"seq\":5}" + ], + [ + "+60s", + "{\"level\":\"error\",\"msg\":\"payment declined\",\"latency_ms\":524,\"seq\":6}" + ] + ] + }, + { + "stream": { + "app": "checkout", + "m2_run": "RUN", + "pod": "p3", + "service_name": "checkout" + }, + "values": [ + [ + "+0s", + "{\"level\":\"info\",\"msg\":\"item reserved\",\"latency_ms\":245,\"seq\":0}" + ] + ] + }, + { + "stream": { + "app": "payments", + "m2_run": "RUN", + "pod": "p1", + "service_name": "payments" + }, + "values": [ + [ + "+0s", + "{\"level\":\"info\",\"msg\":\"order created\",\"latency_ms\":931,\"seq\":0}" + ], + [ + "+10s", + "{\"level\":\"info\",\"msg\":\"item reserved\",\"latency_ms\":492,\"seq\":1}" + ], + [ + "+20s", + "{\"level\":\"error\",\"msg\":\"card rejected\",\"latency_ms\":130,\"seq\":2}" + ], + [ + "+30s", + "{\"level\":\"info\",\"msg\":\"request served\",\"latency_ms\":987,\"seq\":3}" + ], + [ + "+40s", + "{\"level\":\"error\",\"msg\":\"inventory timeout\",\"latency_ms\":446,\"seq\":4}" + ] + ] + } + ], + "resultType": "streams" + }, + "status": "success" +} diff --git a/test/integration/testdata/logs/series.json b/test/integration/testdata/logs/series.json new file mode 100644 index 000000000..0cc430881 --- /dev/null +++ b/test/integration/testdata/logs/series.json @@ -0,0 +1,29 @@ +{ + "data": [ + { + "app": "checkout", + "m2_run": "RUN", + "pod": "p1", + "service_name": "checkout" + }, + { + "app": "checkout", + "m2_run": "RUN", + "pod": "p2", + "service_name": "checkout" + }, + { + "app": "checkout", + "m2_run": "RUN", + "pod": "p3", + "service_name": "checkout" + }, + { + "app": "payments", + "m2_run": "RUN", + "pod": "p1", + "service_name": "payments" + } + ], + "status": "success" +} From f88fec0500c12c49ca418c326e5fec46ae203721 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Tue, 24 Nov 2026 21:17:39 +0000 Subject: [PATCH 04/11] test(integration): sort label values and decode pinned responses strictly (M2 2/4, #920) Review of #1061: the label values come from SELECT DISTINCT without ORDER BY, so they are sorted before comparing. The pinned responses are decoded strictly: an undeclared field or data after the response fails, and log entries and vector samples must have exactly two elements. gigapipe.log and gigapipe.pid, created by make integration-start, are ignored. --- .gitignore | 2 + test/integration/logs_roundtrip_test.go | 174 +++++++++++++++++------- 2 files changed, 127 insertions(+), 49 deletions(-) diff --git a/.gitignore b/.gitignore index 2f1bf37e4..d38d2629d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ /.claude/ /.superpowers/ /gigapipe +/gigapipe.log +/gigapipe.pid diff --git a/test/integration/logs_roundtrip_test.go b/test/integration/logs_roundtrip_test.go index 4083e2ed2..032730a75 100644 --- a/test/integration/logs_roundtrip_test.go +++ b/test/integration/logs_roundtrip_test.go @@ -89,21 +89,9 @@ func TestLogsRoundTrip(t *testing.T) { t.Run("count_over_time per app and pod", func(t *testing.T) { q := fmt.Sprintf("sum by (app, pod) (count_over_time(%s[1h]))", selector) raw := apiGet(t, "/loki/api/v1/query", url.Values{"query": {q}, "time": {nanos(to)}}) - var resp struct { - Data struct { - ResultType string `json:"resultType"` - Result []struct { - Metric map[string]string `json:"metric"` - Value [2]any `json:"value"` - } `json:"result"` - } `json:"data"` - } - mustUnmarshal(t, raw, &resp) - if resp.Data.ResultType != "vector" { - t.Fatalf("resultType = %q, want vector", resp.Data.ResultType) - } + _, samples := decodeVector(t, raw) got := map[string]string{} - for _, r := range resp.Data.Result { + for _, r := range samples { got[r.Metric["app"]+"/"+r.Metric["pod"]] = fmt.Sprint(r.Value[1]) } want := map[string]string{} @@ -136,10 +124,8 @@ func TestLogsRoundTrip(t *testing.T) { t.Run("label values of pod", func(t *testing.T) { raw := apiGet(t, "/loki/api/v1/label/pod/values", url.Values{"query": {selector}, "start": {nanos(from)}, "end": {nanos(to)}}) - var resp struct { - Data []string `json:"data"` - } - mustUnmarshal(t, raw, &resp) + var resp valuesResponse + strictUnmarshal(t, raw, &resp) var want []string for _, s := range streams { if !slices.Contains(want, s.Labels["pod"]) { @@ -152,16 +138,14 @@ func TestLogsRoundTrip(t *testing.T) { if !slices.Equal(got, want) { t.Errorf("pod values = %v, want %v", got, want) } - assertPinned(t, "logs/label_pod_values.json", norm.generic(t, raw)) + assertPinned(t, "logs/label_pod_values.json", norm.labelValues(t, raw)) }) t.Run("series lists every stream", func(t *testing.T) { raw := apiGet(t, "/loki/api/v1/series", url.Values{"match[]": {selector}, "start": {nanos(from)}, "end": {nanos(to)}}) - var resp struct { - Data []map[string]string `json:"data"` - } - mustUnmarshal(t, raw, &resp) + var resp seriesResponse + strictUnmarshal(t, raw, &resp) var got, want []string for _, s := range resp.Data { got = append(got, labelKey(s)) @@ -207,24 +191,103 @@ func expectedStreams(streams []seed.LogStream, keep func(seed.LogLine) bool) map return out } +// lokiStream is one stream of a streams response, with its [timestamp, +// line] entries. type lokiStream struct { Stream map[string]string `json:"stream"` Values [][2]string `json:"values"` } -func decodeStreams(t *testing.T, raw []byte) []lokiStream { +// The response types below list every field gigapipe sends and are decoded +// strictly (strictUnmarshal), so a new field fails the decoding, and a field +// that goes missing leaves an empty value that no longer matches the pin. +// Entries are decoded as slices and checked to have exactly two elements, so +// an entry with a third element isn't cut to fit. + +type streamsResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Stream map[string]string `json:"stream"` + Values [][]string `json:"values"` + } `json:"result"` + } `json:"data"` +} + +type vectorResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Value []any `json:"value"` + } `json:"result"` + } `json:"data"` +} + +type seriesResponse struct { + Status string `json:"status"` + Data []map[string]string `json:"data"` +} + +type valuesResponse struct { + Status string `json:"status"` + Data []string `json:"data"` +} + +// decodeStreamsResponse decodes a streams response strictly and returns its +// status and streams. +func decodeStreamsResponse(t *testing.T, raw []byte) (string, []lokiStream) { t.Helper() - var resp struct { - Data struct { - ResultType string `json:"resultType"` - Result []lokiStream `json:"result"` - } `json:"data"` - } - mustUnmarshal(t, raw, &resp) + var resp streamsResponse + strictUnmarshal(t, raw, &resp) if resp.Data.ResultType != "streams" { t.Fatalf("resultType = %q, want streams", resp.Data.ResultType) } - return resp.Data.Result + out := make([]lokiStream, len(resp.Data.Result)) + for i, r := range resp.Data.Result { + values := make([][2]string, len(r.Values)) + for j, v := range r.Values { + if len(v) != 2 { + t.Fatalf("stream %v entry %d has %d elements, want 2 (timestamp, line): %q", r.Stream, j, len(v), v) + } + values[j] = [2]string{v[0], v[1]} + } + out[i] = lokiStream{Stream: r.Stream, Values: values} + } + return resp.Status, out +} + +func decodeStreams(t *testing.T, raw []byte) []lokiStream { + t.Helper() + _, streams := decodeStreamsResponse(t, raw) + return streams +} + +// vectorSample is one sample of a vector response: [time, value]. +type vectorSample struct { + Metric map[string]string `json:"metric"` + Value [2]any `json:"value"` +} + +// decodeVector decodes a vector response strictly and returns its status and +// samples. +func decodeVector(t *testing.T, raw []byte) (string, []vectorSample) { + t.Helper() + var resp vectorResponse + strictUnmarshal(t, raw, &resp) + if resp.Data.ResultType != "vector" { + t.Fatalf("resultType = %q, want vector", resp.Data.ResultType) + } + out := make([]vectorSample, len(resp.Data.Result)) + for i, r := range resp.Data.Result { + if len(r.Value) != 2 { + t.Fatalf("sample %v has %d elements, want 2 (time, value): %v", r.Metric, len(r.Value), r.Value) + } + out[i] = vectorSample{Metric: r.Metric, Value: [2]any{r.Value[0], r.Value[1]}} + } + return resp.Status, out } // assertStreams compares a streams response with want, by label set, with the @@ -345,6 +408,20 @@ func mustUnmarshal(t *testing.T, raw []byte, v any) { } } +// strictUnmarshal decodes a response, failing on a field v doesn't declare +// or on data after the response. +func strictUnmarshal(t *testing.T, raw []byte, v any) { + t.Helper() + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(v); err != nil { + t.Fatalf("decode %q: %v", raw, err) + } + if dec.More() { + t.Fatalf("decode %q: data after the response", raw) + } +} + // normalizer replaces the values that differ between runs with fixed ones, so // a response can be compared with its pinned copy: the run label value becomes // "RUN" and timestamps become offsets from the fixture start, such as "+10s". @@ -379,7 +456,8 @@ func (n normalizer) streams(t *testing.T, raw []byte) any { Result []lokiStream `json:"result"` } `json:"data"` } - mustUnmarshal(t, raw, &resp) + resp.Data.ResultType = "streams" + resp.Status, resp.Data.Result = decodeStreamsResponse(t, raw) for i, r := range resp.Data.Result { r.Stream = n.labels(r.Stream) for j, v := range r.Values { @@ -403,14 +481,12 @@ func (n normalizer) vector(t *testing.T, raw []byte, evalTime time.Time) any { var resp struct { Status string `json:"status"` Data struct { - ResultType string `json:"resultType"` - Result []struct { - Metric map[string]string `json:"metric"` - Value [2]any `json:"value"` - } `json:"result"` + ResultType string `json:"resultType"` + Result []vectorSample `json:"result"` } `json:"data"` } - mustUnmarshal(t, raw, &resp) + resp.Data.ResultType = "vector" + resp.Status, resp.Data.Result = decodeVector(t, raw) for i, r := range resp.Data.Result { ts, ok := r.Value[0].(float64) if !ok { @@ -432,11 +508,8 @@ func (n normalizer) vector(t *testing.T, raw []byte, evalTime time.Time) any { // series normalizes a series response. func (n normalizer) series(t *testing.T, raw []byte) any { t.Helper() - var resp struct { - Status string `json:"status"` - Data []map[string]string `json:"data"` - } - mustUnmarshal(t, raw, &resp) + var resp seriesResponse + strictUnmarshal(t, raw, &resp) for i, s := range resp.Data { resp.Data[i] = n.labels(s) } @@ -444,12 +517,15 @@ func (n normalizer) series(t *testing.T, raw []byte) any { return resp } -// generic decodes a response that has no run-specific values. -func (n normalizer) generic(t *testing.T, raw []byte) any { +// labelValues normalizes a label values response. The values come from a +// SELECT DISTINCT without ORDER BY, so their order is not defined: they are +// sorted. +func (n normalizer) labelValues(t *testing.T, raw []byte) any { t.Helper() - var v any - mustUnmarshal(t, raw, &v) - return v + var resp valuesResponse + strictUnmarshal(t, raw, &resp) + sort.Strings(resp.Data) + return resp } // assertPinned compares got, once encoded as JSON, with the pinned file under From dc6c8f43b56da1f017e8bc89c17551cb8e3fcead Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Fri, 30 Oct 2026 16:04:38 +0000 Subject: [PATCH 05/11] test(integration): write-read cases for metrics, traces and profiles (M2 3/4, #920) Extend the seed with the other three signals, all derived from the same declaration of services and pods: - metrics: per pod, an http_requests_total counter growing by RequestsPerScrape at every 15s scrape and a process_resident_memory_bytes gauge, sent as a Prometheus remote-write request (snappy protobuf) - traces: per checkout pod, a POST /checkout -> charge -> INSERT payments trace across both services, sent as OTLP/HTTP protobuf; trace IDs are derived from the run, so runs never share one - profiles: per pod, three consecutive 10s CPU profiles uploaded to /ingest the way the Pyroscope Go SDK uploads them (multipart pprof, name "{labels}") TestMetricsRoundTrip, TestTracesRoundTrip and TestProfilesRoundTrip read them back the way their clients do: the Prometheus query API; the Tempo API as Grafana's Tempo data source uses it (trace by ID as protobuf, TraceQL search, tag names and values); the Pyroscope Connect API as Grafana's Pyroscope data source uses it, plus /pyroscope/render and /pyroscope/render-diff. Every value is checked against the fixture, one named case each. Pinned responses under testdata/{metrics,traces,profiles} follow the same rules as the logs pins: run-specific values normalized, maintained by hand. The rate query is checked with a 1e-9 tolerance and not pinned, since its last digits depend on the order the per-pod rates are added. If data does not show up within 30s, the tests log it and still run every named case, so a broken ingest path reports which answers are wrong. --- test/integration/metrics_roundtrip_test.go | 389 ++++++++++++++++++ test/integration/profiles_roundtrip_test.go | 333 +++++++++++++++ test/integration/seed/seed.go | 328 ++++++++++++++- test/integration/seed/seed_test.go | 180 ++++++++ .../testdata/metrics/query_counter.json | 60 +++ .../testdata/metrics/query_range_total.json | 62 +++ test/integration/testdata/metrics/series.json | 61 +++ .../testdata/profiles/flamegraph_cpu.json | 60 +++ .../testdata/profiles/render_cpu.json | 64 +++ .../testdata/profiles/render_diff_cpu.json | 80 ++++ test/integration/testdata/traces/search.json | 169 ++++++++ test/integration/traces_roundtrip_test.go | 362 ++++++++++++++++ 12 files changed, 2139 insertions(+), 9 deletions(-) create mode 100644 test/integration/metrics_roundtrip_test.go create mode 100644 test/integration/profiles_roundtrip_test.go create mode 100644 test/integration/testdata/metrics/query_counter.json create mode 100644 test/integration/testdata/metrics/query_range_total.json create mode 100644 test/integration/testdata/metrics/series.json create mode 100644 test/integration/testdata/profiles/flamegraph_cpu.json create mode 100644 test/integration/testdata/profiles/render_cpu.json create mode 100644 test/integration/testdata/profiles/render_diff_cpu.json create mode 100644 test/integration/testdata/traces/search.json create mode 100644 test/integration/traces_roundtrip_test.go diff --git a/test/integration/metrics_roundtrip_test.go b/test/integration/metrics_roundtrip_test.go new file mode 100644 index 000000000..c074fece0 --- /dev/null +++ b/test/integration/metrics_roundtrip_test.go @@ -0,0 +1,389 @@ +//go:build integration + +// Write-read round trip for metrics (M2, #920): the seed fixture's metrics are +// sent as a Prometheus remote-write request and read back through the +// Prometheus query API, each answer checked against the fixture. See +// logs_roundtrip_test.go for the pinned responses. + +package integration + +import ( + "bytes" + "fmt" + "io" + "math" + "net/http" + "net/url" + "slices" + "sort" + "strconv" + "testing" + "time" + + "github.com/metrico/qryn/v5/test/integration/seed" +) + +func TestMetricsRoundTrip(t *testing.T) { + run := fmt.Sprintf("metrics-%d", time.Now().UnixNano()) + start := time.Now().Add(-15 * time.Minute).Truncate(time.Minute) + fixture := seed.Default(run, start) + series := fixture.Metrics() + // The last scrape: instant queries are evaluated there, like a dashboard + // refreshed right after it. + end := start.Add((seed.Scrapes - 1) * seed.ScrapeInterval) + runMatcher := fmt.Sprintf("%s=%q", seed.RunLabel, run) + norm := normalizer{run: run, start: start} + + postRemoteWrite(t, seed.PromRemoteWrite(series)) + waitForLastSamples(t, fmt.Sprintf("http_requests_total{%s}", runMatcher), end, len(series)/2) + + t.Run("counter value per pod at the last scrape", func(t *testing.T) { + raw := apiGet(t, "/api/v1/query", url.Values{ + "query": {fmt.Sprintf("http_requests_total{%s}", runMatcher)}, + "time": {unixSeconds(end)}, + }) + got := vectorByLabels(t, raw) + want := map[string]float64{} + for _, s := range series { + if s.Labels["__name__"] == "http_requests_total" { + want[labelKey(withServiceName(s.Labels))] = s.Samples[len(s.Samples)-1].Value + } + } + assertFloatMap(t, got, want, 0) + assertPinned(t, "metrics/query_counter.json", norm.vector(t, raw, end)) + }) + + ratePerApp := func() map[string]float64 { + want := map[string]float64{} + for _, svc := range fixture.Services { + for _, pod := range svc.Pods { + want[labelKey(map[string]string{"app": svc.Name})] += float64(pod.RequestsPerScrape) / seed.ScrapeInterval.Seconds() + } + } + return want + } + rateQuery := fmt.Sprintf("sum by (app) (rate(http_requests_total{%s}[5m]))", runMatcher) + + t.Run("requests per second per app", func(t *testing.T) { + raw := apiGet(t, "/api/v1/query", url.Values{"query": {rateQuery}, "time": {unixSeconds(end)}}) + assertFloatMap(t, vectorByLabels(t, raw), ratePerApp(), 1e-9) + }) + + t.Run("requests per second over time", func(t *testing.T) { + from := start.Add(5 * time.Minute) + raw := apiGet(t, "/api/v1/query_range", url.Values{ + "query": {rateQuery}, + "start": {unixSeconds(from)}, + "end": {unixSeconds(end)}, + "step": {"60"}, + }) + want := ratePerApp() + for key, points := range matrixByLabels(t, raw) { + wantRate, ok := want[key] + if !ok { + t.Errorf("unexpected series %s", key) + continue + } + // One point per step from the start of the range up to its end. + if wantPoints := int(end.Sub(from)/time.Minute) + 1; len(points) != wantPoints { + t.Errorf("%s: %d points, want %d", key, len(points), wantPoints) + } + for _, p := range points { + if math.Abs(p.value-wantRate) > 1e-9 { + t.Errorf("%s at %v: %v requests/s, want %v", key, p.time, p.value, wantRate) + } + } + delete(want, key) + } + for key := range want { + t.Errorf("missing series %s", key) + } + }) + + t.Run("total requests per app over time", func(t *testing.T) { + from := start.Add(5 * time.Minute) + raw := apiGet(t, "/api/v1/query_range", url.Values{ + "query": {fmt.Sprintf("sum by (app) (http_requests_total{%s})", runMatcher)}, + "start": {unixSeconds(from)}, + "end": {unixSeconds(end)}, + "step": {"60"}, + }) + // Each step falls on a scrape, so a pod contributes the sample taken at + // that step. + want := map[string][]matrixPoint{} + for at := from; !at.After(end); at = at.Add(time.Minute) { + scrape := int(at.Sub(start) / seed.ScrapeInterval) + perApp := map[string]float64{} + for _, s := range series { + if s.Labels["__name__"] == "http_requests_total" { + perApp[s.Labels["app"]] += s.Samples[scrape].Value + } + } + for app, v := range perApp { + key := labelKey(map[string]string{"app": app}) + want[key] = append(want[key], matrixPoint{float64(at.Unix()), v}) + } + } + got := matrixByLabels(t, raw) + for key, points := range want { + if !slices.Equal(got[key], points) { + t.Errorf("%s:\n got %v\nwant %v", key, got[key], points) + } + } + for key := range got { + if _, ok := want[key]; !ok { + t.Errorf("unexpected series %s", key) + } + } + assertPinned(t, "metrics/query_range_total.json", norm.matrix(t, raw)) + }) + + t.Run("peak memory per pod over ten minutes", func(t *testing.T) { + raw := apiGet(t, "/api/v1/query", url.Values{ + "query": {fmt.Sprintf("max_over_time(process_resident_memory_bytes{%s}[10m])", runMatcher)}, + "time": {unixSeconds(end)}, + }) + want := map[string]float64{} + for _, s := range series { + if s.Labels["__name__"] != "process_resident_memory_bytes" { + continue + } + peak := 0.0 + for _, sample := range s.Samples { + peak = max(peak, sample.Value) + } + // *_over_time functions drop the metric name. + labels := withServiceName(s.Labels) + delete(labels, "__name__") + want[labelKey(labels)] = peak + } + assertFloatMap(t, vectorByLabels(t, raw), want, 0) + }) + + matchParams := url.Values{ + "match[]": {fmt.Sprintf("{%s}", runMatcher)}, + "start": {unixSeconds(start)}, + "end": {unixSeconds(end)}, + } + + t.Run("series lists every series", func(t *testing.T) { + raw := apiGet(t, "/api/v1/series", matchParams) + var resp struct { + Data []map[string]string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + var got, want []string + for _, s := range resp.Data { + got = append(got, labelKey(s)) + } + for _, s := range series { + want = append(want, labelKey(withServiceName(s.Labels))) + } + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("series:\n got %q\nwant %q", got, want) + } + assertPinned(t, "metrics/series.json", norm.series(t, raw)) + }) + + t.Run("label names", func(t *testing.T) { + raw := apiGet(t, "/api/v1/labels", matchParams) + var resp struct { + Data []string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + got := slices.Clone(resp.Data) + slices.Sort(got) + want := []string{"__name__", "app", seed.RunLabel, "pod", "service_name"} + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("labels = %v, want %v", got, want) + } + }) + + t.Run("label values of pod", func(t *testing.T) { + raw := apiGet(t, "/api/v1/label/pod/values", matchParams) + var resp struct { + Data []string `json:"data"` + } + mustUnmarshal(t, raw, &resp) + var want []string + for _, s := range series { + if !slices.Contains(want, s.Labels["pod"]) { + want = append(want, s.Labels["pod"]) + } + } + got := slices.Clone(resp.Data) + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("pod values = %v, want %v", got, want) + } + }) +} + +func unixSeconds(t time.Time) string { return strconv.FormatInt(t.Unix(), 10) } + +func postRemoteWrite(t *testing.T, body []byte) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, baseURL()+"/api/v1/prom/remote/write", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/x-protobuf") + req.Header.Set("Content-Encoding", "snappy") + req.Header.Set("X-Prometheus-Remote-Write-Version", "0.1.0") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("remote write: status %d, body %q", resp.StatusCode, raw) + } +} + +// waitForLastSamples polls until query, evaluated at the last scrape, returns +// want series, since ingestion is flushed asynchronously. On timeout it only +// logs, so the named checks that follow still run and report what is wrong. +func waitForLastSamples(t *testing.T, query string, at time.Time, want int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := len(vectorByLabels(t, apiGet(t, "/api/v1/query", url.Values{"query": {query}, "time": {unixSeconds(at)}}))) + if got == want { + return + } + if time.Now().After(deadline) { + t.Logf("after 30s %s returns %d series, want %d; checking anyway", query, got, want) + return + } + time.Sleep(500 * time.Millisecond) + } +} + +// vectorByLabels decodes an instant query vector response into values keyed by +// label set. +func vectorByLabels(t *testing.T, raw []byte) map[string]float64 { + t.Helper() + var resp struct { + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Value [2]any `json:"value"` + } `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + if resp.Data.ResultType != "vector" { + t.Fatalf("resultType = %q, want vector", resp.Data.ResultType) + } + out := map[string]float64{} + for _, r := range resp.Data.Result { + out[labelKey(r.Metric)] = parseSampleValue(t, r.Value[1]) + } + return out +} + +type matrixPoint struct { + time float64 + value float64 +} + +// matrixByLabels decodes a range query matrix response into points keyed by +// label set. +func matrixByLabels(t *testing.T, raw []byte) map[string][]matrixPoint { + t.Helper() + var resp struct { + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Values [][2]any `json:"values"` + } `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + if resp.Data.ResultType != "matrix" { + t.Fatalf("resultType = %q, want matrix", resp.Data.ResultType) + } + out := map[string][]matrixPoint{} + for _, r := range resp.Data.Result { + for _, v := range r.Values { + ts, ok := v[0].(float64) + if !ok { + t.Fatalf("point time %v is not a number", v[0]) + } + out[labelKey(r.Metric)] = append(out[labelKey(r.Metric)], matrixPoint{ts, parseSampleValue(t, v[1])}) + } + } + return out +} + +// parseSampleValue parses a sample value, which the Prometheus API encodes as +// a string. +func parseSampleValue(t *testing.T, v any) float64 { + t.Helper() + s, ok := v.(string) + if !ok { + t.Fatalf("sample value %v is not a string", v) + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + t.Fatalf("sample value %q: %v", s, err) + } + return f +} + +func assertFloatMap(t *testing.T, got, want map[string]float64, tolerance float64) { + t.Helper() + for key, w := range want { + g, ok := got[key] + if !ok { + t.Errorf("missing %s (want %v)", key, w) + continue + } + if math.Abs(g-w) > tolerance { + t.Errorf("%s = %v, want %v", key, g, w) + } + } + for key, g := range got { + if _, ok := want[key]; !ok { + t.Errorf("unexpected %s = %v", key, g) + } + } +} + +// matrix normalizes a range query matrix response. +func (n normalizer) matrix(t *testing.T, raw []byte) any { + t.Helper() + var resp struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Values [][2]any `json:"values"` + } `json:"result"` + } `json:"data"` + } + mustUnmarshal(t, raw, &resp) + for i, r := range resp.Data.Result { + r.Metric = n.labels(r.Metric) + for j, v := range r.Values { + ts, ok := v[0].(float64) + if !ok { + t.Fatalf("point time %v is not a number", v[0]) + } + r.Values[j][0] = n.offset(time.Unix(int64(ts), 0)) + } + resp.Data.Result[i] = r + } + sort.Slice(resp.Data.Result, func(i, j int) bool { + return labelKey(resp.Data.Result[i].Metric) < labelKey(resp.Data.Result[j].Metric) + }) + return resp +} diff --git a/test/integration/profiles_roundtrip_test.go b/test/integration/profiles_roundtrip_test.go new file mode 100644 index 000000000..cbb02ab44 --- /dev/null +++ b/test/integration/profiles_roundtrip_test.go @@ -0,0 +1,333 @@ +//go:build integration + +// Write-read round trip for profiles (M2, #920): the seed fixture's CPU +// profiles are uploaded to /ingest the way the Pyroscope Go SDK uploads them, +// and read back through the Connect API Grafana's Pyroscope data source uses +// (profile types, label names and values, flame graph, time series), each +// answer checked against the fixture. See logs_roundtrip_test.go for the +// pinned responses. + +package integration + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strconv" + "testing" + "time" + + querierv1 "github.com/metrico/qryn/v5/reader/prof" + typesv1 "github.com/metrico/qryn/v5/reader/prof/types/v1" + "github.com/metrico/qryn/v5/test/integration/seed" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +const ( + cpuNanosType = "process_cpu:cpu:nanoseconds:cpu:nanoseconds" + cpuSamplesType = "process_cpu:samples:count:cpu:nanoseconds" +) + +func TestProfilesRoundTrip(t *testing.T) { + run := fmt.Sprintf("profiles-%d", time.Now().UnixNano()) + start := time.Now().Add(-10 * time.Minute).Truncate(time.Minute) + fixture := seed.Default(run, start) + profiles := fixture.Profiles() + from, to := start.Add(-time.Minute).UnixMilli(), start.Add(5*time.Minute).UnixMilli() + runSelector := fmt.Sprintf("%s=%q", seed.RunLabel, run) + + // cpu[service][upload] is the CPU time in nanoseconds the fixture records. + cpu := map[string][]int64{} + samples := map[string]int64{} + for i, p := range profiles { + if cpu[p.Service] == nil { + cpu[p.Service] = make([]int64, seed.ProfileUploads) + } + for _, n := range p.Samples { + cpu[p.Service][i%seed.ProfileUploads] += n * int64(seed.CPUPeriod) + samples[p.Service] += n + } + query, contentType, body := fixture.PyroscopeIngest(p) + postIngest(t, query.Encode(), contentType, body) + } + total := func(service string) int64 { + var sum int64 + for _, v := range cpu[service] { + sum += v + } + return sum + } + var all int64 + for svc := range cpu { + all += total(svc) + } + waitForProfiles(t, fmt.Sprintf("{%s}", runSelector), from, to, all) + + t.Run("profile types include CPU", func(t *testing.T) { + var resp querierv1.ProfileTypesResponse + connectCall(t, "ProfileTypes", &querierv1.ProfileTypesRequest{Start: from, End: to}, &resp) + var got []string + for _, pt := range resp.ProfileTypes { + got = append(got, pt.ID) + } + for _, want := range []string{cpuNanosType, cpuSamplesType} { + if !slices.Contains(got, want) { + t.Errorf("profile types %v do not include %q", got, want) + } + } + }) + + t.Run("label names", func(t *testing.T) { + var resp typesv1.LabelNamesResponse + connectCall(t, "LabelNames", &typesv1.LabelNamesRequest{ + Matchers: []string{fmt.Sprintf("{%s}", runSelector)}, Start: from, End: to, + }, &resp) + got := slices.Clone(resp.Names) + slices.Sort(got) + want := []string{seed.RunLabel, "pod", "service_name"} + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("label names = %v, want %v", got, want) + } + }) + + t.Run("service names", func(t *testing.T) { + var resp typesv1.LabelValuesResponse + connectCall(t, "LabelValues", &typesv1.LabelValuesRequest{ + Name: "service_name", Matchers: []string{fmt.Sprintf("{%s}", runSelector)}, Start: from, End: to, + }, &resp) + got := slices.Clone(resp.Names) + slices.Sort(got) + var want []string + for _, svc := range fixture.Services { + want = append(want, svc.Name) + } + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("service names = %v, want %v", got, want) + } + }) + + for _, svc := range fixture.Services { + selector := fmt.Sprintf("{%s, service_name=%q}", runSelector, svc.Name) + + t.Run("flame graph of "+svc.Name, func(t *testing.T) { + graph := mergeStacktraces(t, cpuNanosType, selector, from, to) + if graph.Total != total(svc.Name) { + t.Errorf("CPU time = %dns, want %dns", graph.Total, total(svc.Name)) + } + // Every function the service's stacks sample must appear. + for i, p := range profiles { + if p.Service != svc.Name || i%seed.ProfileUploads != 0 { + continue + } + for _, stack := range p.Stacks { + for _, frame := range stack { + if !slices.Contains(graph.Names, frame) { + t.Errorf("function %q missing from the flame graph names %v", frame, graph.Names) + } + } + } + } + if svc.Name == fixture.Services[0].Name { + raw, err := protojson.Marshal(graph) + if err != nil { + t.Fatal(err) + } + var v any + mustUnmarshal(t, raw, &v) + assertPinned(t, "profiles/flamegraph_cpu.json", v) + } + }) + + t.Run("CPU samples of "+svc.Name, func(t *testing.T) { + if got := mergeStacktraces(t, cpuSamplesType, selector, from, to).Total; got != samples[svc.Name] { + t.Errorf("samples = %d, want %d", got, samples[svc.Name]) + } + }) + } + + // The legacy Pyroscope HTTP API: render merges every profile in the range + // into one flame graph, render-diff compares two ranges. + checkout := fixture.Services[0].Name + renderQuery := fmt.Sprintf("%s{%s, service_name=%q}", cpuNanosType, runSelector, checkout) + + t.Run("render merges every upload of "+checkout, func(t *testing.T) { + raw := apiGet(t, "/pyroscope/render", url.Values{ + "query": {renderQuery}, + "from": {strconv.FormatInt(from, 10)}, + "until": {strconv.FormatInt(to, 10)}, + }) + var resp struct { + Flamebearer struct { + Names []string `json:"names"` + NumTicks int64 `json:"numTicks"` + } `json:"flamebearer"` + } + mustUnmarshal(t, raw, &resp) + if resp.Flamebearer.NumTicks != total(checkout) { + t.Errorf("CPU time = %dns, want %dns", resp.Flamebearer.NumTicks, total(checkout)) + } + for _, frame := range profiles[0].Stacks[0] { + if !slices.Contains(resp.Flamebearer.Names, frame) { + t.Errorf("function %q missing from %v", frame, resp.Flamebearer.Names) + } + } + var v any + mustUnmarshal(t, raw, &v) + assertPinned(t, "profiles/render_cpu.json", v) + }) + + t.Run("render-diff compares the first and the last upload of "+checkout, func(t *testing.T) { + last := start.Add((seed.ProfileUploads - 1) * seed.ProfileInterval) + raw := apiGet(t, "/pyroscope/render-diff", url.Values{ + "leftQuery": {renderQuery}, + "leftFrom": {strconv.FormatInt(start.Add(-5*time.Second).UnixMilli(), 10)}, + "leftUntil": {strconv.FormatInt(start.Add(5*time.Second).UnixMilli(), 10)}, + "rightQuery": {renderQuery}, + "rightFrom": {strconv.FormatInt(last.Add(-5*time.Second).UnixMilli(), 10)}, + "rightUntil": {strconv.FormatInt(last.Add(5*time.Second).UnixMilli(), 10)}, + }) + var resp struct { + LeftTicks int64 `json:"leftTicks"` + RightTicks int64 `json:"rightTicks"` + Metadata struct { + Format string `json:"format"` + } `json:"metadata"` + } + mustUnmarshal(t, raw, &resp) + if want := cpu[checkout][0]; resp.LeftTicks != want { + t.Errorf("left (first upload) CPU time = %dns, want %dns", resp.LeftTicks, want) + } + if want := cpu[checkout][seed.ProfileUploads-1]; resp.RightTicks != want { + t.Errorf("right (last upload) CPU time = %dns, want %dns", resp.RightTicks, want) + } + if resp.Metadata.Format != "double" { + t.Errorf("format = %q, want double", resp.Metadata.Format) + } + var v any + mustUnmarshal(t, raw, &v) + assertPinned(t, "profiles/render_diff_cpu.json", v) + }) + + t.Run("CPU time over time per service", func(t *testing.T) { + var resp querierv1.SelectSeriesResponse + connectCall(t, "SelectSeries", &querierv1.SelectSeriesRequest{ + ProfileTypeID: cpuNanosType, + LabelSelector: fmt.Sprintf("{%s}", runSelector), + Start: start.UnixMilli(), + End: start.Add(seed.ProfileUploads * seed.ProfileInterval).UnixMilli(), + GroupBy: []string{"service_name"}, + Step: seed.ProfileInterval.Seconds(), + }, &resp) + got := map[string][]string{} + for _, s := range resp.Series { + service := "" + for _, l := range s.Labels { + if l.Name == "service_name" { + service = l.Value + } + } + for _, p := range s.Points { + got[service] = append(got[service], fmt.Sprintf("%d@%d", int64(p.Value), p.Timestamp)) + } + } + want := map[string][]string{} + for svc, uploads := range cpu { + for n, v := range uploads { + want[svc] = append(want[svc], fmt.Sprintf("%d@%d", v, start.Add(time.Duration(n)*seed.ProfileInterval).UnixMilli())) + } + } + for svc, points := range want { + if !slices.Equal(got[svc], points) { + t.Errorf("%s: points %v, want %v", svc, got[svc], points) + } + } + for svc := range got { + if _, ok := want[svc]; !ok { + t.Errorf("unexpected series for service %q", svc) + } + } + }) +} + +func postIngest(t *testing.T, query, contentType string, body []byte) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, baseURL()+"/ingest?"+query, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", contentType) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("ingest: status %d, body %q", resp.StatusCode, raw) + } +} + +// connectCall makes a Connect unary call with a protobuf body, as Grafana's +// Pyroscope data source does. +func connectCall(t *testing.T, method string, req, resp proto.Message) { + t.Helper() + raw, err := proto.Marshal(req) + if err != nil { + t.Fatal(err) + } + r, err := http.NewRequest(http.MethodPost, baseURL()+"/querier.v1.QuerierService/"+method, bytes.NewReader(raw)) + if err != nil { + t.Fatal(err) + } + r.Header.Set("Content-Type", "application/proto") + res, err := http.DefaultClient.Do(r) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + if res.StatusCode != http.StatusOK { + t.Fatalf("%s: status %d, body %q", method, res.StatusCode, body) + } + if err := proto.Unmarshal(body, resp); err != nil { + t.Fatalf("%s: decode response: %v", method, err) + } +} + +func mergeStacktraces(t *testing.T, profileType, selector string, from, to int64) *querierv1.FlameGraph { + t.Helper() + var resp querierv1.SelectMergeStacktracesResponse + connectCall(t, "SelectMergeStacktraces", &querierv1.SelectMergeStacktracesRequest{ + ProfileTypeID: profileType, LabelSelector: selector, Start: from, End: to, + }, &resp) + if resp.Flamegraph == nil { + return &querierv1.FlameGraph{} + } + return resp.Flamegraph +} + +// waitForProfiles polls until the flame graph of the selector adds up to want +// nanoseconds of CPU time, since ingestion is flushed asynchronously. On +// timeout it only logs, so the named checks that follow still run and report +// what is wrong. +func waitForProfiles(t *testing.T, selector string, from, to, want int64) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := mergeStacktraces(t, cpuNanosType, selector, from, to).Total + if got == want { + return + } + if time.Now().After(deadline) { + t.Logf("after 30s the flame graph totals %dns, want %dns; checking anyway", got, want) + return + } + time.Sleep(500 * time.Millisecond) + } +} diff --git a/test/integration/seed/seed.go b/test/integration/seed/seed.go index 8fb3de7a1..818377ff4 100644 --- a/test/integration/seed/seed.go +++ b/test/integration/seed/seed.go @@ -10,11 +10,25 @@ package seed import ( + "bytes" + "crypto/sha256" "encoding/json" "fmt" "math/rand/v2" + "mime/multipart" + "net/url" + "sort" "strconv" + "strings" "time" + + "github.com/golang/snappy" + "github.com/google/pprof/profile" + "github.com/metrico/qryn/v5/writer/utils/proto/prompb" + commonv1 "go.opentelemetry.io/proto/otlp/common/v1" + resourcev1 "go.opentelemetry.io/proto/otlp/resource/v1" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" + "google.golang.org/protobuf/proto" ) // RunLabel is the label carrying Fixture.Run on every series written. @@ -36,12 +50,14 @@ type Service struct { Pods []Pod } -// Pod is one log stream of a service: Lines lines, ErrorLines of them at -// level "error" and the rest at level "info". +// Pod is one instance of a service. For logs it is one stream: Lines lines, +// ErrorLines of them at level "error" and the rest at level "info". For +// metrics it serves RequestsPerScrape requests between two scrapes. type Pod struct { - Name string - Lines int - ErrorLines int + Name string + Lines int + ErrorLines int + RequestsPerScrape int } // Default returns the standard fixture used by the integration tests. @@ -51,12 +67,12 @@ func Default(run string, start time.Time) Fixture { Start: start, Services: []Service{ {Name: "checkout", Pods: []Pod{ - {Name: "p1", Lines: 4, ErrorLines: 1}, - {Name: "p2", Lines: 7, ErrorLines: 3}, - {Name: "p3", Lines: 1, ErrorLines: 0}, + {Name: "p1", Lines: 4, ErrorLines: 1, RequestsPerScrape: 3}, + {Name: "p2", Lines: 7, ErrorLines: 3, RequestsPerScrape: 12}, + {Name: "p3", Lines: 1, ErrorLines: 0, RequestsPerScrape: 6}, }}, {Name: "payments", Pods: []Pod{ - {Name: "p1", Lines: 5, ErrorLines: 2}, + {Name: "p1", Lines: 5, ErrorLines: 2, RequestsPerScrape: 9}, }}, }, } @@ -149,3 +165,297 @@ func LokiPushJSON(streams []LogStream) []byte { } return out } + +// ScrapeInterval is the time between consecutive metric samples, as scraped by +// a Prometheus server. +const ScrapeInterval = 15 * time.Second + +// Scrapes is the number of samples in each metric series: ten minutes. +const Scrapes = 40 + +// MetricSeries is one time series as sent to gigapipe. Labels include +// __name__. +type MetricSeries struct { + Labels map[string]string + Samples []MetricSample +} + +// MetricSample is one sample of a series. +type MetricSample struct { + Time time.Time + Value float64 +} + +// Metrics returns two series per pod, in declaration order: the counter +// http_requests_total, which grows by RequestsPerScrape at every scrape, and +// the gauge process_resident_memory_bytes. Sample i is at +// Start + i*ScrapeInterval. +func (f Fixture) Metrics() []MetricSeries { + rng := rand.New(rand.NewPCG(920, 3)) + var series []MetricSeries + for _, svc := range f.Services { + for _, pod := range svc.Pods { + labels := func(name string) map[string]string { + return map[string]string{"__name__": name, RunLabel: f.Run, "app": svc.Name, "pod": pod.Name} + } + requests := MetricSeries{Labels: labels("http_requests_total")} + memory := MetricSeries{Labels: labels("process_resident_memory_bytes")} + counter := float64(1000 + rng.IntN(9000)) + for i := range Scrapes { + at := f.Start.Add(time.Duration(i) * ScrapeInterval) + requests.Samples = append(requests.Samples, MetricSample{at, counter + float64(i*pod.RequestsPerScrape)}) + memory.Samples = append(memory.Samples, MetricSample{at, float64(100<<20 + rng.IntN(100<<20))}) + } + series = append(series, requests, memory) + } + } + return series +} + +// PromRemoteWrite encodes series as a Prometheus remote-write request body: +// a snappy-compressed WriteRequest protobuf, labels sorted by name as +// Prometheus sends them. +func PromRemoteWrite(series []MetricSeries) []byte { + req := &prompb.WriteRequest{} + for _, s := range series { + ts := &prompb.TimeSeries{} + names := make([]string, 0, len(s.Labels)) + for name := range s.Labels { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + ts.Labels = append(ts.Labels, &prompb.Label{Name: name, Value: s.Labels[name]}) + } + for _, sample := range s.Samples { + ts.Samples = append(ts.Samples, &prompb.Sample{Value: sample.Value, Timestamp: sample.Time.UnixMilli()}) + } + req.Timeseries = append(req.Timeseries, ts) + } + raw, err := proto.Marshal(req) + if err != nil { + panic(err) + } + return snappy.Encode(nil, raw) +} + +// Trace is one request through the system. +type Trace struct { + ID []byte + Spans []Span +} + +// Span is one span of a trace. Service and Pod become the resource attributes +// service.name and k8s.pod.name; Attributes are span attributes. +type Span struct { + ID []byte + ParentID []byte + Service string + Pod string + Name string + Kind tracev1.Span_SpanKind + Start time.Time + End time.Time + Attributes map[string]string +} + +// Traces returns one checkout request per pod of the first service, each +// calling the first pod of the second service, which writes to its database: +// +// POST /checkout (first service) -> charge (second service) -> INSERT payments +// +// Trace i starts at Start + i*LineInterval. IDs are derived from Run, so +// traces of different runs never share an ID; everything else is the same in +// every run. +func (f Fixture) Traces() []Trace { + if len(f.Services) < 2 || len(f.Services[1].Pods) == 0 { + panic("seed: traces need a second service with a pod") + } + rng := rand.New(rand.NewPCG(920, 4)) + frontend, backend := f.Services[0], f.Services[1] + var traces []Trace + for i, pod := range frontend.Pods { + id := func(name string, size int) []byte { + sum := sha256.Sum256([]byte(fmt.Sprintf("%s/%d/%s", f.Run, i, name))) + return sum[:size] + } + start := f.Start.Add(time.Duration(i) * LineInterval) + root := time.Duration(100+rng.IntN(200)) * time.Millisecond + charge := time.Duration(40+rng.IntN(50)) * time.Millisecond + insert := time.Duration(5+rng.IntN(20)) * time.Millisecond + traces = append(traces, Trace{ID: id("trace", 16), Spans: []Span{ + { + ID: id("root", 8), Service: frontend.Name, Pod: pod.Name, Name: "POST /checkout", + Kind: tracev1.Span_SPAN_KIND_SERVER, Start: start, End: start.Add(root), + Attributes: map[string]string{"http.request.method": "POST", "http.route": "/checkout"}, + }, + { + ID: id("charge", 8), ParentID: id("root", 8), Service: backend.Name, Pod: backend.Pods[0].Name, Name: "charge", + Kind: tracev1.Span_SPAN_KIND_SERVER, Start: start.Add(10 * time.Millisecond), End: start.Add(10*time.Millisecond + charge), + }, + { + ID: id("insert", 8), ParentID: id("charge", 8), Service: backend.Name, Pod: backend.Pods[0].Name, Name: "INSERT payments", + Kind: tracev1.Span_SPAN_KIND_CLIENT, Start: start.Add(20 * time.Millisecond), End: start.Add(20*time.Millisecond + insert), + Attributes: map[string]string{"db.system": "postgresql", "db.operation.name": "INSERT"}, + }, + }}) + } + return traces +} + +// OTLPTraces encodes traces as an OTLP/HTTP traces request body (protobuf), +// one ResourceSpans per span with the resource attributes service.name, +// k8s.pod.name and RunLabel. +func (f Fixture) OTLPTraces(traces []Trace) []byte { + str := func(k, v string) *commonv1.KeyValue { + return &commonv1.KeyValue{Key: k, Value: &commonv1.AnyValue{Value: &commonv1.AnyValue_StringValue{StringValue: v}}} + } + req := &tracev1.TracesData{} + for _, tr := range traces { + for _, sp := range tr.Spans { + span := &tracev1.Span{ + TraceId: tr.ID, SpanId: sp.ID, ParentSpanId: sp.ParentID, Name: sp.Name, Kind: sp.Kind, + StartTimeUnixNano: uint64(sp.Start.UnixNano()), EndTimeUnixNano: uint64(sp.End.UnixNano()), + } + keys := make([]string, 0, len(sp.Attributes)) + for k := range sp.Attributes { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + span.Attributes = append(span.Attributes, str(k, sp.Attributes[k])) + } + req.ResourceSpans = append(req.ResourceSpans, &tracev1.ResourceSpans{ + Resource: &resourcev1.Resource{Attributes: []*commonv1.KeyValue{ + str("service.name", sp.Service), str("k8s.pod.name", sp.Pod), str(RunLabel, f.Run), + }}, + ScopeSpans: []*tracev1.ScopeSpans{{Spans: []*tracev1.Span{span}}}, + }) + } + } + raw, err := proto.Marshal(req) + if err != nil { + panic(err) + } + return raw +} + +// ProfileInterval is the length of one CPU profile, as uploaded by the +// Pyroscope Go SDK. +const ProfileInterval = 10 * time.Second + +// ProfileUploads is the number of consecutive profiles each pod uploads. +const ProfileUploads = 3 + +// CPUPeriod is the CPU sampling period: 100 samples per second. +const CPUPeriod = 10 * time.Millisecond + +// stacks lists, per service position in the declaration, the call stacks its +// CPU profiles sample, leaf first. +var stacks = [][][]string{ + { + {"main.chargePayment", "main.handleCheckout", "net/http.HandlerFunc.ServeHTTP", "main.main"}, + {"encoding/json.Marshal", "main.handleCheckout", "net/http.HandlerFunc.ServeHTTP", "main.main"}, + {"main.handleCheckout", "net/http.HandlerFunc.ServeHTTP", "main.main"}, + }, + { + {"database/sql.(*DB).ExecContext", "main.handleCharge", "net/http.HandlerFunc.ServeHTTP", "main.main"}, + {"main.handleCharge", "net/http.HandlerFunc.ServeHTTP", "main.main"}, + }, +} + +// CPUProfile is one CPU profile upload of a pod. Samples[i] is the number of +// CPU samples taken in Stacks[i]. +type CPUProfile struct { + Service string + Pod string + Start time.Time + Stacks [][]string + Samples []int64 +} + +// Profiles returns ProfileUploads consecutive CPU profiles per pod, in +// declaration order, the first starting at Start. +func (f Fixture) Profiles() []CPUProfile { + if len(f.Services) > len(stacks) { + panic("seed: no profile stacks declared for every service") + } + rng := rand.New(rand.NewPCG(920, 5)) + var out []CPUProfile + for i, svc := range f.Services { + for _, pod := range svc.Pods { + for n := range ProfileUploads { + p := CPUProfile{Service: svc.Name, Pod: pod.Name, Start: f.Start.Add(time.Duration(n) * ProfileInterval), Stacks: stacks[i]} + for range stacks[i] { + p.Samples = append(p.Samples, int64(5+rng.IntN(60))) + } + out = append(out, p) + } + } + } + return out +} + +// PyroscopeIngest returns the query string and multipart body the Pyroscope Go +// SDK sends to /ingest for p: a gzipped pprof CPU profile with samples/count +// and cpu/nanoseconds values, and the labels RunLabel and pod. +func (f Fixture) PyroscopeIngest(p CPUProfile) (url.Values, string, []byte) { + prof := &profile.Profile{ + SampleType: []*profile.ValueType{{Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "nanoseconds"}}, + PeriodType: &profile.ValueType{Type: "cpu", Unit: "nanoseconds"}, + Period: int64(CPUPeriod), + TimeNanos: p.Start.UnixNano(), + DurationNanos: int64(ProfileInterval), + } + locations := map[string]*profile.Location{} + location := func(name string) *profile.Location { + if l, ok := locations[name]; ok { + return l + } + id := uint64(len(locations) + 1) + fn := &profile.Function{ID: id, Name: name, SystemName: name, Filename: "main.go"} + l := &profile.Location{ID: id, Line: []profile.Line{{Function: fn, Line: int64(10 * id)}}} + locations[name] = l + prof.Function = append(prof.Function, fn) + prof.Location = append(prof.Location, l) + return l + } + for i, stack := range p.Stacks { + sample := &profile.Sample{Value: []int64{p.Samples[i], p.Samples[i] * int64(CPUPeriod)}} + for _, frame := range stack { + sample.Location = append(sample.Location, location(frame)) + } + prof.Sample = append(prof.Sample, sample) + } + var pprof bytes.Buffer + if err := prof.Write(&pprof); err != nil { + panic(err) + } + + var body bytes.Buffer + w := multipart.NewWriter(&body) + if err := w.SetBoundary(strings.Repeat("-", 8) + "seed"); err != nil { + panic(err) + } + part, err := w.CreateFormFile("profile", "profile.pprof") + if err != nil { + panic(err) + } + if _, err := part.Write(pprof.Bytes()); err != nil { + panic(err) + } + if err := w.Close(); err != nil { + panic(err) + } + + query := url.Values{ + "name": {fmt.Sprintf("%s{%s=%s,pod=%s}", p.Service, RunLabel, f.Run, p.Pod)}, + "from": {strconv.FormatInt(p.Start.UnixNano(), 10)}, + "until": {strconv.FormatInt(p.Start.Add(ProfileInterval).UnixNano(), 10)}, + "spyName": {"gospy"}, + "sampleRate": {strconv.Itoa(int(time.Second / CPUPeriod))}, + "units": {"samples"}, + "aggregationType": {"sum"}, + } + return query, w.FormDataContentType(), body.Bytes() +} diff --git a/test/integration/seed/seed_test.go b/test/integration/seed/seed_test.go index b76a20756..b04750a16 100644 --- a/test/integration/seed/seed_test.go +++ b/test/integration/seed/seed_test.go @@ -3,8 +3,13 @@ package seed import ( "bytes" "encoding/json" + "mime" + "mime/multipart" + "slices" "testing" "time" + + "github.com/google/pprof/profile" ) var testStart = time.Date(2026, 1, 2, 3, 4, 0, 0, time.UTC) @@ -76,3 +81,178 @@ func TestLogsMatchDeclaration(t *testing.T) { t.Errorf("%d streams, want %d", len(streams), i) } } + +// TestMetricsAreDeterministic checks that generating the same fixture twice +// gives byte-identical remote-write bodies. +func TestMetricsAreDeterministic(t *testing.T) { + first := PromRemoteWrite(Default("r1", testStart).Metrics()) + second := PromRemoteWrite(Default("r1", testStart).Metrics()) + if !bytes.Equal(first, second) { + t.Fatal("the same fixture produced different remote-write bodies") + } +} + +// TestMetricsMatchDeclaration checks every series against its Pod +// declaration: labels, sample times, counter increments and gauge range. +func TestMetricsMatchDeclaration(t *testing.T) { + f := Default("r1", testStart) + series := f.Metrics() + + i := 0 + for _, svc := range f.Services { + for _, pod := range svc.Pods { + for _, name := range []string{"http_requests_total", "process_resident_memory_bytes"} { + s := series[i] + i++ + want := map[string]string{"__name__": name, RunLabel: "r1", "app": svc.Name, "pod": pod.Name} + if len(s.Labels) != len(want) { + t.Errorf("%s %s/%s: labels = %v, want %v", name, svc.Name, pod.Name, s.Labels, want) + } + for k, v := range want { + if s.Labels[k] != v { + t.Errorf("%s %s/%s: label %s = %q, want %q", name, svc.Name, pod.Name, k, s.Labels[k], v) + } + } + if len(s.Samples) != Scrapes { + t.Fatalf("%s %s/%s: %d samples, want %d", name, svc.Name, pod.Name, len(s.Samples), Scrapes) + } + for n, sample := range s.Samples { + if want := testStart.Add(time.Duration(n) * ScrapeInterval); !sample.Time.Equal(want) { + t.Errorf("%s %s/%s sample %d: time %v, want %v", name, svc.Name, pod.Name, n, sample.Time, want) + } + switch name { + case "http_requests_total": + if n > 0 && sample.Value-s.Samples[n-1].Value != float64(pod.RequestsPerScrape) { + t.Errorf("%s/%s sample %d: counter grew by %v, want %d", svc.Name, pod.Name, n, + sample.Value-s.Samples[n-1].Value, pod.RequestsPerScrape) + } + case "process_resident_memory_bytes": + if sample.Value < 100<<20 || sample.Value >= 200<<20 { + t.Errorf("%s/%s sample %d: memory %v outside [100MiB, 200MiB)", svc.Name, pod.Name, n, sample.Value) + } + } + } + } + } + } + if i != len(series) { + t.Errorf("%d series, want %d", len(series), i) + } +} + +// TestTracesAreDeterministic checks that the same fixture gives byte-identical +// OTLP bodies, and that another run gets different trace IDs. +func TestTracesAreDeterministic(t *testing.T) { + f := Default("r1", testStart) + if !bytes.Equal(f.OTLPTraces(f.Traces()), f.OTLPTraces(f.Traces())) { + t.Fatal("the same fixture produced different OTLP bodies") + } + other := Default("r2", testStart).Traces() + for i, tr := range f.Traces() { + if bytes.Equal(tr.ID, other[i].ID) { + t.Errorf("trace %d has the same ID in runs r1 and r2", i) + } + } +} + +// TestTracesMatchDeclaration checks one trace per pod of the first service, +// each a chain of three spans with every child inside its parent's time. +func TestTracesMatchDeclaration(t *testing.T) { + f := Default("r1", testStart) + traces := f.Traces() + if len(traces) != len(f.Services[0].Pods) { + t.Fatalf("%d traces, want %d", len(traces), len(f.Services[0].Pods)) + } + for i, tr := range traces { + if len(tr.ID) != 16 || len(tr.Spans) != 3 { + t.Fatalf("trace %d: ID of %d bytes and %d spans, want 16 and 3", i, len(tr.ID), len(tr.Spans)) + } + root := tr.Spans[0] + if root.ParentID != nil || root.Service != f.Services[0].Name || root.Pod != f.Services[0].Pods[i].Name { + t.Errorf("trace %d root: parent %x, service %s, pod %s", i, root.ParentID, root.Service, root.Pod) + } + if want := testStart.Add(time.Duration(i) * LineInterval); !root.Start.Equal(want) { + t.Errorf("trace %d starts at %v, want %v", i, root.Start, want) + } + for n := 1; n < len(tr.Spans); n++ { + child, parent := tr.Spans[n], tr.Spans[n-1] + if !bytes.Equal(child.ParentID, parent.ID) { + t.Errorf("trace %d span %q: parent %x, want %x", i, child.Name, child.ParentID, parent.ID) + } + if child.Start.Before(parent.Start) || child.End.After(parent.End) { + t.Errorf("trace %d span %q is not inside its parent", i, child.Name) + } + } + } +} + +// TestProfilesAreDeterministic checks that the same fixture gives +// byte-identical ingest requests. +func TestProfilesAreDeterministic(t *testing.T) { + f := Default("r1", testStart) + first, second := f.Profiles(), f.Profiles() + for i := range first { + q1, ct1, b1 := f.PyroscopeIngest(first[i]) + q2, ct2, b2 := f.PyroscopeIngest(second[i]) + if q1.Encode() != q2.Encode() || ct1 != ct2 || !bytes.Equal(b1, b2) { + t.Fatalf("profile %d: the same fixture produced different requests", i) + } + } +} + +// TestProfilesMatchDeclaration decodes every upload the way the ingest +// endpoint does (multipart field "profile", pprof) and checks it against the +// declaration: one profile per pod and interval, with the declared stacks and +// sample counts. +func TestProfilesMatchDeclaration(t *testing.T) { + f := Default("r1", testStart) + profiles := f.Profiles() + pods := 0 + for _, svc := range f.Services { + pods += len(svc.Pods) + } + if len(profiles) != pods*ProfileUploads { + t.Fatalf("%d profiles, want %d", len(profiles), pods*ProfileUploads) + } + for i, p := range profiles { + if want := testStart.Add(time.Duration(i%ProfileUploads) * ProfileInterval); !p.Start.Equal(want) { + t.Errorf("profile %d starts at %v, want %v", i, p.Start, want) + } + query, contentType, body := f.PyroscopeIngest(p) + if want := p.Service + "{" + RunLabel + "=r1,pod=" + p.Pod + "}"; query.Get("name") != want { + t.Errorf("profile %d: name %q, want %q", i, query.Get("name"), want) + } + _, params, err := mime.ParseMediaType(contentType) + if err != nil { + t.Fatal(err) + } + form, err := multipart.NewReader(bytes.NewReader(body), params["boundary"]).ReadForm(1 << 20) + if err != nil { + t.Fatal(err) + } + file, err := form.File["profile"][0].Open() + if err != nil { + t.Fatal(err) + } + prof, err := profile.Parse(file) + file.Close() + if err != nil { + t.Fatalf("profile %d: %v", i, err) + } + if len(prof.Sample) != len(p.Stacks) { + t.Fatalf("profile %d: %d samples, want %d", i, len(prof.Sample), len(p.Stacks)) + } + for n, sample := range prof.Sample { + var frames []string + for _, loc := range sample.Location { + frames = append(frames, loc.Line[0].Function.Name) + } + if !slices.Equal(frames, p.Stacks[n]) { + t.Errorf("profile %d sample %d: stack %v, want %v", i, n, frames, p.Stacks[n]) + } + if want := []int64{p.Samples[n], p.Samples[n] * int64(CPUPeriod)}; !slices.Equal(sample.Value, want) { + t.Errorf("profile %d sample %d: values %v, want %v", i, n, sample.Value, want) + } + } + } +} diff --git a/test/integration/testdata/metrics/query_counter.json b/test/integration/testdata/metrics/query_counter.json new file mode 100644 index 000000000..4b6a8fdac --- /dev/null +++ b/test/integration/testdata/metrics/query_counter.json @@ -0,0 +1,60 @@ +{ + "data": { + "result": [ + { + "metric": { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p1", + "service_name": "checkout" + }, + "value": [ + "+585s", + "4200" + ] + }, + { + "metric": { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p2", + "service_name": "checkout" + }, + "value": [ + "+585s", + "7721" + ] + }, + { + "metric": { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p3", + "service_name": "checkout" + }, + "value": [ + "+585s", + "7219" + ] + }, + { + "metric": { + "__name__": "http_requests_total", + "app": "payments", + "m2_run": "RUN", + "pod": "p1", + "service_name": "payments" + }, + "value": [ + "+585s", + "2801" + ] + } + ], + "resultType": "vector" + }, + "status": "success" +} diff --git a/test/integration/testdata/metrics/query_range_total.json b/test/integration/testdata/metrics/query_range_total.json new file mode 100644 index 000000000..1f6f69bb7 --- /dev/null +++ b/test/integration/testdata/metrics/query_range_total.json @@ -0,0 +1,62 @@ +{ + "data": { + "result": [ + { + "metric": { + "app": "checkout" + }, + "values": [ + [ + "+300s", + "18741" + ], + [ + "+360s", + "18825" + ], + [ + "+420s", + "18909" + ], + [ + "+480s", + "18993" + ], + [ + "+540s", + "19077" + ] + ] + }, + { + "metric": { + "app": "payments" + }, + "values": [ + [ + "+300s", + "2630" + ], + [ + "+360s", + "2666" + ], + [ + "+420s", + "2702" + ], + [ + "+480s", + "2738" + ], + [ + "+540s", + "2774" + ] + ] + } + ], + "resultType": "matrix" + }, + "status": "success" +} diff --git a/test/integration/testdata/metrics/series.json b/test/integration/testdata/metrics/series.json new file mode 100644 index 000000000..4f8182825 --- /dev/null +++ b/test/integration/testdata/metrics/series.json @@ -0,0 +1,61 @@ +{ + "data": [ + { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p1", + "service_name": "checkout" + }, + { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p2", + "service_name": "checkout" + }, + { + "__name__": "http_requests_total", + "app": "checkout", + "m2_run": "RUN", + "pod": "p3", + "service_name": "checkout" + }, + { + "__name__": "http_requests_total", + "app": "payments", + "m2_run": "RUN", + "pod": "p1", + "service_name": "payments" + }, + { + "__name__": "process_resident_memory_bytes", + "app": "checkout", + "m2_run": "RUN", + "pod": "p1", + "service_name": "checkout" + }, + { + "__name__": "process_resident_memory_bytes", + "app": "checkout", + "m2_run": "RUN", + "pod": "p2", + "service_name": "checkout" + }, + { + "__name__": "process_resident_memory_bytes", + "app": "checkout", + "m2_run": "RUN", + "pod": "p3", + "service_name": "checkout" + }, + { + "__name__": "process_resident_memory_bytes", + "app": "payments", + "m2_run": "RUN", + "pod": "p1", + "service_name": "payments" + } + ], + "status": "success" +} diff --git a/test/integration/testdata/profiles/flamegraph_cpu.json b/test/integration/testdata/profiles/flamegraph_cpu.json new file mode 100644 index 000000000..861f52686 --- /dev/null +++ b/test/integration/testdata/profiles/flamegraph_cpu.json @@ -0,0 +1,60 @@ +{ + "levels": [ + { + "values": [ + "0", + "9940000000", + "0", + "0" + ] + }, + { + "values": [ + "0", + "9940000000", + "0", + "6" + ] + }, + { + "values": [ + "0", + "9940000000", + "0", + "3" + ] + }, + { + "values": [ + "0", + "9940000000", + "3710000000", + "4" + ] + }, + { + "values": [ + "0", + "3230000000", + "3230000000", + "5", + "0", + "3000000000", + "3000000000", + "2" + ] + }, + {} + ], + "maxSelf": "3710000000", + "names": [ + "total", + "n/a", + "encoding/json.Marshal", + "net/http.HandlerFunc.ServeHTTP", + "main.handleCheckout", + "main.chargePayment", + "main.main" + ], + "total": "9940000000" +} diff --git a/test/integration/testdata/profiles/render_cpu.json b/test/integration/testdata/profiles/render_cpu.json new file mode 100644 index 000000000..708b88a14 --- /dev/null +++ b/test/integration/testdata/profiles/render_cpu.json @@ -0,0 +1,64 @@ +{ + "flamebearer": { + "levels": [ + [ + 0, + 9940000000, + 0, + 0 + ], + [ + 0, + 9940000000, + 0, + 6 + ], + [ + 0, + 9940000000, + 0, + 3 + ], + [ + 0, + 9940000000, + 3710000000, + 4 + ], + [ + 0, + 3230000000, + 3230000000, + 5, + 0, + 3000000000, + 3000000000, + 2 + ], + [] + ], + "maxSelf": 3710000000, + "names": [ + "total", + "n/a", + "encoding/json.Marshal", + "net/http.HandlerFunc.ServeHTTP", + "main.handleCheckout", + "main.chargePayment", + "main.main" + ], + "numTicks": 9940000000 + }, + "groups": null, + "heatmap": null, + "leftTicks": 0, + "metadata": { + "format": "single", + "name": "cpu", + "sampleRate": 1000000000, + "spyName": "", + "units": "samples" + }, + "rightTicks": 0, + "timeline": null +} diff --git a/test/integration/testdata/profiles/render_diff_cpu.json b/test/integration/testdata/profiles/render_diff_cpu.json new file mode 100644 index 000000000..113fadd99 --- /dev/null +++ b/test/integration/testdata/profiles/render_diff_cpu.json @@ -0,0 +1,80 @@ +{ + "flamebearer": { + "levels": [ + [ + 0, + 3330000000, + 0, + 0, + 3670000000, + 0, + 0 + ], + [ + 0, + 3330000000, + 0, + 0, + 3670000000, + 0, + 1 + ], + [ + 0, + 3330000000, + 0, + 0, + 3670000000, + 0, + 2 + ], + [ + 0, + 3330000000, + 1270000000, + 0, + 3670000000, + 1500000000, + 3 + ], + [ + 0, + 900000000, + 900000000, + 0, + 1180000000, + 1180000000, + 4, + 0, + 1160000000, + 1160000000, + 0, + 990000000, + 990000000, + 5 + ] + ], + "maxSelf": 1500000000, + "names": [ + "total", + "main.main", + "net/http.HandlerFunc.ServeHTTP", + "main.handleCheckout", + "encoding/json.Marshal", + "main.chargePayment" + ], + "numTicks": 7000000000 + }, + "groups": null, + "heatmap": null, + "leftTicks": 3330000000, + "metadata": { + "format": "double", + "name": "cpu", + "sampleRate": 1000000000, + "spyName": "", + "units": "samples" + }, + "rightTicks": 3670000000, + "timeline": null +} diff --git a/test/integration/testdata/traces/search.json b/test/integration/testdata/traces/search.json new file mode 100644 index 000000000..cb6615f24 --- /dev/null +++ b/test/integration/testdata/traces/search.json @@ -0,0 +1,169 @@ +{ + "traces": [ + { + "durationMs": 169, + "rootServiceName": "checkout", + "rootTraceName": "POST /checkout", + "spanSet": { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "169000000", + "spanID": "span-0-0", + "startTimeUnixNano": "+0ms" + }, + { + "attributes": [], + "durationNanos": "72000000", + "spanID": "span-0-1", + "startTimeUnixNano": "+10ms" + }, + { + "attributes": [], + "durationNanos": "20000000", + "spanID": "span-0-2", + "startTimeUnixNano": "+20ms" + } + ] + }, + "spanSets": [ + { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "169000000", + "spanID": "span-0-0", + "startTimeUnixNano": "+0ms" + }, + { + "attributes": [], + "durationNanos": "72000000", + "spanID": "span-0-1", + "startTimeUnixNano": "+10ms" + }, + { + "attributes": [], + "durationNanos": "20000000", + "spanID": "span-0-2", + "startTimeUnixNano": "+20ms" + } + ] + } + ], + "startTimeUnixNano": "+0ms", + "traceID": "trace-0" + }, + { + "durationMs": 161, + "rootServiceName": "checkout", + "rootTraceName": "POST /checkout", + "spanSet": { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "161000000", + "spanID": "span-1-0", + "startTimeUnixNano": "+10000ms" + }, + { + "attributes": [], + "durationNanos": "74000000", + "spanID": "span-1-1", + "startTimeUnixNano": "+10010ms" + }, + { + "attributes": [], + "durationNanos": "8000000", + "spanID": "span-1-2", + "startTimeUnixNano": "+10020ms" + } + ] + }, + "spanSets": [ + { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "161000000", + "spanID": "span-1-0", + "startTimeUnixNano": "+10000ms" + }, + { + "attributes": [], + "durationNanos": "74000000", + "spanID": "span-1-1", + "startTimeUnixNano": "+10010ms" + }, + { + "attributes": [], + "durationNanos": "8000000", + "spanID": "span-1-2", + "startTimeUnixNano": "+10020ms" + } + ] + } + ], + "startTimeUnixNano": "+10000ms", + "traceID": "trace-1" + }, + { + "durationMs": 183, + "rootServiceName": "checkout", + "rootTraceName": "POST /checkout", + "spanSet": { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "183000000", + "spanID": "span-2-0", + "startTimeUnixNano": "+20000ms" + }, + { + "attributes": [], + "durationNanos": "70000000", + "spanID": "span-2-1", + "startTimeUnixNano": "+20010ms" + }, + { + "attributes": [], + "durationNanos": "9000000", + "spanID": "span-2-2", + "startTimeUnixNano": "+20020ms" + } + ] + }, + "spanSets": [ + { + "matched": 3, + "spans": [ + { + "attributes": [], + "durationNanos": "183000000", + "spanID": "span-2-0", + "startTimeUnixNano": "+20000ms" + }, + { + "attributes": [], + "durationNanos": "70000000", + "spanID": "span-2-1", + "startTimeUnixNano": "+20010ms" + }, + { + "attributes": [], + "durationNanos": "9000000", + "spanID": "span-2-2", + "startTimeUnixNano": "+20020ms" + } + ] + } + ], + "startTimeUnixNano": "+20000ms", + "traceID": "trace-2" + } + ] +} diff --git a/test/integration/traces_roundtrip_test.go b/test/integration/traces_roundtrip_test.go new file mode 100644 index 000000000..6eaf07c7d --- /dev/null +++ b/test/integration/traces_roundtrip_test.go @@ -0,0 +1,362 @@ +//go:build integration + +// Write-read round trip for traces (M2, #920): the seed fixture's traces are +// sent as an OTLP/HTTP request and read back through the Tempo API the way +// Grafana's Tempo data source reads them (trace by ID as protobuf, TraceQL +// search, tag names and values), each answer checked against the fixture. See +// logs_roundtrip_test.go for the pinned responses. + +package integration + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "sort" + "strconv" + "testing" + "time" + + "github.com/metrico/qryn/v5/test/integration/seed" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" + "google.golang.org/protobuf/proto" +) + +func TestTracesRoundTrip(t *testing.T) { + run := fmt.Sprintf("traces-%d", time.Now().UnixNano()) + start := time.Now().Add(-10 * time.Minute).Truncate(time.Minute) + fixture := seed.Default(run, start) + traces := fixture.Traces() + from, to := start.Add(-time.Minute), start.Add(5*time.Minute) + window := url.Values{"start": {unixSeconds(from)}, "end": {unixSeconds(to)}} + runQuery := fmt.Sprintf(`{ resource.%s = %q }`, seed.RunLabel, run) + + postOTLPTraces(t, fixture.OTLPTraces(traces)) + waitForTraces(t, runQuery, window, len(traces)) + + t.Run("trace by ID returns every span", func(t *testing.T) { + for i, tr := range traces { + got := fetchTraceSpans(t, tr.ID, window) + if len(got) != len(tr.Spans) { + t.Errorf("trace %d: %d spans, want %d", i, len(got), len(tr.Spans)) + } + for _, want := range tr.Spans { + span, ok := got[hex.EncodeToString(want.ID)] + if !ok { + t.Errorf("trace %d: span %q missing", i, want.Name) + continue + } + if span.service != want.Service || span.name != want.Name || span.kind != want.Kind || + span.parent != hex.EncodeToString(want.ParentID) || + span.start != uint64(want.Start.UnixNano()) || span.end != uint64(want.End.UnixNano()) { + t.Errorf("trace %d span %q:\n got %+v\nwant service %s, kind %v, parent %x, start %d, end %d", + i, want.Name, span, want.Service, want.Kind, want.ParentID, want.Start.UnixNano(), want.End.UnixNano()) + } + for k, v := range want.Attributes { + if span.attributes[k] != v { + t.Errorf("trace %d span %q: attribute %s = %q, want %q", i, want.Name, k, span.attributes[k], v) + } + } + } + } + }) + + t.Run("search finds every trace of the run", func(t *testing.T) { + raw := apiGet(t, "/api/search", withQuery(window, runQuery)) + got := map[string]searchTrace{} + for _, tr := range decodeSearch(t, raw) { + got[tr.TraceID] = tr + } + if len(got) != len(traces) { + t.Errorf("%d traces found, want %d", len(got), len(traces)) + } + for i, tr := range traces { + id := hex.EncodeToString(tr.ID) + found, ok := got[id] + if !ok { + t.Errorf("trace %d (%s) not found", i, id) + continue + } + root := tr.Spans[0] + wantDuration := int(root.End.Sub(root.Start) / time.Millisecond) + if found.RootServiceName != root.Service || found.RootTraceName != root.Name || + found.StartTimeUnixNano != strconv.FormatInt(root.Start.UnixNano(), 10) || found.DurationMs != wantDuration { + t.Errorf("trace %d: got %+v, want root %s %q starting at %d, %dms", + i, found, root.Service, root.Name, root.Start.UnixNano(), wantDuration) + } + } + assertPinned(t, "traces/search.json", normalizeSearch(t, raw, run, start, traces)) + }) + + t.Run("search by service and span name", func(t *testing.T) { + q := fmt.Sprintf(`{ resource.%s = %q && resource.service.name = %q && name = "charge" }`, + seed.RunLabel, run, fixture.Services[1].Name) + var got []string + for _, tr := range decodeSearch(t, apiGet(t, "/api/search", withQuery(window, q))) { + got = append(got, tr.TraceID) + if tr.SpanSet.Matched != 1 { + t.Errorf("trace %s: %d spans matched, want 1", tr.TraceID, tr.SpanSet.Matched) + } + } + var want []string + for _, tr := range traces { + want = append(want, hex.EncodeToString(tr.ID)) + } + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("traces = %v, want %v", got, want) + } + }) + + t.Run("search by duration", func(t *testing.T) { + const limit = 200 * time.Millisecond + q := fmt.Sprintf(`{ resource.%s = %q && duration > 200ms }`, seed.RunLabel, run) + var got []string + for _, tr := range decodeSearch(t, apiGet(t, "/api/search", withQuery(window, q))) { + got = append(got, tr.TraceID) + } + var want []string + for _, tr := range traces { + for _, sp := range tr.Spans { + if sp.End.Sub(sp.Start) > limit { + want = append(want, hex.EncodeToString(tr.ID)) + break + } + } + } + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("traces = %v, want %v", got, want) + } + }) + + // The tag list is not limited to this run, so it checks that the names + // written are listed, in whichever scope. + t.Run("tag names", func(t *testing.T) { + var resp struct { + Scopes []struct { + Tags []string `json:"tags"` + } `json:"scopes"` + } + mustUnmarshal(t, apiGet(t, "/api/v2/search/tags", window), &resp) + var got []string + for _, s := range resp.Scopes { + got = append(got, s.Tags...) + } + for _, name := range []string{"service.name", "k8s.pod.name", seed.RunLabel, "http.route", "db.system"} { + if !slices.Contains(got, name) { + t.Errorf("tags %v do not include %q", got, name) + } + } + }) + + t.Run("service names", func(t *testing.T) { + var resp struct { + TagValues []string `json:"tagValues"` + } + mustUnmarshal(t, apiGet(t, "/api/search/tag/service.name/values", window), &resp) + for _, svc := range fixture.Services { + if !slices.Contains(resp.TagValues, svc.Name) { + t.Errorf("service names %v do not include %q", resp.TagValues, svc.Name) + } + } + }) +} + +func withQuery(v url.Values, q string) url.Values { + out := url.Values{"q": {q}, "limit": {"100"}} + for k, vals := range v { + out[k] = vals + } + return out +} + +func postOTLPTraces(t *testing.T, body []byte) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, baseURL()+"/v1/traces", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/x-protobuf") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("OTLP traces: status %d, body %q", resp.StatusCode, raw) + } +} + +type searchTrace struct { + TraceID string `json:"traceID"` + RootServiceName string `json:"rootServiceName"` + RootTraceName string `json:"rootTraceName"` + StartTimeUnixNano string `json:"startTimeUnixNano"` + DurationMs int `json:"durationMs"` + SpanSet struct { + Matched int `json:"matched"` + } `json:"spanSet"` +} + +func decodeSearch(t *testing.T, raw []byte) []searchTrace { + t.Helper() + var resp struct { + Traces []searchTrace `json:"traces"` + } + mustUnmarshal(t, raw, &resp) + return resp.Traces +} + +// waitForTraces polls until the search returns want traces, since ingestion +// is flushed asynchronously. On timeout it only logs, so the named checks that +// follow still run and report what is wrong. +func waitForTraces(t *testing.T, q string, window url.Values, want int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := len(decodeSearch(t, apiGet(t, "/api/search", withQuery(window, q)))) + if got == want { + return + } + if time.Now().After(deadline) { + t.Logf("after 30s the search returns %d traces, want %d; checking anyway", got, want) + return + } + time.Sleep(500 * time.Millisecond) + } +} + +type fetchedSpan struct { + service string + name string + kind tracev1.Span_SpanKind + parent string + start, end uint64 + attributes map[string]string +} + +// fetchTraceSpans gets a trace as protobuf, as Grafana does, and returns its +// spans keyed by hex span ID. +func fetchTraceSpans(t *testing.T, id []byte, window url.Values) map[string]fetchedSpan { + t.Helper() + req, err := http.NewRequest(http.MethodGet, + fmt.Sprintf("%s/api/traces/%s?%s", baseURL(), hex.EncodeToString(id), window.Encode()), nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Accept", "application/protobuf") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET trace %x: status %d, body %q", id, resp.StatusCode, raw) + } + var td tracev1.TracesData + if err := proto.Unmarshal(raw, &td); err != nil { + t.Fatalf("trace %x is not an OTLP TracesData: %v", id, err) + } + out := map[string]fetchedSpan{} + for _, rs := range td.ResourceSpans { + service := "" + for _, a := range rs.GetResource().GetAttributes() { + if a.Key == "service.name" { + service = a.GetValue().GetStringValue() + } + } + for _, ss := range rs.ScopeSpans { + for _, sp := range ss.Spans { + attrs := map[string]string{} + for _, a := range sp.Attributes { + attrs[a.Key] = a.GetValue().GetStringValue() + } + out[hex.EncodeToString(sp.SpanId)] = fetchedSpan{ + service: service, name: sp.Name, kind: sp.Kind, parent: hex.EncodeToString(sp.ParentSpanId), + start: sp.StartTimeUnixNano, end: sp.EndTimeUnixNano, attributes: attrs, + } + } + } + } + return out +} + +// normalizeSearch replaces the run-specific values of a search response so it +// can be compared with its pinned copy: trace IDs become "trace-" in +// fixture order, span IDs "span--", and times offsets from the +// fixture start in milliseconds, since spans start within a second of each +// other. Traces and spans are sorted. +func normalizeSearch(t *testing.T, raw []byte, run string, start time.Time, traces []seed.Trace) any { + t.Helper() + names := map[string]string{} + for i, tr := range traces { + names[hex.EncodeToString(tr.ID)] = fmt.Sprintf("trace-%d", i) + for j, sp := range tr.Spans { + names[hex.EncodeToString(sp.ID)] = fmt.Sprintf("span-%d-%d", i, j) + } + } + rename := func(id string) string { + if n, ok := names[id]; ok { + return n + } + t.Errorf("unexpected ID %s in the search response", id) + return id + } + offset := func(ns string) string { + v, err := strconv.ParseInt(ns, 10, 64) + if err != nil { + t.Fatalf("time %q: %v", ns, err) + } + return fmt.Sprintf("%+dms", time.Unix(0, v).Sub(start).Milliseconds()) + } + type span struct { + SpanID string `json:"spanID"` + StartTimeUnixNano string `json:"startTimeUnixNano"` + DurationNanos string `json:"durationNanos"` + Attributes []any `json:"attributes"` + } + type spanSet struct { + Spans []span `json:"spans"` + Matched int `json:"matched"` + } + var resp struct { + Traces []struct { + TraceID string `json:"traceID"` + RootServiceName string `json:"rootServiceName"` + RootTraceName string `json:"rootTraceName"` + StartTimeUnixNano string `json:"startTimeUnixNano"` + DurationMs int `json:"durationMs"` + SpanSet spanSet `json:"spanSet"` + SpanSets []spanSet `json:"spanSets"` + } `json:"traces"` + } + mustUnmarshal(t, raw, &resp) + fix := func(s spanSet) spanSet { + for i := range s.Spans { + s.Spans[i].SpanID = rename(s.Spans[i].SpanID) + s.Spans[i].StartTimeUnixNano = offset(s.Spans[i].StartTimeUnixNano) + } + sort.Slice(s.Spans, func(i, j int) bool { return s.Spans[i].SpanID < s.Spans[j].SpanID }) + return s + } + for i, tr := range resp.Traces { + tr.TraceID = rename(tr.TraceID) + tr.StartTimeUnixNano = offset(tr.StartTimeUnixNano) + tr.SpanSet = fix(tr.SpanSet) + for j := range tr.SpanSets { + tr.SpanSets[j] = fix(tr.SpanSets[j]) + } + resp.Traces[i] = tr + } + sort.Slice(resp.Traces, func(i, j int) bool { return resp.Traces[i].TraceID < resp.Traces[j].TraceID }) + return resp +} From 92e87b0957cf2c7db93da1247b75ac44e8ede664 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Wed, 25 Nov 2026 12:25:41 +0000 Subject: [PATCH 06/11] test(integration): pin flame graphs as call stacks and decode strictly (M2 3/4, #920) Review of #1062: the flame graph pins (SelectMergeStacktraces, render, render-diff) hold call stacks with their total and self values instead of the raw names and levels arrays, whose order the query doesn't define. The matrix, search and render responses are decoded strictly, and matrix points must have exactly two elements. --- test/integration/metrics_roundtrip_test.go | 43 +++- test/integration/profiles_roundtrip_test.go | 196 +++++++++++++++--- .../testdata/profiles/flamegraph_cpu.json | 70 ++----- .../testdata/profiles/render_cpu.json | 80 +++---- .../testdata/profiles/render_diff_cpu.json | 108 ++++------ test/integration/traces_roundtrip_test.go | 3 +- 6 files changed, 307 insertions(+), 193 deletions(-) diff --git a/test/integration/metrics_roundtrip_test.go b/test/integration/metrics_roundtrip_test.go index c074fece0..511eeea73 100644 --- a/test/integration/metrics_roundtrip_test.go +++ b/test/integration/metrics_roundtrip_test.go @@ -357,20 +357,49 @@ func assertFloatMap(t *testing.T, got, want map[string]float64, tolerance float6 } } -// matrix normalizes a range query matrix response. +// matrixResponse is a range query matrix response as gigapipe sends it. +// Points are decoded as slices and checked to have exactly two elements. +type matrixResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Values [][]any `json:"values"` + } `json:"result"` + } `json:"data"` +} + +// matrix normalizes a range query matrix response, decoded strictly. func (n normalizer) matrix(t *testing.T, raw []byte) any { t.Helper() + var wire matrixResponse + strictUnmarshal(t, raw, &wire) + if wire.Data.ResultType != "matrix" { + t.Fatalf("resultType = %q, want matrix", wire.Data.ResultType) + } + type series struct { + Metric map[string]string `json:"metric"` + Values [][2]any `json:"values"` + } var resp struct { Status string `json:"status"` Data struct { - ResultType string `json:"resultType"` - Result []struct { - Metric map[string]string `json:"metric"` - Values [][2]any `json:"values"` - } `json:"result"` + ResultType string `json:"resultType"` + Result []series `json:"result"` } `json:"data"` } - mustUnmarshal(t, raw, &resp) + resp.Status, resp.Data.ResultType = wire.Status, wire.Data.ResultType + for _, w := range wire.Data.Result { + r := series{Metric: w.Metric} + for _, v := range w.Values { + if len(v) != 2 { + t.Fatalf("series %v point has %d elements, want 2 (time, value): %v", w.Metric, len(v), v) + } + r.Values = append(r.Values, [2]any{v[0], v[1]}) + } + resp.Data.Result = append(resp.Data.Result, r) + } for i, r := range resp.Data.Result { r.Metric = n.labels(r.Metric) for j, v := range r.Values { diff --git a/test/integration/profiles_roundtrip_test.go b/test/integration/profiles_roundtrip_test.go index cbb02ab44..d61518038 100644 --- a/test/integration/profiles_roundtrip_test.go +++ b/test/integration/profiles_roundtrip_test.go @@ -11,11 +11,13 @@ package integration import ( "bytes" + "encoding/json" "fmt" "io" "net/http" "net/url" "slices" + "sort" "strconv" "testing" "time" @@ -23,7 +25,6 @@ import ( querierv1 "github.com/metrico/qryn/v5/reader/prof" typesv1 "github.com/metrico/qryn/v5/reader/prof/types/v1" "github.com/metrico/qryn/v5/test/integration/seed" - "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -134,13 +135,15 @@ func TestProfilesRoundTrip(t *testing.T) { } } if svc.Name == fixture.Services[0].Name { - raw, err := protojson.Marshal(graph) - if err != nil { - t.Fatal(err) + levels := make([][]int64, len(graph.Levels)) + for i, l := range graph.Levels { + levels[i] = l.Values } - var v any - mustUnmarshal(t, raw, &v) - assertPinned(t, "profiles/flamegraph_cpu.json", v) + assertPinned(t, "profiles/flamegraph_cpu.json", struct { + Total int64 `json:"total"` + MaxSelf int64 `json:"maxSelf"` + Stacks []flameStack `json:"stacks"` + }{graph.Total, graph.MaxSelf, singleStacks(t, graph.Names, levels)}) } }) @@ -162,13 +165,7 @@ func TestProfilesRoundTrip(t *testing.T) { "from": {strconv.FormatInt(from, 10)}, "until": {strconv.FormatInt(to, 10)}, }) - var resp struct { - Flamebearer struct { - Names []string `json:"names"` - NumTicks int64 `json:"numTicks"` - } `json:"flamebearer"` - } - mustUnmarshal(t, raw, &resp) + resp := decodeRender(t, raw) if resp.Flamebearer.NumTicks != total(checkout) { t.Errorf("CPU time = %dns, want %dns", resp.Flamebearer.NumTicks, total(checkout)) } @@ -177,9 +174,7 @@ func TestProfilesRoundTrip(t *testing.T) { t.Errorf("function %q missing from %v", frame, resp.Flamebearer.Names) } } - var v any - mustUnmarshal(t, raw, &v) - assertPinned(t, "profiles/render_cpu.json", v) + assertPinned(t, "profiles/render_cpu.json", resp.normalize(t, singleStacks(t, resp.Flamebearer.Names, resp.Flamebearer.Levels))) }) t.Run("render-diff compares the first and the last upload of "+checkout, func(t *testing.T) { @@ -192,14 +187,7 @@ func TestProfilesRoundTrip(t *testing.T) { "rightFrom": {strconv.FormatInt(last.Add(-5*time.Second).UnixMilli(), 10)}, "rightUntil": {strconv.FormatInt(last.Add(5*time.Second).UnixMilli(), 10)}, }) - var resp struct { - LeftTicks int64 `json:"leftTicks"` - RightTicks int64 `json:"rightTicks"` - Metadata struct { - Format string `json:"format"` - } `json:"metadata"` - } - mustUnmarshal(t, raw, &resp) + resp := decodeRender(t, raw) if want := cpu[checkout][0]; resp.LeftTicks != want { t.Errorf("left (first upload) CPU time = %dns, want %dns", resp.LeftTicks, want) } @@ -209,9 +197,7 @@ func TestProfilesRoundTrip(t *testing.T) { if resp.Metadata.Format != "double" { t.Errorf("format = %q, want double", resp.Metadata.Format) } - var v any - mustUnmarshal(t, raw, &v) - assertPinned(t, "profiles/render_diff_cpu.json", v) + assertPinned(t, "profiles/render_diff_cpu.json", resp.normalize(t, diffStacks(t, resp.Flamebearer.Names, resp.Flamebearer.Levels))) }) t.Run("CPU time over time per service", func(t *testing.T) { @@ -300,6 +286,160 @@ func connectCall(t *testing.T, method string, req, resp proto.Message) { } } +// renderResponse is a /pyroscope/render or /pyroscope/render-diff response +// as gigapipe sends it, decoded strictly. Timeline, groups and heatmap are +// always null; they are kept raw so a missing key can be told from a null. +type renderResponse struct { + Flamebearer struct { + Names []string `json:"names"` + Levels [][]int64 `json:"levels"` + NumTicks int64 `json:"numTicks"` + MaxSelf int64 `json:"maxSelf"` + } `json:"flamebearer"` + Metadata struct { + Format string `json:"format"` + SpyName string `json:"spyName"` + SampleRate int64 `json:"sampleRate"` + Units string `json:"units"` + Name string `json:"name"` + } `json:"metadata"` + Timeline json.RawMessage `json:"timeline"` + Groups json.RawMessage `json:"groups"` + Heatmap json.RawMessage `json:"heatmap"` + LeftTicks int64 `json:"leftTicks"` + RightTicks int64 `json:"rightTicks"` +} + +func decodeRender(t *testing.T, raw []byte) renderResponse { + t.Helper() + var resp renderResponse + strictUnmarshal(t, raw, &resp) + for name, v := range map[string]json.RawMessage{"timeline": resp.Timeline, "groups": resp.Groups, "heatmap": resp.Heatmap} { + if len(v) == 0 { + t.Fatalf("field %q missing from the render response", name) + } + } + return resp +} + +// normalize replaces the flame graph's names and levels, whose order the +// query doesn't define, with its call stacks, and keeps every other field. +func (r renderResponse) normalize(t *testing.T, stacks any) any { + t.Helper() + return struct { + Flamebearer struct { + Stacks any `json:"stacks"` + NumTicks int64 `json:"numTicks"` + MaxSelf int64 `json:"maxSelf"` + } `json:"flamebearer"` + Metadata any `json:"metadata"` + Timeline json.RawMessage `json:"timeline"` + Groups json.RawMessage `json:"groups"` + Heatmap json.RawMessage `json:"heatmap"` + LeftTicks int64 `json:"leftTicks"` + RightTicks int64 `json:"rightTicks"` + }{ + Flamebearer: struct { + Stacks any `json:"stacks"` + NumTicks int64 `json:"numTicks"` + MaxSelf int64 `json:"maxSelf"` + }{stacks, r.Flamebearer.NumTicks, r.Flamebearer.MaxSelf}, + Metadata: r.Metadata, Timeline: r.Timeline, Groups: r.Groups, Heatmap: r.Heatmap, + LeftTicks: r.LeftTicks, RightTicks: r.RightTicks, + } +} + +// flameStack is one call stack of a flame graph, root first, with its total +// and self values. +type flameStack struct { + Stack string `json:"stack"` + Total int64 `json:"total"` + Self int64 `json:"self"` +} + +// flameDiffStack is one call stack of a diff flame graph with the values of +// both sides. +type flameDiffStack struct { + Stack string `json:"stack"` + LeftTotal int64 `json:"leftTotal"` + LeftSelf int64 `json:"leftSelf"` + RightTotal int64 `json:"rightTotal"` + RightSelf int64 `json:"rightSelf"` +} + +func singleStacks(t *testing.T, names []string, levels [][]int64) []flameStack { + t.Helper() + var out []flameStack + for _, n := range flameNodes(t, names, levels, 4) { + out = append(out, flameStack{n.stack, n.values[1], n.values[2]}) + } + return out +} + +func diffStacks(t *testing.T, names []string, levels [][]int64) []flameDiffStack { + t.Helper() + var out []flameDiffStack + for _, n := range flameNodes(t, names, levels, 7) { + out = append(out, flameDiffStack{n.stack, n.values[1], n.values[2], n.values[4], n.values[5]}) + } + return out +} + +type flameNode struct { + stack string + x int64 // start on its level + values []int64 +} + +// flameNodes rebuilds the call stacks of a flame graph, sorted by stack. +// Each level lists its nodes as groups of width numbers: the node's offset +// from the end of the previous node on the level, its total, ..., and last +// the index of its name (for a diff, width 7, the first three numbers are the +// left side's and are used for positions). A node's parent is the node one +// level up whose range contains the node's start, so names order and the +// order of siblings don't matter. +func flameNodes(t *testing.T, names []string, levels [][]int64, width int) []flameNode { + t.Helper() + var all []flameNode + var above []flameNode + for li, level := range levels { + if len(level)%width != 0 { + t.Fatalf("flame graph level %d has %d values, not groups of %d", li, len(level), width) + } + var here []flameNode + var x int64 + for j := 0; j < len(level); j += width { + g := level[j : j+width] + x += g[0] + idx := g[width-1] + if idx < 0 || int(idx) >= len(names) { + t.Fatalf("flame graph level %d: name index %d out of %d names", li, idx, len(names)) + } + stack := names[idx] + if li > 0 { + parent := -1 + for k, p := range above { + if p.x <= x && x < p.x+p.values[1] || p.x == x && p.values[1] == 0 { + parent = k + break + } + } + if parent < 0 { + t.Fatalf("flame graph level %d: no parent for %q at %d", li, names[idx], x) + } + stack = above[parent].stack + ";" + stack + } + n := flameNode{stack: stack, x: x, values: g} + here = append(here, n) + all = append(all, n) + x += g[1] + } + above = here + } + sort.SliceStable(all, func(i, j int) bool { return all[i].stack < all[j].stack }) + return all +} + func mergeStacktraces(t *testing.T, profileType, selector string, from, to int64) *querierv1.FlameGraph { t.Helper() var resp querierv1.SelectMergeStacktracesResponse diff --git a/test/integration/testdata/profiles/flamegraph_cpu.json b/test/integration/testdata/profiles/flamegraph_cpu.json index 861f52686..06d60d80e 100644 --- a/test/integration/testdata/profiles/flamegraph_cpu.json +++ b/test/integration/testdata/profiles/flamegraph_cpu.json @@ -1,60 +1,36 @@ { - "levels": [ + "maxSelf": 3710000000, + "stacks": [ { - "values": [ - "0", - "9940000000", - "0", - "0" - ] + "self": 0, + "stack": "total", + "total": 9940000000 }, { - "values": [ - "0", - "9940000000", - "0", - "6" - ] + "self": 0, + "stack": "total;main.main", + "total": 9940000000 }, { - "values": [ - "0", - "9940000000", - "0", - "3" - ] + "self": 0, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP", + "total": 9940000000 }, { - "values": [ - "0", - "9940000000", - "3710000000", - "4" - ] + "self": 3710000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout", + "total": 9940000000 }, { - "values": [ - "0", - "3230000000", - "3230000000", - "5", - "0", - "3000000000", - "3000000000", - "2" - ] + "self": 3000000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;encoding/json.Marshal", + "total": 3000000000 }, - {} - ], - "maxSelf": "3710000000", - "names": [ - "total", - "n/a", - "encoding/json.Marshal", - "net/http.HandlerFunc.ServeHTTP", - "main.handleCheckout", - "main.chargePayment", - "main.main" + { + "self": 3230000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;main.chargePayment", + "total": 3230000000 + } ], - "total": "9940000000" + "total": 9940000000 } diff --git a/test/integration/testdata/profiles/render_cpu.json b/test/integration/testdata/profiles/render_cpu.json index 708b88a14..da5937dac 100644 --- a/test/integration/testdata/profiles/render_cpu.json +++ b/test/integration/testdata/profiles/render_cpu.json @@ -1,53 +1,39 @@ { "flamebearer": { - "levels": [ - [ - 0, - 9940000000, - 0, - 0 - ], - [ - 0, - 9940000000, - 0, - 6 - ], - [ - 0, - 9940000000, - 0, - 3 - ], - [ - 0, - 9940000000, - 3710000000, - 4 - ], - [ - 0, - 3230000000, - 3230000000, - 5, - 0, - 3000000000, - 3000000000, - 2 - ], - [] - ], "maxSelf": 3710000000, - "names": [ - "total", - "n/a", - "encoding/json.Marshal", - "net/http.HandlerFunc.ServeHTTP", - "main.handleCheckout", - "main.chargePayment", - "main.main" - ], - "numTicks": 9940000000 + "numTicks": 9940000000, + "stacks": [ + { + "self": 0, + "stack": "total", + "total": 9940000000 + }, + { + "self": 0, + "stack": "total;main.main", + "total": 9940000000 + }, + { + "self": 0, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP", + "total": 9940000000 + }, + { + "self": 3710000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout", + "total": 9940000000 + }, + { + "self": 3000000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;encoding/json.Marshal", + "total": 3000000000 + }, + { + "self": 3230000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;main.chargePayment", + "total": 3230000000 + } + ] }, "groups": null, "heatmap": null, diff --git a/test/integration/testdata/profiles/render_diff_cpu.json b/test/integration/testdata/profiles/render_diff_cpu.json index 113fadd99..483421ac8 100644 --- a/test/integration/testdata/profiles/render_diff_cpu.json +++ b/test/integration/testdata/profiles/render_diff_cpu.json @@ -1,69 +1,51 @@ { "flamebearer": { - "levels": [ - [ - 0, - 3330000000, - 0, - 0, - 3670000000, - 0, - 0 - ], - [ - 0, - 3330000000, - 0, - 0, - 3670000000, - 0, - 1 - ], - [ - 0, - 3330000000, - 0, - 0, - 3670000000, - 0, - 2 - ], - [ - 0, - 3330000000, - 1270000000, - 0, - 3670000000, - 1500000000, - 3 - ], - [ - 0, - 900000000, - 900000000, - 0, - 1180000000, - 1180000000, - 4, - 0, - 1160000000, - 1160000000, - 0, - 990000000, - 990000000, - 5 - ] - ], "maxSelf": 1500000000, - "names": [ - "total", - "main.main", - "net/http.HandlerFunc.ServeHTTP", - "main.handleCheckout", - "encoding/json.Marshal", - "main.chargePayment" - ], - "numTicks": 7000000000 + "numTicks": 7000000000, + "stacks": [ + { + "leftSelf": 0, + "leftTotal": 3330000000, + "rightSelf": 0, + "rightTotal": 3670000000, + "stack": "total" + }, + { + "leftSelf": 0, + "leftTotal": 3330000000, + "rightSelf": 0, + "rightTotal": 3670000000, + "stack": "total;main.main" + }, + { + "leftSelf": 0, + "leftTotal": 3330000000, + "rightSelf": 0, + "rightTotal": 3670000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP" + }, + { + "leftSelf": 1270000000, + "leftTotal": 3330000000, + "rightSelf": 1500000000, + "rightTotal": 3670000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout" + }, + { + "leftSelf": 900000000, + "leftTotal": 900000000, + "rightSelf": 1180000000, + "rightTotal": 1180000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;encoding/json.Marshal" + }, + { + "leftSelf": 1160000000, + "leftTotal": 1160000000, + "rightSelf": 990000000, + "rightTotal": 990000000, + "stack": "total;main.main;net/http.HandlerFunc.ServeHTTP;main.handleCheckout;main.chargePayment" + } + ] }, "groups": null, "heatmap": null, diff --git a/test/integration/traces_roundtrip_test.go b/test/integration/traces_roundtrip_test.go index 6eaf07c7d..0378b23a7 100644 --- a/test/integration/traces_roundtrip_test.go +++ b/test/integration/traces_roundtrip_test.go @@ -339,7 +339,8 @@ func normalizeSearch(t *testing.T, raw []byte, run string, start time.Time, trac SpanSets []spanSet `json:"spanSets"` } `json:"traces"` } - mustUnmarshal(t, raw, &resp) + // Strict: a field this type doesn't declare fails the pin. + strictUnmarshal(t, raw, &resp) fix := func(s spanSet) spanSet { for i := range s.Spans { s.Spans[i].SpanID = rename(s.Spans[i].SpanID) From 58b87ab05b9a98edb4e736dae6baf502bac618cd Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Wed, 25 Nov 2026 14:29:50 +0000 Subject: [PATCH 07/11] test(integration): require every field of the render responses (M2 3/4, #920) Several pinned values of the render responses are zero, empty or null (leftTicks, rightTicks, spyName, timeline), so a missing key would decode to the same value: every declared field is now required. --- test/integration/profiles_roundtrip_test.go | 40 ++++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/test/integration/profiles_roundtrip_test.go b/test/integration/profiles_roundtrip_test.go index d61518038..0c9d0b277 100644 --- a/test/integration/profiles_roundtrip_test.go +++ b/test/integration/profiles_roundtrip_test.go @@ -16,9 +16,11 @@ import ( "io" "net/http" "net/url" + "reflect" "slices" "sort" "strconv" + "strings" "testing" "time" @@ -288,7 +290,7 @@ func connectCall(t *testing.T, method string, req, resp proto.Message) { // renderResponse is a /pyroscope/render or /pyroscope/render-diff response // as gigapipe sends it, decoded strictly. Timeline, groups and heatmap are -// always null; they are kept raw so a missing key can be told from a null. +// always null, so they are kept raw. type renderResponse struct { Flamebearer struct { Names []string `json:"names"` @@ -314,12 +316,40 @@ func decodeRender(t *testing.T, raw []byte) renderResponse { t.Helper() var resp renderResponse strictUnmarshal(t, raw, &resp) - for name, v := range map[string]json.RawMessage{"timeline": resp.Timeline, "groups": resp.Groups, "heatmap": resp.Heatmap} { - if len(v) == 0 { - t.Fatalf("field %q missing from the render response", name) + // Several pinned values are zero, empty or null (leftTicks, rightTicks, + // spyName, timeline...): a missing key would decode to the same value, so + // every key is required. + requireFields(t, raw, resp) + return resp +} + +// requireFields fails when the JSON object raw lacks a key that the struct v +// declares, also in nested structs. Together with strict decoding, which +// rejects keys v doesn't declare, the keys must match exactly. +func requireFields(t *testing.T, raw []byte, v any) { + t.Helper() + var check func(path string, raw json.RawMessage, typ reflect.Type) + check = func(path string, raw json.RawMessage, typ reflect.Type) { + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil { + t.Fatalf("%s is not a JSON object: %v", strings.TrimSuffix(path, "."), err) + } + for i := range typ.NumField() { + f := typ.Field(i) + name, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if name == "" || name == "-" { + continue + } + value, ok := obj[name] + if !ok { + t.Fatalf("field %s%s missing from the response", path, name) + } + if f.Type.Kind() == reflect.Struct { + check(path+name+".", value, f.Type) + } } } - return resp + check("", raw, reflect.TypeOf(v)) } // normalize replaces the flame graph's names and levels, whose order the From b0e9f3cca8720b9e31c766f209f8b9a7d5710dd1 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Fri, 30 Oct 2026 16:04:38 +0000 Subject: [PATCH 08/11] test(integration): schema migration and ruler boot-order checks (M2 4/4, #920) TestSchemaMigrations runs gigapipe with MODE=init_only against a new database and checks it holds every table and view the single-node scripts in ctrl/qryn/sql declare (plus ver, where the migration runner records its progress). A second run on the same database, as on restarting an existing install, must succeed and change nothing. TestRulerBootOrder starts gigapipe in all mode with the ruler enabled and checks it from outside, as #920 asks: GET /api/v1/rules answers (a ruler started before the reader registers no routes, so the failure is a 404), and a recording rule uploaded through that API writes back samples with the expected values. Moving the ruler before the reader in bootSequence makes both cases fail; restoring the order makes them pass. Both start their own gigapipe process, each with a database of its own, so docker-compose.yml now publishes ClickHouse's ports to the host and run.sh builds the binary first. A process that exits because its port was taken is restarted on another port. --- test/integration/docker-compose.yml | 5 +- test/integration/migrations_test.go | 67 +++++++++ test/integration/process_test.go | 216 ++++++++++++++++++++++++++++ test/integration/ruler_boot_test.go | 106 ++++++++++++++ test/integration/run.sh | 3 + 5 files changed, 396 insertions(+), 1 deletion(-) create mode 100644 test/integration/migrations_test.go create mode 100644 test/integration/process_test.go create mode 100644 test/integration/ruler_boot_test.go diff --git a/test/integration/docker-compose.yml b/test/integration/docker-compose.yml index 907e6e1eb..1b7166022 100644 --- a/test/integration/docker-compose.yml +++ b/test/integration/docker-compose.yml @@ -9,9 +9,12 @@ services: environment: # Newer images limit the passwordless default user to the container. CLICKHOUSE_SKIP_USER_SETUP: "1" - # Published for the CI lane, which runs gigapipe on the host. + # Published for the CI lane, which runs gigapipe on the host, and for the + # tests that start their own gigapipe (migrations, ruler boot order) and + # read ClickHouse over HTTP. ports: - "127.0.0.1:9000:9000" + - "127.0.0.1:8123:8123" healthcheck: test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"] interval: 2s diff --git a/test/integration/migrations_test.go b/test/integration/migrations_test.go new file mode 100644 index 000000000..e906dbdc1 --- /dev/null +++ b/test/integration/migrations_test.go @@ -0,0 +1,67 @@ +//go:build integration + +// Schema migration lane (M2, #920): gigapipe's start-up migrations run against +// an empty single-node ClickHouse database must create every table and view +// the migration scripts declare, and running them again on the same database, +// as a restart of an existing install does, must succeed and change nothing. + +package integration + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "testing" + "time" +) + +// singleNodeScripts are the migration scripts applied to a single node; the +// *_dist.sql ones only run on a cluster. +var singleNodeScripts = []string{"log.sql", "traces.sql", "profiles.sql", "rules.sql"} + +var createStatement = regexp.MustCompile(`(?i)CREATE\s+(?:TABLE|MATERIALIZED\s+VIEW|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?\{\{\.DB\}\}\.(\w+)`) + +// declaredTables returns every table and view the single-node migration +// scripts create, plus ver, where the migration runner records how far each +// script has been applied (ctrl/qryn/maintenance/update.go), sorted. +func declaredTables(t *testing.T) []string { + t.Helper() + names := []string{"ver"} + for _, script := range singleNodeScripts { + sql, err := os.ReadFile(filepath.Join("..", "..", "ctrl", "qryn", "sql", script)) + if err != nil { + t.Fatal(err) + } + for _, m := range createStatement.FindAllStringSubmatch(string(sql), -1) { + if !slices.Contains(names, m[1]) { + names = append(names, m[1]) + } + } + } + if len(names) == 1 { + t.Fatal("found no CREATE statements in the migration scripts") + } + slices.Sort(names) + return names +} + +func TestSchemaMigrations(t *testing.T) { + db := freshDatabase(t, "m2_migrate") + env := processEnv(db, "MODE=init_only") + want := declaredTables(t) + + t.Run("an empty database gets every declared table", func(t *testing.T) { + runGigapipe(t, env, 2*time.Minute) + if got := databaseTables(t, db); !slices.Equal(got, want) { + t.Errorf("tables after the first run:\n got %v\nwant %v", got, want) + } + }) + + t.Run("running the migrations again changes nothing", func(t *testing.T) { + runGigapipe(t, env, 2*time.Minute) + if got := databaseTables(t, db); !slices.Equal(got, want) { + t.Errorf("tables after the second run:\n got %v\nwant %v", got, want) + } + }) +} diff --git a/test/integration/process_test.go b/test/integration/process_test.go new file mode 100644 index 000000000..8d104a1ff --- /dev/null +++ b/test/integration/process_test.go @@ -0,0 +1,216 @@ +//go:build integration + +// Helpers for the integration tests that start their own gigapipe process +// against the ClickHouse the stack uses, each with a database of its own. +// +// GIGAPIPE_BIN gigapipe binary (default: the one `make build` writes) +// CLICKHOUSE_SERVER ClickHouse host for that process (default localhost) +// CLICKHOUSE_PORT ClickHouse native port (default 9000) +// CLICKHOUSE_HTTP_URL ClickHouse HTTP interface the tests query (default http://localhost:8123) + +package integration + +import ( + "bytes" + "context" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +func envOr(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} + +// gigapipeBinary returns the binary to start, failing with a hint when it has +// not been built. +func gigapipeBinary(t *testing.T) string { + t.Helper() + bin := envOr("GIGAPIPE_BIN", filepath.Join("..", "..", "gigapipe")) + abs, err := filepath.Abs(bin) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(abs); err != nil { + t.Fatalf("gigapipe binary %s not found (run `make build` at the repository root, or set GIGAPIPE_BIN): %v", abs, err) + } + return abs +} + +// processEnv is the environment of a gigapipe process using database db. +func processEnv(db string, extra ...string) []string { + return append([]string{ + "CLICKHOUSE_SERVER=" + envOr("CLICKHOUSE_SERVER", "localhost"), + "CLICKHOUSE_PORT=" + envOr("CLICKHOUSE_PORT", "9000"), + "CLICKHOUSE_DB=" + db, + "BULK_MAX_AGE_MS=100", + "PATH=" + os.Getenv("PATH"), + "HOME=" + os.Getenv("HOME"), + }, extra...) +} + +// syncBuffer collects a process's output; the process writes it while the +// test may read it. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// runGigapipe runs gigapipe to completion, as with MODE=init_only, and returns +// its output. It fails the test if gigapipe exits with an error or runs +// longer than timeout. +func runGigapipe(t *testing.T, env []string, timeout time.Duration) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cmd := exec.CommandContext(ctx, gigapipeBinary(t)) + cmd.Env = env + out, err := cmd.CombinedOutput() + if ctx.Err() != nil { + t.Fatalf("gigapipe still running after %v; output:\n%s", timeout, out) + } + if err != nil { + t.Fatalf("gigapipe: %v; output:\n%s", err, out) + } + return string(out) +} + +// startGigapipe starts gigapipe on a free port and waits until it answers. It +// stops the process when the test ends and prints its output if the test +// failed. It returns the base URL. +// +// The port is found by binding to port 0 and releasing it, so another process +// can take it before gigapipe binds it. When gigapipe exits because the port +// is in use, it is started again on another port; any other early exit fails +// the test. +func startGigapipe(t *testing.T, env []string) string { + t.Helper() + for attempt := 1; ; attempt++ { + base, inUse := tryStartGigapipe(t, env) + if !inUse { + return base + } + if attempt == 3 { + t.Fatal("gigapipe could not bind a free port in 3 attempts") + } + } +} + +// tryStartGigapipe starts gigapipe once. It returns inUse when gigapipe +// exited because its port was taken. +func tryStartGigapipe(t *testing.T, env []string) (base string, inUse bool) { + t.Helper() + l, err := net.Listen("tcp", "0.0.0.0:0") + if err != nil { + t.Fatal(err) + } + port := l.Addr().(*net.TCPAddr).Port + l.Close() + + var output syncBuffer + cmd := exec.Command(gigapipeBinary(t)) + cmd.Env = append(env, "PORT="+strconv.Itoa(port)) + cmd.Stdout = &output + cmd.Stderr = &output + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + exited := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(exited) + }() + stop := func() { + _ = cmd.Process.Kill() + <-exited + } + + base = fmt.Sprintf("http://127.0.0.1:%d", port) + deadline := time.Now().Add(60 * time.Second) + for { + select { + case <-exited: + if strings.Contains(output.String(), "address already in use") { + return "", true + } + t.Fatalf("gigapipe on port %d exited during startup; output:\n%s", port, output.String()) + default: + } + resp, err := http.Get(base + "/api/v1/status/buildinfo") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + t.Cleanup(func() { + stop() + if t.Failed() { + t.Logf("gigapipe output:\n%s", output.String()) + } + }) + return base, false + } + } + if time.Now().After(deadline) { + stop() + t.Fatalf("gigapipe on port %d not ready after 60s; output:\n%s", port, output.String()) + } + time.Sleep(250 * time.Millisecond) + } +} + +// clickhouseQuery runs a query on the ClickHouse HTTP interface and returns +// the body. +func clickhouseQuery(t *testing.T, query string) string { + t.Helper() + endpoint := envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123") + resp, err := http.Post(endpoint+"/?"+url.Values{"query": {query}}.Encode(), "text/plain", nil) + if err != nil { + t.Fatalf("ClickHouse %s: %v", endpoint, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("ClickHouse query %q: status %d, body %q", query, resp.StatusCode, body) + } + return string(body) +} + +// freshDatabase returns the name of a database no other test uses, dropped +// when the test ends. gigapipe creates it on startup. +func freshDatabase(t *testing.T, prefix string) string { + t.Helper() + db := fmt.Sprintf("%s_%d", prefix, time.Now().UnixNano()) + t.Cleanup(func() { clickhouseQuery(t, "DROP DATABASE IF EXISTS "+db) }) + return db +} + +// databaseTables lists the tables and views of a database, sorted. +func databaseTables(t *testing.T, db string) []string { + t.Helper() + out := clickhouseQuery(t, fmt.Sprintf("SELECT name FROM system.tables WHERE database = '%s' ORDER BY name", db)) + return strings.Fields(out) +} diff --git a/test/integration/ruler_boot_test.go b/test/integration/ruler_boot_test.go new file mode 100644 index 000000000..14e5096ce --- /dev/null +++ b/test/integration/ruler_boot_test.go @@ -0,0 +1,106 @@ +//go:build integration + +// Ruler boot-order lane (M2, #920): with the ruler enabled, gigapipe must +// start it, which only works when it boots after the writer and the reader +// (see bootSequence in cmd/gigapipe). A ruler started too early logs an error +// and registers no routes, so the server is up and nothing else looks wrong. +// This checks it from outside: the rules API answers, and a recording rule +// uploaded through it produces samples. + +package integration + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/url" + "testing" + "time" + + "github.com/metrico/qryn/v5/test/integration/seed" +) + +func TestRulerBootOrder(t *testing.T) { + base := startGigapipe(t, processEnv(freshDatabase(t, "m2_ruler"), + "MODE=all", "GIGAPIPE_RULER_ENABLED=true", "GIGAPIPE_RULER_POLL_INTERVAL=2s")) + + t.Run("rules API answers", func(t *testing.T) { + resp, err := http.Get(base + "/api/v1/rules") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /api/v1/rules: status %d (404 means the ruler did not start), body %q", resp.StatusCode, body) + } + }) + + t.Run("recording rule produces samples", func(t *testing.T) { + run := fmt.Sprintf("ruler-%d", time.Now().UnixNano()) + // The last scrape is within a minute of now, inside the lookback of the + // rule's evaluation. + fixture := seed.Default(run, time.Now().Truncate(time.Minute).Add(-(seed.Scrapes-1)*seed.ScrapeInterval)) + series := fixture.Metrics() + postTo(t, base+"/api/v1/prom/remote/write", "application/x-protobuf", + map[string]string{"Content-Encoding": "snappy", "X-Prometheus-Remote-Write-Version": "0.1.0"}, + seed.PromRemoteWrite(series)) + + const record = "app:http_requests:sum" + rules := fmt.Sprintf("name: m2\ninterval: 5s\nrules:\n - record: %s\n expr: sum by (app) (http_requests_total{%s=%q})\n", + record, seed.RunLabel, run) + postTo(t, base+"/api/v1/rules/m2", "application/yaml", nil, []byte(rules)) + + want := map[string]float64{} + for _, s := range series { + if s.Labels["__name__"] == "http_requests_total" { + // gigapipe adds service_name to every series it writes, including + // the ones the ruler writes back. + want[labelKey(withServiceName(map[string]string{"__name__": record, "app": s.Labels["app"]}))] += s.Samples[len(s.Samples)-1].Value + } + } + deadline := time.Now().Add(60 * time.Second) + for { + resp, err := http.Get(base + "/api/v1/query?" + url.Values{"query": {record}}.Encode()) + if err != nil { + t.Fatal(err) + } + raw, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("query %s: status %d, body %q", record, resp.StatusCode, raw) + } + got := vectorByLabels(t, raw) + if len(got) == len(want) { + assertFloatMap(t, got, want, 0) + return + } + if time.Now().After(deadline) { + t.Fatalf("after 60s %s returns %v, want %v", record, got, want) + } + time.Sleep(time.Second) + } + }) +} + +func postTo(t *testing.T, target, contentType string, headers map[string]string, body []byte) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, target, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", contentType) + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("POST %s: status %d, body %q", target, resp.StatusCode, raw) + } +} diff --git a/test/integration/run.sh b/test/integration/run.sh index c9531bc94..01b6cf99e 100755 --- a/test/integration/run.sh +++ b/test/integration/run.sh @@ -23,6 +23,9 @@ trap cleanup EXIT echo "--- building + starting stack ---" $COMPOSE up -d --build +echo "--- building the gigapipe binary the tests start themselves ---" +(cd ../.. && make build) + echo "--- running integration tests against $GIGAPIPE_URL ---" # Subshell: cleanup must still run from this directory, where docker-compose.yml is. (cd ../.. && make test-integration) From 02c7ee001cf8dc0c3b9f5e26e7550b985475323a Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Fri, 30 Oct 2026 16:33:20 +0000 Subject: [PATCH 09/11] test(integration): cluster variant of the schema migration lane (M2 4/4, #920) TestSchemaMigrationsCluster runs gigapipe's migrations with CLUSTER_NAME set against a two-node ClickHouse cluster (test_cluster_two_shards) that reuses the e2e stack's configuration. Every node must hold the objects of the single-node and *_dist.sql scripts, plus ver and ver_dist, and a second run must change nothing. It has its own build tag (integration_cluster) and runs through make test-integration-cluster, which starts the cluster, runs the test and always stops the cluster. A new workflow runs it on the release cadence #920 names (pushes to master, by hand) and on pull requests that change ctrl/qryn or this lane. The ClickHouse helpers can now target a given node, and declaredTables takes the scripts to read, so the single-node and cluster checks share them. --- .github/workflows/integration-cluster.yml | 35 ++++++++++++ Makefile | 14 ++++- docs/contributing.md | 1 + test/integration/cluster/docker-compose.yml | 52 ++++++++++++++++++ test/integration/migrations_cluster_test.go | 60 +++++++++++++++++++++ test/integration/migrations_test.go | 12 ++--- test/integration/process_test.go | 17 +++++- 7 files changed, 182 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/integration-cluster.yml create mode 100644 test/integration/cluster/docker-compose.yml create mode 100644 test/integration/migrations_cluster_test.go diff --git a/.github/workflows/integration-cluster.yml b/.github/workflows/integration-cluster.yml new file mode 100644 index 000000000..f1827e32a --- /dev/null +++ b/.github/workflows/integration-cluster.yml @@ -0,0 +1,35 @@ +name: Integration (cluster migrations) + +# Cluster variant of the schema migration lane (#920): runs gigapipe's +# migrations ON CLUSTER against a two-node ClickHouse cluster and checks that +# every node gets every declared table. It runs on the release cadence (pushes +# to master, or by hand), and on pull requests that change the migrations or +# this lane. +on: + push: + branches: [ "master" ] + workflow_dispatch: + pull_request: + branches: [ "master" ] + paths: + - "ctrl/qryn/**" + - "test/integration/cluster/**" + - "test/integration/migrations*_test.go" + - ".github/workflows/integration-cluster.yml" + +permissions: + contents: read + +jobs: + migrations-cluster: + 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: Cluster migration lane + run: make test-integration-cluster diff --git a/Makefile b/Makefile index af7471a8b..28112686c 100644 --- a/Makefile +++ b/Makefile @@ -22,7 +22,8 @@ DURATION ?= 60s 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 integration-start test-integration lint fuzz + fmt-check build test-unit integration-start test-integration test-integration-cluster \ + lint fuzz docker: docker build -t gigapipe . @@ -61,6 +62,17 @@ integration-start: test-integration: go test -tags integration -count=1 -v ./test/integration/... +# Run the cluster variant of the schema migration lane: start the two-node +# ClickHouse cluster in test/integration/cluster, run the test against it and +# always stop the cluster afterwards. It publishes ClickHouse on ports 9000, +# 8123 and 8124, so stop the stack of test/integration/run.sh first. +test-integration-cluster: build + docker compose -f test/integration/cluster/docker-compose.yml up -d --wait + go test -tags integration,integration_cluster -count=1 -v -run TestSchemaMigrationsCluster ./test/integration/... ; \ + status=$$?; \ + docker compose -f test/integration/cluster/docker-compose.yml down -v; \ + exit $$status + # 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 diff --git a/docs/contributing.md b/docs/contributing.md index c8395c040..bab9ed4e7 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -77,6 +77,7 @@ 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 test-integration # integration tests against GIGAPIPE_URL (see test/integration/run.sh) +make test-integration-cluster # cluster migration lane on a two-node ClickHouse cluster (Docker) 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 ``` diff --git a/test/integration/cluster/docker-compose.yml b/test/integration/cluster/docker-compose.yml new file mode 100644 index 000000000..9650d3982 --- /dev/null +++ b/test/integration/cluster/docker-compose.yml @@ -0,0 +1,52 @@ +# Two-shard ClickHouse cluster (test_cluster_two_shards) for the cluster +# variant of the schema migration lane. It uses the same ClickHouse +# configuration as the e2e stack in scripts/test/e2e: the nodes must keep the +# host names that configuration refers to. Ports are published so the tests +# can reach both nodes from the host. +# +# CLICKHOUSE_SKIP_USER_SETUP keeps the image from limiting the passwordless +# default user to connections from inside the container, so the users.xml +# above applies as written. +services: + clickhouse1: + image: clickhouse/clickhouse-server:25.3 + hostname: e2e.clickhouse + environment: + CLICKHOUSE_SKIP_USER_SETUP: "1" + volumes: + - ../../../scripts/test/e2e/clickhouse/config.xml:/etc/clickhouse-server/config.xml + - ../../../scripts/test/e2e/clickhouse/users.xml:/etc/clickhouse-server/users.xml + networks: + default: + aliases: + - e2e.clickhouse + - clickhouse_1 + ports: + - "9000:9000" + - "8123:8123" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"] + interval: 2s + timeout: 3s + retries: 30 + + clickhouse2: + image: clickhouse/clickhouse-server:25.3 + hostname: e2e.clickhouse2 + environment: + CLICKHOUSE_SKIP_USER_SETUP: "1" + volumes: + - ../../../scripts/test/e2e/clickhouse/config2.xml:/etc/clickhouse-server/config.xml + - ../../../scripts/test/e2e/clickhouse/users.xml:/etc/clickhouse-server/users.xml + networks: + default: + aliases: + - e2e.clickhouse2 + - clickhouse_2 + ports: + - "8124:8123" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"] + interval: 2s + timeout: 3s + retries: 30 diff --git a/test/integration/migrations_cluster_test.go b/test/integration/migrations_cluster_test.go new file mode 100644 index 000000000..a3854baa5 --- /dev/null +++ b/test/integration/migrations_cluster_test.go @@ -0,0 +1,60 @@ +//go:build integration && integration_cluster + +// Cluster variant of the schema migration lane (M2, #920): with CLUSTER_NAME +// set, gigapipe's start-up migrations run ON CLUSTER and add the distributed +// tables of the *_dist.sql scripts. Every node of the cluster must end up with +// every declared table, and running the migrations again must change nothing. +// +// It needs a two-node cluster; test/integration/cluster/docker-compose.yml +// starts one, and `make test-integration-cluster` runs this test against it. +// +// CLICKHOUSE_CLUSTER cluster name (default test_cluster_two_shards) +// CLICKHOUSE_NODE_HTTP_URLS space-separated HTTP interfaces of the nodes +// (default http://localhost:8123 http://localhost:8124) + +package integration + +import ( + "fmt" + "slices" + "strings" + "testing" + "time" +) + +var distributedScripts = []string{"log_dist.sql", "traces_dist.sql", "profiles_dist.sql", "rules_dist.sql"} + +func TestSchemaMigrationsCluster(t *testing.T) { + cluster := envOr("CLICKHOUSE_CLUSTER", "test_cluster_two_shards") + nodes := strings.Fields(envOr("CLICKHOUSE_NODE_HTTP_URLS", "http://localhost:8123 http://localhost:8124")) + db := fmt.Sprintf("m2_migrate_cluster_%d", time.Now().UnixNano()) + t.Cleanup(func() { + clickhouseQueryAt(t, nodes[0], fmt.Sprintf("DROP DATABASE IF EXISTS %s ON CLUSTER `%s` SYNC", db, cluster)) + }) + env := processEnv(db, "MODE=init_only", "CLUSTER_NAME="+cluster) + + // On a cluster the migration runner also keeps ver_dist, the distributed + // view of ver (ctrl/qryn/maintenance/update.go). + want := declaredTables(t, append(slices.Clone(singleNodeScripts), distributedScripts...)) + want = append(want, "ver_dist") + slices.Sort(want) + + checkNodes := func(t *testing.T, run string) { + t.Helper() + for _, node := range nodes { + if got := databaseTablesAt(t, node, db); !slices.Equal(got, want) { + t.Errorf("tables on %s after the %s run:\n got %v\nwant %v", node, run, got, want) + } + } + } + + t.Run("every node gets every declared table", func(t *testing.T) { + runGigapipe(t, env, 2*time.Minute) + checkNodes(t, "first") + }) + + t.Run("running the migrations again changes nothing", func(t *testing.T) { + runGigapipe(t, env, 2*time.Minute) + checkNodes(t, "second") + }) +} diff --git a/test/integration/migrations_test.go b/test/integration/migrations_test.go index e906dbdc1..71a36be74 100644 --- a/test/integration/migrations_test.go +++ b/test/integration/migrations_test.go @@ -22,13 +22,13 @@ var singleNodeScripts = []string{"log.sql", "traces.sql", "profiles.sql", "rules var createStatement = regexp.MustCompile(`(?i)CREATE\s+(?:TABLE|MATERIALIZED\s+VIEW|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?\{\{\.DB\}\}\.(\w+)`) -// declaredTables returns every table and view the single-node migration -// scripts create, plus ver, where the migration runner records how far each -// script has been applied (ctrl/qryn/maintenance/update.go), sorted. -func declaredTables(t *testing.T) []string { +// declaredTables returns every table and view the given migration scripts +// create, plus ver, where the migration runner records how far each script +// has been applied (ctrl/qryn/maintenance/update.go), sorted. +func declaredTables(t *testing.T, scripts []string) []string { t.Helper() names := []string{"ver"} - for _, script := range singleNodeScripts { + for _, script := range scripts { sql, err := os.ReadFile(filepath.Join("..", "..", "ctrl", "qryn", "sql", script)) if err != nil { t.Fatal(err) @@ -49,7 +49,7 @@ func declaredTables(t *testing.T) []string { func TestSchemaMigrations(t *testing.T) { db := freshDatabase(t, "m2_migrate") env := processEnv(db, "MODE=init_only") - want := declaredTables(t) + want := declaredTables(t, singleNodeScripts) t.Run("an empty database gets every declared table", func(t *testing.T) { runGigapipe(t, env, 2*time.Minute) diff --git a/test/integration/process_test.go b/test/integration/process_test.go index 8d104a1ff..1f0a95dd5 100644 --- a/test/integration/process_test.go +++ b/test/integration/process_test.go @@ -186,7 +186,13 @@ func tryStartGigapipe(t *testing.T, env []string) (base string, inUse bool) { // the body. func clickhouseQuery(t *testing.T, query string) string { t.Helper() - endpoint := envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123") + return clickhouseQueryAt(t, envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123"), query) +} + +// clickhouseQueryAt runs a query on the ClickHouse HTTP interface at endpoint +// and returns the body. +func clickhouseQueryAt(t *testing.T, endpoint, query string) string { + t.Helper() resp, err := http.Post(endpoint+"/?"+url.Values{"query": {query}}.Encode(), "text/plain", nil) if err != nil { t.Fatalf("ClickHouse %s: %v", endpoint, err) @@ -211,6 +217,13 @@ func freshDatabase(t *testing.T, prefix string) string { // databaseTables lists the tables and views of a database, sorted. func databaseTables(t *testing.T, db string) []string { t.Helper() - out := clickhouseQuery(t, fmt.Sprintf("SELECT name FROM system.tables WHERE database = '%s' ORDER BY name", db)) + return databaseTablesAt(t, envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123"), db) +} + +// databaseTablesAt lists the tables and views of a database on the ClickHouse +// HTTP interface at endpoint, sorted. +func databaseTablesAt(t *testing.T, endpoint, db string) []string { + t.Helper() + out := clickhouseQueryAt(t, endpoint, fmt.Sprintf("SELECT name FROM system.tables WHERE database = '%s' ORDER BY name", db)) return strings.Fields(out) } From c304d26bcb5aed65afba945cef9994d4ec54e84f Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Wed, 25 Nov 2026 14:29:50 +0000 Subject: [PATCH 10/11] test(integration): compare migrated table definitions, reuse the e2e cluster (M2 4/4, #920) Review of #1063: rerunning the migrations must leave every table's create_table_query unchanged, on every node. The cluster lane runs the e2e stack's two ClickHouse services with an override that only adds ports on 127.0.0.1, healthchecks and CLICKHOUSE_SKIP_USER_SETUP, and is torn down also when it fails to start. The integration stack publishes ClickHouse's HTTP port on 127.0.0.1 for the tests that read it, and the gigapipe processes the tests start listen on 127.0.0.1. --- .github/workflows/integration-cluster.yml | 5 ++- Makefile | 23 ++++++---- test/integration/cluster/docker-compose.yml | 47 ++++++--------------- test/integration/migrations_cluster_test.go | 15 +++++-- test/integration/migrations_test.go | 8 +++- test/integration/process_test.go | 47 ++++++++++++++++++++- 6 files changed, 97 insertions(+), 48 deletions(-) diff --git a/.github/workflows/integration-cluster.yml b/.github/workflows/integration-cluster.yml index f1827e32a..2a99e29d5 100644 --- a/.github/workflows/integration-cluster.yml +++ b/.github/workflows/integration-cluster.yml @@ -14,6 +14,7 @@ on: paths: - "ctrl/qryn/**" - "test/integration/cluster/**" + - "scripts/test/**" - "test/integration/migrations*_test.go" - ".github/workflows/integration-cluster.yml" @@ -24,10 +25,10 @@ jobs: migrations-cluster: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: go-version-file: go.mod diff --git a/Makefile b/Makefile index 28112686c..6113f8c70 100644 --- a/Makefile +++ b/Makefile @@ -62,16 +62,23 @@ integration-start: test-integration: go test -tags integration -count=1 -v ./test/integration/... -# Run the cluster variant of the schema migration lane: start the two-node -# ClickHouse cluster in test/integration/cluster, run the test against it and -# always stop the cluster afterwards. It publishes ClickHouse on ports 9000, -# 8123 and 8124, so stop the stack of test/integration/run.sh first. +# The two-node ClickHouse cluster of the e2e stack, with the host ports the +# cluster migration test needs (test/integration/cluster/docker-compose.yml). +CLUSTER_COMPOSE = docker compose -p gigapipe-migrations-cluster \ + -f scripts/test/e2e/docker-compose.yml -f test/integration/cluster/docker-compose.yml + +# Run the cluster variant of the schema migration lane: start the cluster, run +# the test against it and stop the cluster afterwards, also when it fails to +# start. It publishes ClickHouse on 127.0.0.1 ports 9000, 8123 and 8124, so +# stop the stack of test/integration/run.sh first. test-integration-cluster: build - docker compose -f test/integration/cluster/docker-compose.yml up -d --wait - go test -tags integration,integration_cluster -count=1 -v -run TestSchemaMigrationsCluster ./test/integration/... ; \ + $(CLUSTER_COMPOSE) up -d --wait e2e-clickhouse e2e-clickhouse2; status=$$?; \ + if [ $$status -eq 0 ]; then \ + go test -tags integration,integration_cluster -count=1 -v -run TestSchemaMigrationsCluster ./test/integration/...; \ status=$$?; \ - docker compose -f test/integration/cluster/docker-compose.yml down -v; \ - exit $$status + fi; \ + $(CLUSTER_COMPOSE) down -v --remove-orphans; \ + exit $$status # 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 diff --git a/test/integration/cluster/docker-compose.yml b/test/integration/cluster/docker-compose.yml index 9650d3982..7fd6745d6 100644 --- a/test/integration/cluster/docker-compose.yml +++ b/test/integration/cluster/docker-compose.yml @@ -1,50 +1,31 @@ -# Two-shard ClickHouse cluster (test_cluster_two_shards) for the cluster -# variant of the schema migration lane. It uses the same ClickHouse -# configuration as the e2e stack in scripts/test/e2e: the nodes must keep the -# host names that configuration refers to. Ports are published so the tests -# can reach both nodes from the host. +# Additions to scripts/test/e2e/docker-compose.yml for the cluster variant of +# the schema migration lane: it runs the e2e stack's two ClickHouse nodes +# (test_cluster_two_shards; the image version is in +# scripts/test/docker-compose.clickhouse.yml) and only adds what the test needs +# from the host. `make test-integration-cluster` uses both files. # -# CLICKHOUSE_SKIP_USER_SETUP keeps the image from limiting the passwordless -# default user to connections from inside the container, so the users.xml -# above applies as written. +# Ports are published on 127.0.0.1 only: the default user has no password. +# CLICKHOUSE_SKIP_USER_SETUP keeps the image from limiting that user to +# connections from inside the container, so the e2e users.xml applies as +# written. services: - clickhouse1: - image: clickhouse/clickhouse-server:25.3 - hostname: e2e.clickhouse + e2e-clickhouse: environment: CLICKHOUSE_SKIP_USER_SETUP: "1" - volumes: - - ../../../scripts/test/e2e/clickhouse/config.xml:/etc/clickhouse-server/config.xml - - ../../../scripts/test/e2e/clickhouse/users.xml:/etc/clickhouse-server/users.xml - networks: - default: - aliases: - - e2e.clickhouse - - clickhouse_1 ports: - - "9000:9000" - - "8123:8123" + - "127.0.0.1:9000:9000" + - "127.0.0.1:8123:8123" healthcheck: test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"] interval: 2s timeout: 3s retries: 30 - clickhouse2: - image: clickhouse/clickhouse-server:25.3 - hostname: e2e.clickhouse2 + e2e-clickhouse2: environment: CLICKHOUSE_SKIP_USER_SETUP: "1" - volumes: - - ../../../scripts/test/e2e/clickhouse/config2.xml:/etc/clickhouse-server/config.xml - - ../../../scripts/test/e2e/clickhouse/users.xml:/etc/clickhouse-server/users.xml - networks: - default: - aliases: - - e2e.clickhouse2 - - clickhouse_2 ports: - - "8124:8123" + - "127.0.0.1:8124:8123" healthcheck: test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"] interval: 2s diff --git a/test/integration/migrations_cluster_test.go b/test/integration/migrations_cluster_test.go index a3854baa5..355f913fc 100644 --- a/test/integration/migrations_cluster_test.go +++ b/test/integration/migrations_cluster_test.go @@ -3,10 +3,12 @@ // Cluster variant of the schema migration lane (M2, #920): with CLUSTER_NAME // set, gigapipe's start-up migrations run ON CLUSTER and add the distributed // tables of the *_dist.sql scripts. Every node of the cluster must end up with -// every declared table, and running the migrations again must change nothing. +// every declared table, and running the migrations again must change nothing: +// on every node, the same tables, each with the same CREATE statement. // -// It needs a two-node cluster; test/integration/cluster/docker-compose.yml -// starts one, and `make test-integration-cluster` runs this test against it. +// It needs a two-node cluster: `make test-integration-cluster` starts the two +// ClickHouse nodes of the e2e stack (scripts/test/e2e), with the ports from +// test/integration/cluster/docker-compose.yml, and runs this test. // // CLICKHOUSE_CLUSTER cluster name (default test_cluster_two_shards) // CLICKHOUSE_NODE_HTTP_URLS space-separated HTTP interfaces of the nodes @@ -47,14 +49,21 @@ func TestSchemaMigrationsCluster(t *testing.T) { } } } + first := map[string]map[string]string{} t.Run("every node gets every declared table", func(t *testing.T) { runGigapipe(t, env, 2*time.Minute) checkNodes(t, "first") + for _, node := range nodes { + first[node] = tableDefinitionsAt(t, node, db) + } }) t.Run("running the migrations again changes nothing", func(t *testing.T) { runGigapipe(t, env, 2*time.Minute) checkNodes(t, "second") + for _, node := range nodes { + assertSameDefinitions(t, node, first[node], tableDefinitionsAt(t, node, db)) + } }) } diff --git a/test/integration/migrations_test.go b/test/integration/migrations_test.go index 71a36be74..43ae30237 100644 --- a/test/integration/migrations_test.go +++ b/test/integration/migrations_test.go @@ -3,7 +3,9 @@ // Schema migration lane (M2, #920): gigapipe's start-up migrations run against // an empty single-node ClickHouse database must create every table and view // the migration scripts declare, and running them again on the same database, -// as a restart of an existing install does, must succeed and change nothing. +// as a restart of an existing install does, must succeed and change nothing: +// the same tables, each with the same CREATE statement (columns, engine, TTL, +// view query). package integration @@ -50,12 +52,15 @@ func TestSchemaMigrations(t *testing.T) { db := freshDatabase(t, "m2_migrate") env := processEnv(db, "MODE=init_only") want := declaredTables(t, singleNodeScripts) + node := envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123") + var first map[string]string t.Run("an empty database gets every declared table", func(t *testing.T) { runGigapipe(t, env, 2*time.Minute) if got := databaseTables(t, db); !slices.Equal(got, want) { t.Errorf("tables after the first run:\n got %v\nwant %v", got, want) } + first = tableDefinitionsAt(t, node, db) }) t.Run("running the migrations again changes nothing", func(t *testing.T) { @@ -63,5 +68,6 @@ func TestSchemaMigrations(t *testing.T) { if got := databaseTables(t, db); !slices.Equal(got, want) { t.Errorf("tables after the second run:\n got %v\nwant %v", got, want) } + assertSameDefinitions(t, node, first, tableDefinitionsAt(t, node, db)) }) } diff --git a/test/integration/process_test.go b/test/integration/process_test.go index 1f0a95dd5..b56d97741 100644 --- a/test/integration/process_test.go +++ b/test/integration/process_test.go @@ -13,6 +13,7 @@ package integration import ( "bytes" "context" + "encoding/json" "fmt" "io" "net" @@ -53,6 +54,9 @@ func gigapipeBinary(t *testing.T) string { // processEnv is the environment of a gigapipe process using database db. func processEnv(db string, extra ...string) []string { return append([]string{ + // gigapipe listens on all interfaces by default, and these processes + // run without authentication: keep them on this machine. + "HOST=127.0.0.1", "CLICKHOUSE_SERVER=" + envOr("CLICKHOUSE_SERVER", "localhost"), "CLICKHOUSE_PORT=" + envOr("CLICKHOUSE_PORT", "9000"), "CLICKHOUSE_DB=" + db, @@ -125,7 +129,7 @@ func startGigapipe(t *testing.T, env []string) string { // exited because its port was taken. func tryStartGigapipe(t *testing.T, env []string) (base string, inUse bool) { t.Helper() - l, err := net.Listen("tcp", "0.0.0.0:0") + l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } @@ -220,6 +224,47 @@ func databaseTables(t *testing.T, db string) []string { return databaseTablesAt(t, envOr("CLICKHOUSE_HTTP_URL", "http://localhost:8123"), db) } +// tableDefinitionsAt returns the CREATE statement of every table and view of +// a database on the ClickHouse HTTP interface at endpoint, by name. +func tableDefinitionsAt(t *testing.T, endpoint, db string) map[string]string { + t.Helper() + out := clickhouseQueryAt(t, endpoint, fmt.Sprintf("SELECT name, create_table_query FROM system.tables WHERE database = '%s' FORMAT JSONEachRow", db)) + defs := map[string]string{} + for _, line := range strings.Split(out, "\n") { + if line == "" { + continue + } + var row struct { + Name string `json:"name"` + Create string `json:"create_table_query"` + } + if err := json.Unmarshal([]byte(line), &row); err != nil { + t.Fatalf("ClickHouse row %q: %v", line, err) + } + defs[row.Name] = row.Create + } + return defs +} + +// assertSameDefinitions reports every table or view whose CREATE statement +// differs between two runs of the migrations. +func assertSameDefinitions(t *testing.T, where string, before, after map[string]string) { + t.Helper() + if before == nil { + t.Fatalf("%s: no definitions from the first run to compare with", where) + } + for name, def := range after { + if before[name] != def { + t.Errorf("%s: %s changed:\n before %s\n after %s", where, name, before[name], def) + } + } + for name := range before { + if _, ok := after[name]; !ok { + t.Errorf("%s: %s is gone", where, name) + } + } +} + // databaseTablesAt lists the tables and views of a database on the ClickHouse // HTTP interface at endpoint, sorted. func databaseTablesAt(t *testing.T, endpoint, db string) []string { From 032ee2ddfe66524faca7e6df96035b6b26598c39 Mon Sep 17 00:00:00 2001 From: Guess-Who-sec Date: Fri, 20 Nov 2026 17:32:58 +0000 Subject: [PATCH 11/11] test(integration): Loki push ingestion conformance (M8, #924) TestLokiPushConformance sends Loki pushes and checks the rows gigapipe stores in ClickHouse: time_series, samples_v3, time_series_gin and metrics_15s. Cases: the M2 seed as JSON and as snappy protobuf, a pinned fingerprint shared by both formats, label order, service_name, label name cleanup, values over 100 characters, structured metadata, lines on two days, and the old labels/entries format. Expected values are what gigapipe stores today, measured. seed.LokiPushProto encodes streams the way Promtail sends them. ClickHouse is read with the clickhouseQuery helper and ports from the M2 lifecycle tests. --- test/integration/ingest_loki_push_test.go | 459 ++++++++++++++++++++++ test/integration/seed/seed.go | 34 ++ test/integration/seed/seed_test.go | 40 ++ 3 files changed, 533 insertions(+) create mode 100644 test/integration/ingest_loki_push_test.go diff --git a/test/integration/ingest_loki_push_test.go b/test/integration/ingest_loki_push_test.go new file mode 100644 index 000000000..57ace55b3 --- /dev/null +++ b/test/integration/ingest_loki_push_test.go @@ -0,0 +1,459 @@ +//go:build integration + +// Ingestion conformance for the Loki push API (M8, #924). What a Loki client +// sends is checked where gigapipe stores it, in ClickHouse, rather than through +// the query API as the M2 round trips do: which tables get rows, and the +// fingerprint, labels, timestamps, line text and sample type in them. +// +// The expected values are what gigapipe stores today, measured against a real +// stack. If a case fails after an intended change (for example the samples +// table split in #972), review the difference and edit the case by hand. +// +// ClickHouse is read with clickhouseQuery (process_test.go), over its HTTP +// interface at CLICKHOUSE_HTTP_URL (default http://localhost:8123), in the +// database CLICKHOUSE_DB (default cloki). + +package integration + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "maps" + "net/http" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/metrico/qryn/v5/test/integration/seed" +) + +// Where gigapipe stores logs today. The samples table split (#972) changes +// these; this is the one place that names them. +const ( + seriesTable = "time_series" // one row per stream, day and sample type + samplesTable = "samples_v3" // one row per log line + labelIndexTable = "time_series_gin" // one row per label, filled by a materialized view + logsRollupTable = "metrics_15s" // 15-second rollup, filled by a materialized view +) + +// sampleTypeLog is the type column value of a log line (writer/model). +const sampleTypeLog = 1 + +// pinnedFingerprint is the fingerprint gigapipe gives the stream +// {app="checkout", case="pinned-fingerprint", pod="p1"}, measured with the +// default fingerprint function (CityHash). It covers the whole path: label +// cleanup, the added service_name label, and the hash. Measured on 2026-11-20. +const pinnedFingerprint = "18270485951633840138" + +func TestLokiPushConformance(t *testing.T) { + run := fmt.Sprintf("ingest-%d", time.Now().UnixNano()) + start := time.Now().Add(-10 * time.Minute).Truncate(time.Minute) + + // The M2 seed: 4 streams, 17 lines. + t.Run("seed as JSON", func(t *testing.T) { + streams := seed.Default(run+"-json", start).Logs() + postBody(t, "/loki/api/v1/push", "application/json", seed.LokiPushJSON(streams)) + assertSeedStored(t, run+"-json", streams) + }) + + // The same streams the way Promtail and Alloy send them. The run label + // differs, so these are new streams with their own rows. + t.Run("seed as protobuf", func(t *testing.T) { + streams := seed.Default(run+"-proto", start).Logs() + postBody(t, "/loki/api/v1/push", "application/x-protobuf", seed.LokiPushProto(streams)) + assertSeedStored(t, run+"-proto", streams) + }) + + t.Run("fingerprint is pinned and the same for JSON and protobuf", func(t *testing.T) { + labels := map[string]string{"app": "checkout", "case": "pinned-fingerprint", "pod": "p1"} + // Nanosecond times only this run uses, so earlier runs' rows of this + // fixed stream don't count. + at := time.Now().Add(-5 * time.Minute) + jsonLine := seed.LogLine{Time: at, Text: "sent as JSON"} + protoLine := seed.LogLine{Time: at.Add(time.Second), Text: "sent as protobuf"} + postBody(t, "/loki/api/v1/push", "application/json", + seed.LokiPushJSON([]seed.LogStream{{Labels: labels, Lines: []seed.LogLine{jsonLine}}})) + postBody(t, "/loki/api/v1/push", "application/x-protobuf", + seed.LokiPushProto([]seed.LogStream{{Labels: labels, Lines: []seed.LogLine{protoLine}}})) + + got := waitForSamples(t, fmt.Sprintf("fingerprint = %s AND timestamp_ns IN (%d, %d)", + pinnedFingerprint, jsonLine.Time.UnixNano(), protoLine.Time.UnixNano()), 2) + want := []sampleRow{ + {pinnedFingerprint, jsonLine.Time.UnixNano(), 0, jsonLine.Text, sampleTypeLog}, + {pinnedFingerprint, protoLine.Time.UnixNano(), 0, protoLine.Text, sampleTypeLog}, + } + if !slices.Equal(got, want) { + t.Errorf("samples:\n got %v\nwant %v", got, want) + } + // Only the log-type row: this fixed stream's rows from earlier runs stay + // in the table, and the samples above already check this run's type. + wantLabels := map[string]string{"app": "checkout", "case": "pinned-fingerprint", "pod": "p1", "service_name": "checkout"} + for _, s := range waitForSeries(t, fmt.Sprintf("fingerprint = %s AND type = %d", pinnedFingerprint, sampleTypeLog), 1) { + if !maps.Equal(s.labelMap(t), wantLabels) { + t.Errorf("series row %+v, want labels %v", s, wantLabels) + } + } + }) + + t.Run("label order does not change the fingerprint", func(t *testing.T) { + ts := start.UnixNano() + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{%q:%q,"case":"order","app":"checkout","pod":"p1"},"values":[["%d","first"]]}]}`, + seed.RunLabel, run, ts)) + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{"pod":"p1","app":"checkout","case":"order",%q:%q},"values":[["%d","second"]]}]}`, + seed.RunLabel, run, ts+int64(time.Second))) + + series := waitForCase(t, run, "order", 2, 1) + fps := map[string]bool{} + for _, s := range series { + fps[s.Fingerprint] = true + } + if len(fps) != 1 { + t.Errorf("%d fingerprints for one stream sent with two label orders, want 1: %+v", len(fps), series) + } + }) + + t.Run("service_name is added from app, kept, or set to unknown", func(t *testing.T) { + ts := start.UnixNano() + pushRaw(t, fmt.Sprintf(`{"streams":[ + {"stream":{%[1]q:%[2]q,"case":"svc-app","app":"checkout"},"values":[["%[3]d","x"]]}, + {"stream":{%[1]q:%[2]q,"case":"svc-present","app":"checkout","service_name":"shop"},"values":[["%[3]d","x"]]}, + {"stream":{%[1]q:%[2]q,"case":"svc-none","pod":"p1"},"values":[["%[3]d","x"]]}]}`, + seed.RunLabel, run, ts)) + for name, want := range map[string]string{"svc-app": "checkout", "svc-present": "shop", "svc-none": "unknown"} { + series := waitForCase(t, run, name, 1, 1) + if got := series[0].labelMap(t)["service_name"]; got != want { + t.Errorf("%s: service_name = %q, want %q (labels %s)", name, got, want, series[0].Labels) + } + } + }) + + t.Run("label names are cleaned up", func(t *testing.T) { + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{%q:%q,"case":"names","k8s.pod-name":"p1"},"values":[["%d","x"]]}]}`, + seed.RunLabel, run, start.UnixNano())) + series := waitForCase(t, run, "names", 1, 1) + want := map[string]string{seed.RunLabel: run, "case": "names", "k8s_pod_name": "p1", "service_name": "unknown"} + if got := series[0].labelMap(t); !maps.Equal(got, want) { + t.Errorf("labels %v, want %v", got, want) + } + }) + + t.Run("label values over 100 characters are cut", func(t *testing.T) { + long := "https://shop.example.com/checkout/cart/items?session=" + strings.Repeat("0", 39) + "7&ref=newsletter-campaign-2026-11" + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{%q:%q,"case":"long","url":%q},"values":[["%d","x"]]}]}`, + seed.RunLabel, run, long, start.UnixNano())) + series := waitForCase(t, run, "long", 1, 1) + if got, want := series[0].labelMap(t)["url"], long[:100]+"..."; got != want { + t.Errorf("url label (sent %d characters) = %q, want %q", len(long), got, want) + } + }) + + t.Run("structured metadata is dropped and the line kept", func(t *testing.T) { + ts := start.UnixNano() + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{%q:%q,"case":"metadata"},"values":[["%d","with metadata",{"trace_id":"0242ac120002"}]]}]}`, + seed.RunLabel, run, ts)) + series := waitForCase(t, run, "metadata", 1, 1) + want := map[string]string{seed.RunLabel: run, "case": "metadata", "service_name": "unknown"} + if got := series[0].labelMap(t); !maps.Equal(got, want) { + t.Errorf("labels %v, want %v", got, want) + } + got := samplesWhere(t, "fingerprint = "+series[0].Fingerprint) + wantSamples := []sampleRow{{series[0].Fingerprint, ts, 0, "with metadata", sampleTypeLog}} + if !slices.Equal(got, wantSamples) { + t.Errorf("samples %v, want %v", got, wantSamples) + } + }) + + t.Run("lines on two days give one series row per day", func(t *testing.T) { + today := start + yesterday := start.Add(-24 * time.Hour) + pushRaw(t, fmt.Sprintf(`{"streams":[{"stream":{%q:%q,"case":"days"},"values":[["%d","yesterday"],["%d","today"]]}]}`, + seed.RunLabel, run, yesterday.UnixNano(), today.UnixNano())) + series := waitForCase(t, run, "days", 2, 2) + var dates []string + for _, s := range series { + dates = append(dates, s.Date) + if s.Fingerprint != series[0].Fingerprint { + t.Errorf("rows have different fingerprints: %+v", series) + } + } + want := []string{day(yesterday), day(today)} + if !slices.Equal(dates, want) { + t.Errorf("series dates %v, want %v", dates, want) + } + }) + + t.Run("old push format with a labels string and entries", func(t *testing.T) { + ts := start.Add(123456789 * time.Nanosecond) + pushRaw(t, fmt.Sprintf(`{"streams":[{"labels":"{%s=\"%s\", case=\"legacy\", app=\"checkout\"}","entries":[{"ts":%q,"line":"legacy line"}]}]}`, + seed.RunLabel, run, ts.UTC().Format(time.RFC3339Nano))) + series := waitForCase(t, run, "legacy", 1, 1) + want := map[string]string{seed.RunLabel: run, "case": "legacy", "app": "checkout", "service_name": "checkout"} + if got := series[0].labelMap(t); !maps.Equal(got, want) { + t.Errorf("labels %v, want %v", got, want) + } + got := samplesWhere(t, "fingerprint = "+series[0].Fingerprint) + wantSamples := []sampleRow{{series[0].Fingerprint, ts.UnixNano(), 0, "legacy line", sampleTypeLog}} + if !slices.Equal(got, wantSamples) { + t.Errorf("samples %v, want %v", got, wantSamples) + } + }) +} + +// assertSeedStored checks every row the seed streams of one run should give: +// a series row per stream and day, a sample per line, the label index, and +// the 15-second rollup. +func assertSeedStored(t *testing.T, run string, streams []seed.LogStream) { + t.Helper() + total := 0 + for _, s := range streams { + total += len(s.Lines) + } + runFilter := fmt.Sprintf("JSONExtractString(labels, %s) = %s", sqlString(seed.RunLabel), sqlString(run)) + waitForSamples(t, fmt.Sprintf("fingerprint IN (SELECT fingerprint FROM %s WHERE %s)", table(seriesTable), runFilter), total) + seriesRows := 0 + for _, s := range streams { + seriesRows += len(days(s.Lines)) + } + + // Labels as stored: in the order sent (names sorted, by both encoders), + // with service_name, copied from app, last. + byLabels := map[string][]seriesRow{} + for _, s := range waitForSeries(t, runFilter, seriesRows) { + byLabels[s.Labels] = append(byLabels[s.Labels], s) + } + if len(byLabels) != len(streams) { + t.Errorf("%d distinct label sets in %s, want %d", len(byLabels), seriesTable, len(streams)) + } + fingerprints := map[string]bool{} + for _, s := range streams { + labels := fmt.Sprintf(`{"app":%q,%q:%q,"pod":%q,"service_name":%q}`, + s.Labels["app"], seed.RunLabel, s.Labels[seed.RunLabel], s.Labels["pod"], s.Labels["app"]) + rows := byLabels[labels] + if len(rows) == 0 { + t.Errorf("no %s row with labels %s", seriesTable, labels) + continue + } + dates := days(s.Lines) + fp := rows[0].Fingerprint + var gotDates []string + for _, r := range rows { + gotDates = append(gotDates, r.Date) + if r.Fingerprint != fp || r.Type != sampleTypeLog || r.Name != "" || r.Metadata != "" { + t.Errorf("%s row %+v: want fingerprint %s, type %d, empty name and metadata", seriesTable, r, fp, sampleTypeLog) + } + } + if !slices.Equal(gotDates, dates) { + t.Errorf("%s: dates %v, want %v", labels, gotDates, dates) + } + if fingerprints[fp] { + t.Errorf("fingerprint %s is shared by two streams", fp) + } + fingerprints[fp] = true + + var want []sampleRow + textBytes := 0 + for _, l := range s.Lines { + want = append(want, sampleRow{fp, l.Time.UnixNano(), 0, l.Text, sampleTypeLog}) + textBytes += len(l.Text) + } + if got := samplesWhere(t, "fingerprint = "+fp); !slices.Equal(got, want) { + t.Errorf("%s: %s rows\n got %v\nwant %v", labels, samplesTable, got, want) + } + + var index []string + for _, row := range query(t, fmt.Sprintf("SELECT DISTINCT key, val, type FROM %s WHERE fingerprint = %s ORDER BY key", + table(labelIndexTable), fp)) { + index = append(index, fmt.Sprintf("%v=%v type %v", row["key"], row["val"], row["type"])) + } + var wantIndex []string + for _, k := range []string{"app", seed.RunLabel, "pod", "service_name"} { + v := s.Labels[k] + if k == "service_name" { + v = s.Labels["app"] + } + wantIndex = append(wantIndex, fmt.Sprintf("%s=%s type %d", k, v, sampleTypeLog)) + } + if !slices.Equal(index, wantIndex) { + t.Errorf("%s: %s rows %v, want %v", labels, labelIndexTable, index, wantIndex) + } + + rollup := query(t, fmt.Sprintf("SELECT toString(countMerge(count)) AS lines, toString(sum(bytes)) AS bytes, groupUniqArray(type) AS types FROM %s WHERE fingerprint = %s", + table(logsRollupTable), fp)) + wantRollup := fmt.Sprintf("lines %d, bytes %d, types [%d]", len(s.Lines), textBytes, sampleTypeLog) + if got := fmt.Sprintf("lines %v, bytes %v, types %v", rollup[0]["lines"], rollup[0]["bytes"], rollup[0]["types"]); got != wantRollup { + t.Errorf("%s: %s %s, want %s", labels, logsRollupTable, got, wantRollup) + } + } +} + +// seriesRow is a row of the series table. Rows are read without FINAL: the +// table is a ReplacingMergeTree(date) ordered by fingerprint and type, and +// FINAL keeps only the newest day's row of a stream. +type seriesRow struct { + Date string `json:"date"` + Fingerprint string `json:"fp"` + Labels string `json:"labels"` + Name string `json:"name"` + Type int `json:"type"` + Metadata string `json:"metadata"` +} + +func (s seriesRow) labelMap(t *testing.T) map[string]string { + t.Helper() + var m map[string]string + if err := json.Unmarshal([]byte(s.Labels), &m); err != nil { + t.Fatalf("labels %q are not a JSON object of strings: %v", s.Labels, err) + } + return m +} + +// sampleRow is a row of the samples table. +type sampleRow struct { + Fingerprint string + TimestampNs int64 + Value float64 + String string + Type int +} + +func seriesWhere(t *testing.T, where string) []seriesRow { + t.Helper() + var out []seriesRow + for _, row := range query(t, fmt.Sprintf("SELECT DISTINCT date, toString(fingerprint) AS fp, labels, name, type, metadata FROM %s WHERE %s ORDER BY date, fp", + table(seriesTable), where)) { + raw, _ := json.Marshal(row) + var s seriesRow + if err := json.Unmarshal(raw, &s); err != nil { + t.Fatalf("%s row %s: %v", seriesTable, raw, err) + } + out = append(out, s) + } + return out +} + +func samplesWhere(t *testing.T, where string) []sampleRow { + t.Helper() + var out []sampleRow + for _, row := range query(t, fmt.Sprintf("SELECT toString(fingerprint) AS fp, toString(timestamp_ns) AS ts, value, string, type FROM %s WHERE %s ORDER BY fingerprint, timestamp_ns", + table(samplesTable), where)) { + ts, err := strconv.ParseInt(fmt.Sprint(row["ts"]), 10, 64) + if err != nil { + t.Fatalf("%s row %v: timestamp: %v", samplesTable, row, err) + } + value, _ := row["value"].(float64) + typ, _ := row["type"].(float64) + out = append(out, sampleRow{fmt.Sprint(row["fp"]), ts, value, fmt.Sprint(row["string"]), int(typ)}) + } + return out +} + +// waitForSamples waits until the samples table has want rows matching where, +// since gigapipe inserts asynchronously, and returns them. +func waitForSamples(t *testing.T, where string, want int) []sampleRow { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := samplesWhere(t, where) + if len(got) == want { + return got + } + if time.Now().After(deadline) { + t.Fatalf("after 30s %s has %d rows where %s, want %d: %v", samplesTable, len(got), where, want, got) + } + time.Sleep(200 * time.Millisecond) + } +} + +// waitForCase waits until the stream of one hand-written case has lines +// samples and at least seriesRows series rows, then returns its series rows. +func waitForCase(t *testing.T, run, name string, lines, seriesRows int) []seriesRow { + t.Helper() + where := fmt.Sprintf("JSONExtractString(labels, %s) = %s AND JSONExtractString(labels, 'case') = %s", + sqlString(seed.RunLabel), sqlString(run), sqlString(name)) + waitForSamples(t, fmt.Sprintf("fingerprint IN (SELECT fingerprint FROM %s WHERE %s)", table(seriesTable), where), lines) + return waitForSeries(t, where, seriesRows) +} + +// waitForSeries waits until the series table has at least want rows matching +// where, and returns them. gigapipe writes series rows and samples separately, +// so samples being there doesn't mean the series rows are. +func waitForSeries(t *testing.T, where string, want int) []seriesRow { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := seriesWhere(t, where) + if len(got) >= want { + return got + } + if time.Now().After(deadline) { + t.Fatalf("after 30s %s has %d rows where %s, want %d: %+v", seriesTable, len(got), where, want, got) + } + time.Sleep(200 * time.Millisecond) + } +} + +func pushRaw(t *testing.T, body string) { + t.Helper() + postBody(t, "/loki/api/v1/push", "application/json", []byte(body)) +} + +func postBody(t *testing.T, path, contentType string, body []byte) { + t.Helper() + resp, err := http.Post(baseURL()+path, contentType, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("POST %s (%s): status %d, body %q", path, contentType, resp.StatusCode, raw) + } +} + +// query runs a SELECT through clickhouseQuery (process_test.go) and returns +// its rows as JSON objects. +func query(t *testing.T, sql string) []map[string]any { + t.Helper() + var rows []map[string]any + for _, line := range strings.Split(clickhouseQuery(t, sql+" FORMAT JSONEachRow"), "\n") { + if line == "" { + continue + } + var row map[string]any + if err := json.Unmarshal([]byte(line), &row); err != nil { + t.Fatalf("ClickHouse row %q: %v", line, err) + } + rows = append(rows, row) + } + return rows +} + +// table qualifies a table name with gigapipe's database. +func table(name string) string { + return envOr("CLICKHOUSE_DB", "cloki") + "." + name +} + +// sqlString quotes s as a ClickHouse string literal. +func sqlString(s string) string { + return "'" + strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace(s) + "'" +} + +// days lists the UTC dates of lines, in order, each once. +func days(lines []seed.LogLine) []string { + var out []string + for _, l := range lines { + if d := day(l.Time); !slices.Contains(out, d) { + out = append(out, d) + } + } + return out +} + +// day is the UTC date gigapipe files a timestamp under in the series table. +func day(ts time.Time) string { + return ts.UTC().Format(time.DateOnly) +} diff --git a/test/integration/seed/seed.go b/test/integration/seed/seed.go index 818377ff4..4ad9ac350 100644 --- a/test/integration/seed/seed.go +++ b/test/integration/seed/seed.go @@ -24,6 +24,7 @@ import ( "github.com/golang/snappy" "github.com/google/pprof/profile" + "github.com/metrico/qryn/v5/writer/utils/proto/logproto" "github.com/metrico/qryn/v5/writer/utils/proto/prompb" commonv1 "go.opentelemetry.io/proto/otlp/common/v1" resourcev1 "go.opentelemetry.io/proto/otlp/resource/v1" @@ -459,3 +460,36 @@ func (f Fixture) PyroscopeIngest(p CPUProfile) (url.Values, string, []byte) { } return query, w.FormDataContentType(), body.Bytes() } + +// LokiPushProto encodes streams the way Promtail and Grafana Alloy send them +// (POST /loki/api/v1/push, application/x-protobuf): a snappy-compressed +// PushRequest whose labels are a selector string with the names sorted, such +// as {app="checkout", pod="p1"}. +func LokiPushProto(streams []LogStream) []byte { + req := &logproto.PushRequest{} + for _, s := range streams { + names := make([]string, 0, len(s.Labels)) + for name := range s.Labels { + names = append(names, name) + } + sort.Strings(names) + pairs := make([]string, len(names)) + for i, name := range names { + pairs[i] = name + "=" + strconv.Quote(s.Labels[name]) + } + stream := &logproto.StreamAdapter{Labels: "{" + strings.Join(pairs, ", ") + "}"} + for _, l := range s.Lines { + ns := l.Time.UnixNano() + stream.Entries = append(stream.Entries, &logproto.EntryAdapter{ + Timestamp: &logproto.Timestamp{Seconds: ns / int64(time.Second), Nanos: int32(ns % int64(time.Second))}, + Line: []byte(l.Text), + }) + } + req.Streams = append(req.Streams, stream) + } + raw, err := proto.Marshal(req) + if err != nil { + panic(err) + } + return snappy.Encode(nil, raw) +} diff --git a/test/integration/seed/seed_test.go b/test/integration/seed/seed_test.go index b04750a16..65f028c07 100644 --- a/test/integration/seed/seed_test.go +++ b/test/integration/seed/seed_test.go @@ -3,13 +3,17 @@ package seed import ( "bytes" "encoding/json" + "fmt" "mime" "mime/multipart" "slices" "testing" "time" + "github.com/golang/snappy" "github.com/google/pprof/profile" + "github.com/metrico/qryn/v5/writer/utils/proto/logproto" + "google.golang.org/protobuf/proto" ) var testStart = time.Date(2026, 1, 2, 3, 4, 0, 0, time.UTC) @@ -256,3 +260,39 @@ func TestProfilesMatchDeclaration(t *testing.T) { } } } + +// TestLokiPushProtoMatchesJSON decodes the protobuf body and checks it carries +// the same streams, labels, timestamps and lines as the JSON body. +func TestLokiPushProtoMatchesJSON(t *testing.T) { + streams := Default("r1", testStart).Logs() + raw, err := snappy.Decode(nil, LokiPushProto(streams)) + if err != nil { + t.Fatalf("not snappy: %v", err) + } + var req logproto.PushRequest + if err := proto.Unmarshal(raw, &req); err != nil { + t.Fatalf("not a PushRequest: %v", err) + } + if len(req.Streams) != len(streams) { + t.Fatalf("%d streams, want %d", len(req.Streams), len(streams)) + } + for i, s := range streams { + got := req.Streams[i] + want := fmt.Sprintf(`{app=%q, m2_run=%q, pod=%q}`, s.Labels["app"], s.Labels[RunLabel], s.Labels["pod"]) + if got.Labels != want { + t.Errorf("stream %d: labels %s, want %s", i, got.Labels, want) + } + if len(got.Entries) != len(s.Lines) { + t.Fatalf("stream %d: %d entries, want %d", i, len(got.Entries), len(s.Lines)) + } + for n, l := range s.Lines { + e := got.Entries[n] + if ns := e.Timestamp.Seconds*int64(time.Second) + int64(e.Timestamp.Nanos); ns != l.Time.UnixNano() { + t.Errorf("stream %d entry %d: time %d, want %d", i, n, ns, l.Time.UnixNano()) + } + if string(e.Line) != l.Text { + t.Errorf("stream %d entry %d: line %q, want %q", i, n, e.Line, l.Text) + } + } + } +}