diff --git a/reader/service/tempo_metrics.go b/reader/service/tempo_metrics.go index cc42cb2a..dbc76c39 100644 --- a/reader/service/tempo_metrics.go +++ b/reader/service/tempo_metrics.go @@ -5,6 +5,7 @@ import ( "context" stdsql "database/sql" "fmt" + "math" "slices" "strconv" "strings" @@ -56,55 +57,23 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics // Group results into time series by label combination seriesMap := make(map[string]*model.MetricsTimeSeries) hasByLabels := len(metricsFn.By) > 0 + isQuantile := metricsFn.Fn == "quantile_over_time" + var queryWideValues []float64 - err = queryMetrics(planCtx, planner, func(rows *stdsql.Rows) error { - byCount := len(resolvedByLabels) - var ts int64 - var value float64 - byVals := make([]string, byCount) - - scanArgs := make([]any, 2+byCount) - scanArgs[0] = &ts - scanArgs[1] = &value - for i := range byVals { - scanArgs[2+i] = &byVals[i] - } - - if err := rows.Scan(scanArgs...); err != nil { - return err - } - + addSample := func(byVals []string, quantile *float64, ts int64, value float64) { key := strings.Join(byVals, "\x00") + if quantile != nil { + key += "\x00" + strconv.FormatFloat(*quantile, 'g', -1, 64) + } series, ok := seriesMap[key] if !ok { - var labels []model.MetricsKeyValue - if !hasByLabels { - switch metricsFn.Fn { - case "rate", "count_over_time": - labels = append(labels, model.MetricsKeyValue{ - Key: "__name__", - Value: model.MetricsLabelValue{StringValue: metricsFn.Fn}, - }) - case "quantile_over_time": - p := 0.5 - if metricsFn.Percentile != nil { - p = *metricsFn.Percentile - } - labels = append(labels, model.MetricsKeyValue{ - Key: "p", - Value: model.MetricsLabelValue{DoubleValue: &p}, - }) - default: - labels = append(labels, model.MetricsKeyValue{ - Key: "__name__", - Value: model.MetricsLabelValue{StringValue: metricsFn.Fn}, - }) - } - } - for i, label := range resolvedByLabels { + labels := byLabelValues(resolvedByLabels, byVals) + if quantile != nil { + labels = append(labels, quantileLabel(quantile)) + } else if !hasByLabels { labels = append(labels, model.MetricsKeyValue{ - Key: label, - Value: model.MetricsLabelValue{StringValue: byVals[i]}, + Key: "__name__", + Value: model.MetricsLabelValue{StringValue: metricsFn.Fn}, }) } @@ -130,6 +99,38 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics TimestampMs: strconv.FormatInt(ts/1e6, 10), Value: value, }) + } + + err = queryMetrics(planCtx, planner, func(rows *stdsql.Rows) error { + var ts int64 + var value float64 + var values []float64 + var queryWide uint64 + byVals := make([]string, len(resolvedByLabels)) + + scanArgs := []any{&ts, &value} + if isQuantile { + scanArgs = []any{&ts, &values, &queryWide} + } + for i := range byVals { + scanArgs = append(scanArgs, &byVals[i]) + } + + if err := rows.Scan(scanArgs...); err != nil { + return err + } + + if !isQuantile { + addSample(byVals, nil, ts, value) + return nil + } + if queryWide != 0 { + queryWideValues = values + return nil + } + for i := range metricsFn.Quantiles { + addSample(byVals, &metricsFn.Quantiles[i], ts, values[i]) + } return nil }) if err != nil { @@ -214,12 +215,11 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics } for i := range result { - var keyParts []string - for _, lbl := range result[i].Labels { - isBy := slices.Contains(resolvedByLabels, lbl.Key) - if isBy { - keyParts = append(keyParts, lbl.Value.StringValue) - } + // By-labels lead a series' labels and are read by position: p may name one. + byLabels := result[i].Labels[:len(resolvedByLabels)] + keyParts := make([]string, len(byLabels)) + for j, lbl := range byLabels { + keyParts[j] = lbl.Value.StringValue } seriesKey := strings.Join(keyParts, "\x00") @@ -227,6 +227,12 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics if len(exByLabels) == 0 { groupExemplars = exemplarRows } + if isQuantile { + p := *result[i].Labels[len(byLabels)].Value.DoubleValue + groupExemplars = slices.DeleteFunc(slices.Clone(groupExemplars), func(ex exRow) bool { + return metricsFn.Quantiles[nearestQuantile(queryWideValues, float64(ex.durNs)/1e9)] != p + }) + } groupExemplars = capExemplars(tq, groupExemplars) tsToValue := make(map[int64]float64) @@ -241,13 +247,7 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics {Key: "trace:id", Value: model.MetricsLabelValue{StringValue: ex.traceID}}, } if hasByLabels { - for _, lbl := range result[i].Labels { - for _, byLabel := range resolvedByLabels { - if lbl.Key == byLabel { - labels = append(labels, lbl) - } - } - } + labels = append(labels, byLabels...) } else { labels = append(labels, model.MetricsKeyValue{ Key: "nestedSetParent", Value: model.MetricsLabelValue{IntValue: "-1"}, @@ -315,35 +315,40 @@ func (t *TempoService) MetricsQueryInstant(ctx context.Context, req *model.Metri return nil, err } + isQuantile := metricsFn.Fn == "quantile_over_time" var result []model.MetricsInstantSeries err = queryMetrics(planCtx, planner, func(rows *stdsql.Rows) error { - byCount := len(resolvedByLabels) var value float64 - byVals := make([]string, byCount) + var values []float64 + byVals := make([]string, len(resolvedByLabels)) - scanArgs := make([]any, 1+byCount) - scanArgs[0] = &value + scanArgs := []any{&value} + if isQuantile { + scanArgs = []any{&values} + } for i := range byVals { - scanArgs[1+i] = &byVals[i] + scanArgs = append(scanArgs, &byVals[i]) } if err := rows.Scan(scanArgs...); err != nil { return err } - labels := make([]model.MetricsKeyValue, byCount) - for i, label := range resolvedByLabels { - labels[i] = model.MetricsKeyValue{ - Key: label, - Value: model.MetricsLabelValue{StringValue: byVals[i]}, - } + if !isQuantile { + result = append(result, model.MetricsInstantSeries{ + Labels: byLabelValues(resolvedByLabels, byVals), + Value: value, + Exemplars: make([]any, 0), + }) + return nil + } + for i := range metricsFn.Quantiles { + result = append(result, model.MetricsInstantSeries{ + Labels: append(byLabelValues(resolvedByLabels, byVals), quantileLabel(&metricsFn.Quantiles[i])), + Value: values[i], + Exemplars: make([]any, 0), + }) } - - result = append(result, model.MetricsInstantSeries{ - Labels: labels, - Value: value, - Exemplars: make([]any, 0), - }) return nil }) if err != nil { @@ -360,6 +365,35 @@ func (t *TempoService) MetricsQueryInstant(ctx context.Context, req *model.Metri }, nil } +// byLabelValues pairs the by-labels with their values. +func byLabelValues(byLabels, byVals []string) []model.MetricsKeyValue { + labels := make([]model.MetricsKeyValue, len(byLabels)) + for i, label := range byLabels { + labels[i] = model.MetricsKeyValue{ + Key: label, + Value: model.MetricsLabelValue{StringValue: byVals[i]}, + } + } + return labels +} + +// quantileLabel is the p label of a quantile series. +func quantileLabel(quantile *float64) model.MetricsKeyValue { + return model.MetricsKeyValue{Key: "p", Value: model.MetricsLabelValue{DoubleValue: quantile}} +} + +// nearestQuantile returns the index of the value closest to v, the earliest +// on a tie. +func nearestQuantile(values []float64, v float64) int { + nearest, distance := 0, math.Inf(1) + for i, value := range values { + if d := math.Abs(value - v); d < distance { + nearest, distance = i, d + } + } + return nearest +} + // metricsPlannerContext parses the metrics query of req and resolves the // planner context for its range. func (t *TempoService) metricsPlannerContext(ctx context.Context, req *model.MetricsQueryRequest) ( @@ -388,7 +422,7 @@ func metricsRequest(fn *traceql_ir.MetricsFn, req *model.MetricsQueryRequest, pl Fn: fn.Fn, Attr: fn.Attr, By: fn.By, - Percentile: fn.Percentile, + Quantiles: fn.Quantiles, FromNS: planCtx.From.UnixNano(), ToNS: planCtx.To.UnixNano(), StepNS: req.Step.Nanoseconds(), diff --git a/reader/service/tempo_quantiles_behaviour_test.go b/reader/service/tempo_quantiles_behaviour_test.go new file mode 100644 index 00000000..c7155080 --- /dev/null +++ b/reader/service/tempo_quantiles_behaviour_test.go @@ -0,0 +1,136 @@ +package service + +import ( + "context" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/jmoiron/sqlx" + "github.com/metrico/qryn/v5/ctrl/logger" + "github.com/metrico/qryn/v5/ctrl/qryn/maintenance" + "github.com/metrico/qryn/v5/reader/model" + "github.com/metrico/qryn/v5/reader/utils/dsn" + "github.com/metrico/qryn/v5/shared/chtest" + "github.com/metrico/qryn/v5/shared/distconfig" + "github.com/stretchr/testify/require" +) + +const quantileHTTPEnv = "GIGAPIPE_TEST_CLICKHOUSE_HTTP" + +// seedQuantileSpans inserts 40 spans, one a second from 1 ms after quantileStart. +// Span i lasts i+1 ms and is in group a when i is even and b when odd. +func seedQuantileSpans(t *testing.T, conn clickhouse.Conn) { + t.Helper() + var rows []string + for i := range 40 { + group := "a" + if i%2 == 1 { + group = "b" + } + rows = append(rows, fmt.Sprintf("('%032x', '%016x', '', 's', 0, %d, %d, [('name','s'),('x','%s')])", + i/4+1, i+1, quantileStart.Add(time.Duration(i)*time.Second+time.Millisecond).UnixNano(), (i+1)*1000000, group)) + } + require.NoError(t, conn.Exec(context.Background(), + "INSERT INTO traces_input (trace_id, span_id, parent_id, name, service_name, timestamp_ns, duration_ns, tags) VALUES "+ + strings.Join(rows, ","))) +} + +// quantileService is a service over database name, on the given client options. +func quantileService(name string, opts *clickhouse.Options) *TempoService { + opts.Auth.Database = name + open := func() *sqlx.DB { return sqlx.NewDb(clickhouse.OpenDB(opts), "clickhouse") } + return serviceOver(name, &dsn.StableSqlxDBWrapper{DB: open(), GetDB: open, Name: name}) +} + +func TestQuantileListsOverNativeAndHTTP(t *testing.T) { + conn, name := chtest.Open(t) + require.NoError(t, maintenance.Update(conn, name, "", maintenance.CLUST_MODE_SINGLE, 7, "", "", false, logger.Logger)) + distconfig.Init() + seedQuantileSpans(t, conn) + t.Run("native", func(t *testing.T) { + checkQuantileLists(t, quantileService(name, &clickhouse.Options{Addr: []string{os.Getenv(chtest.AddrEnv)}})) + }) + t.Run("http", func(t *testing.T) { + addr := os.Getenv(quantileHTTPEnv) + if addr == "" { + t.Skip(quantileHTTPEnv + " is not set") + } + checkQuantileLists(t, quantileService(name, &clickhouse.Options{Addr: []string{addr}, Protocol: clickhouse.HTTP})) + }) +} + +func checkQuantileLists(t *testing.T, svc *TempoService) { + t.Helper() + const query = `{} | quantile_over_time(duration, .5, .95, .99) by (.x)` + req := &model.MetricsQueryRequest{Query: query, From: quantileStart, + To: quantileStart.Add(39500 * time.Millisecond), Step: 20 * time.Second} + res, err := svc.MetricsQueryRange(context.Background(), req) + require.NoError(t, err) + got := make(map[string]model.MetricsTimeSeries, len(res.Series)) + for _, s := range res.Series { + got[s.PromLabels] = s + } + // Linear interpolation over the span durations of each bucket and group, in ms. + want := map[string][2]float64{ + `{.x="a", p="0.5"}`: {10, 30}, + `{.x="a", p="0.95"}`: {18.1, 38.1}, + `{.x="a", p="0.99"}`: {18.82, 38.82}, + `{.x="b", p="0.5"}`: {11, 31}, + `{.x="b", p="0.95"}`: {19.1, 39.1}, + `{.x="b", p="0.99"}`: {19.82, 39.82}, + } + require.Len(t, got, len(want)) + exemplars := 0 + for labels, values := range want { + require.Contains(t, got, labels) + s := got[labels] + require.Len(t, s.Samples, 2, labels) + require.InDelta(t, values[0]/1e3, s.Samples[0].Value, 1e-9, labels) + require.InDelta(t, values[1]/1e3, s.Samples[1].Value, 1e-9, labels) + // Query-wide values are 20.5, 38.05 and 39.61 ms, so p=0.5 ends at the + // midpoint 29.275 ms and p=0.95 at 38.83 ms. + for _, seconds := range seriesExemplars(t, s) { + exemplars++ + ms := seconds * 1e3 + switch { + case strings.HasSuffix(labels, `p="0.5"}`): + require.Less(t, ms, 29.275, labels) + case strings.HasSuffix(labels, `p="0.95"}`): + require.Greater(t, ms, 29.275, labels) + require.Less(t, ms, 38.83, labels) + default: + require.Greater(t, ms, 38.83, labels) + } + } + } + // One span per bucket and group. + require.Equal(t, 4, exemplars) + + instant, err := svc.MetricsQueryInstant(context.Background(), req) + require.NoError(t, err) + require.Len(t, instant.Series, 6) + instantWant := map[string]float64{"a0.5": 20, "a0.95": 37.1, "a0.99": 38.62, "b0.5": 21, "b0.95": 38.1, "b0.99": 39.62} + for _, s := range instant.Series { + require.Len(t, s.Labels, 2) + key := fmt.Sprintf("%s%g", s.Labels[0].Value.StringValue, *s.Labels[1].Value.DoubleValue) + require.InDelta(t, instantWant[key]/1e3, s.Value, 1e-9, key) + } + + noBy, err := svc.MetricsQueryRange(context.Background(), &model.MetricsQueryRequest{ + Query: `{} | quantile_over_time(duration, .5, 1)`, From: req.From, To: req.To, Step: req.Step}) + require.NoError(t, err) + require.Len(t, noBy.Series, 2) + for _, s := range noBy.Series { + require.Len(t, s.Labels, 1) + require.Equal(t, "p", s.Labels[0].Key) + } + + noSpans, err := svc.MetricsQueryRange(context.Background(), &model.MetricsQueryRequest{ + Query: `{.x = "none"} | quantile_over_time(duration, .5, 1) by (.x)`, From: req.From, To: req.To, Step: req.Step}) + require.NoError(t, err) + require.Empty(t, noSpans.Series) +} diff --git a/reader/service/tempo_quantiles_cluster_behaviour_test.go b/reader/service/tempo_quantiles_cluster_behaviour_test.go new file mode 100644 index 00000000..e46f92c5 --- /dev/null +++ b/reader/service/tempo_quantiles_cluster_behaviour_test.go @@ -0,0 +1,425 @@ +package service + +import ( + "context" + stdsql "database/sql" + "encoding/json" + "fmt" + "math" + "os" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/jmoiron/sqlx" + "github.com/metrico/cloki-config/config" + "github.com/metrico/qryn/v5/ctrl/logger" + "github.com/metrico/qryn/v5/ctrl/qryn/maintenance" + "github.com/metrico/qryn/v5/reader/model" + "github.com/metrico/qryn/v5/reader/utils/dsn" + "github.com/metrico/qryn/v5/shared/chtest" + "github.com/metrico/qryn/v5/shared/distconfig" + "github.com/stretchr/testify/require" +) + +var clusterLevels = []float64{.5, .95, .99} + +const clusterStep = 20 * time.Second + +// clusterSpan is a seeded span, as the query sees it. +type clusterSpan struct { + i, trace int + tsNs int64 + durNs int64 + group string + spanHash uint64 +} + +// clusterStore is a two-shard database with a service on each protocol. +type clusterStore struct { + conn clickhouse.Conn + name string + cluster string + spans []clusterSpan + from time.Time + to time.Time +} + +// recordingSession keeps every statement a service ran and its error. +type recordingSession struct { + model.ISqlxDB + mu sync.Mutex + queries []string + errs []string +} + +func (r *recordingSession) QueryCtx(ctx context.Context, q string, args ...any) (*stdsql.Rows, error) { + rows, err := r.ISqlxDB.QueryCtx(ctx, q, args...) + r.mu.Lock() + defer r.mu.Unlock() + r.queries = append(r.queries, q) + if err != nil { + r.errs = append(r.errs, err.Error()) + } + return rows, err +} + +func (s *clusterStore) service(t *testing.T, opts *clickhouse.Options) (*TempoService, *recordingSession) { + t.Helper() + opts.Auth.Database = s.name + var opened []*sqlx.DB + open := func() *sqlx.DB { + d := sqlx.NewDb(clickhouse.OpenDB(opts), "clickhouse") + opened = append(opened, d) + return d + } + t.Cleanup(func() { + for _, d := range opened { + _ = d.Close() + } + }) + rec := &recordingSession{ISqlxDB: &dsn.StableSqlxDBWrapper{DB: open(), GetDB: open, Name: s.name}} + return &TempoService{ServiceData: model.ServiceData{Session: quantileRegistry{&model.DataDatabasesMap{ + Config: &config.ClokiBaseDataBase{Name: s.name, ClusterName: s.cluster}, Session: rec}}}}, rec +} + +// openClusterStore seeds 120 spans, one a second from 1 ms after start, in +// traces of 3. Durations are distinct and out of order. Group is a or b by +// parity, and a alone in the last bucket. +func openClusterStore(t *testing.T, start time.Time) *clusterStore { + t.Helper() + conn, name, cluster := chtest.OpenCluster(t) + require.NoError(t, maintenance.Update(conn, name, cluster, + maintenance.CLUST_MODE_SINGLE|maintenance.CLUST_MODE_DISTRIBUTED, 7, "", "", false, logger.Logger)) + distconfig.Init() + s := &clusterStore{conn: conn, name: name, cluster: cluster, from: start, to: start.Add(120 * time.Second)} + var rows []string + for i := range 120 { + group := "a" + if i%2 == 1 && i < 100 { + group = "b" + } + sp := clusterSpan{i: i, trace: i/3 + 1, tsNs: start.Add(time.Duration(i)*time.Second + time.Millisecond).UnixNano(), + durNs: int64((i*37)%211+1) * 1e6, group: group} + s.spans = append(s.spans, sp) + rows = append(rows, fmt.Sprintf("('%032x', '%016x', '', 's', %d, %d, [('name','s'),('x','%s'),('t','%d')])", + sp.trace, i+1, sp.tsNs, sp.durNs, group, sp.trace)) + } + ctx := context.Background() + exec := func(q string) { + t.Helper() + require.NoError(t, conn.Exec(ctx, q)) + } + const cols = "(trace_id, span_id, parent_id, name, timestamp_ns, duration_ns, tags)" + exec("CREATE TABLE seed_input AS traces_input ENGINE = Memory") + exec("INSERT INTO seed_input " + cols + " VALUES " + strings.Join(rows, ",")) + exec(`INSERT INTO tempo_traces_dist (oid, trace_id, span_id, parent_id, name, timestamp_ns, duration_ns) + SELECT oid, unhex(trace_id)::FixedString(16), unhex(span_id)::FixedString(8), unhex(parent_id), name, + timestamp_ns, duration_ns FROM seed_input`) + exec(`INSERT INTO tempo_traces_attrs_gin_dist (oid, date, key, val, trace_id, span_id, timestamp_ns, duration) + SELECT oid, toDate(toDateTime(intDiv(timestamp_ns, 1000000000), 'UTC')), tags.1, tags.2, unhex(trace_id)::FixedString(16), + unhex(span_id)::FixedString(8), timestamp_ns, duration_ns FROM seed_input ARRAY JOIN tags`) + exec("SYSTEM FLUSH DISTRIBUTED tempo_traces_dist") + exec("SYSTEM FLUSH DISTRIBUTED tempo_traces_attrs_gin_dist") + + r, err := conn.Query(ctx, "SELECT lower(hex(span_id)), cityHash64(span_id), shardNum() FROM tempo_traces_dist") + require.NoError(t, err) + defer r.Close() + hashes, perShard := map[string]uint64{}, map[uint32]int{} + for r.Next() { + var id string + var hash uint64 + var shard uint32 + require.NoError(t, r.Scan(&id, &hash, &shard)) + hashes[id] = hash + perShard[shard]++ + } + require.Len(t, hashes, len(s.spans)) + require.Len(t, perShard, 2, "spans on both shards") + t.Logf("spans per shard: %v", perShard) + for i := range s.spans { + s.spans[i].spanHash = hashes[fmt.Sprintf("%016x", s.spans[i].i+1)] + } + return s +} + +// exactQuantile is linear interpolation at q over values, which quantiles() +// returns below its reservoir size. Every seed here stays below that size. +func exactQuantile(values []float64, q float64) float64 { + sorted := slices.Sorted(slices.Values(values)) + pos := q * float64(len(sorted)-1) + lo := int(math.Floor(pos)) + if lo+1 >= len(sorted) { + return sorted[len(sorted)-1] + } + return sorted[lo] + (pos-float64(lo))*(sorted[lo+1]-sorted[lo]) +} + +func spanSeconds(spans []clusterSpan) []float64 { + res := make([]float64, len(spans)) + for i, sp := range spans { + res[i] = float64(sp.durNs) / 1e9 + } + return res +} + +func spanGroup(sp clusterSpan, by bool) string { + if by { + return sp.group + } + return "" +} + +func wantLabels(group string, by bool, q float64) string { + if by { + return fmt.Sprintf(`{.x="%s", p="%g"}`, group, q) + } + return fmt.Sprintf(`{p="%g"}`, q) +} + +// checkClusterRange compares a range query against spans, the ones it selects. +func checkClusterRange(t *testing.T, s *clusterStore, svc *TempoService, query string, spans []clusterSpan, by bool) { + t.Helper() + res, err := svc.MetricsQueryRange(context.Background(), &model.MetricsQueryRequest{ + Query: query, From: s.from, To: s.to, Step: clusterStep}) + require.NoError(t, err) + + stepMs := clusterStep.Milliseconds() + cells := map[string]map[int64][]float64{} + for _, sp := range spans { + group := spanGroup(sp, by) + if cells[group] == nil { + cells[group] = map[int64][]float64{} + } + bucket := sp.tsNs / 1e6 / stepMs * stepMs + cells[group][bucket] = append(cells[group][bucket], float64(sp.durNs)/1e9) + } + got := map[string]model.MetricsTimeSeries{} + for _, series := range res.Series { + require.NotContains(t, got, series.PromLabels) + got[series.PromLabels] = series + } + require.Len(t, got, len(cells)*len(clusterLevels), "series: %v", seriesNames(got)) + + queryWide := make([]float64, len(clusterLevels)) + all := spanSeconds(spans) + for i, q := range clusterLevels { + queryWide[i] = exactQuantile(all, q) + } + wantExemplars := 0 + for group, buckets := range cells { + wantExemplars += len(buckets) + for _, q := range clusterLevels { + labels := wantLabels(group, by, q) + require.Contains(t, got, labels) + series := got[labels] + wantLen := 1 + if by { + wantLen = 2 + require.Equal(t, ".x", series.Labels[0].Key) + require.Equal(t, group, series.Labels[0].Value.StringValue) + } + require.Len(t, series.Labels, wantLen, labels) + last := series.Labels[wantLen-1] + require.Equal(t, "p", last.Key, labels) + require.NotNil(t, last.Value.DoubleValue, labels) + require.Equal(t, q, *last.Value.DoubleValue, labels) + + // Every step of the range appears, and a step without spans is 0. + fromMs := s.from.UnixMilli() / stepMs * stepMs + wantSteps := int((s.to.UnixMilli()-fromMs)/stepMs) + 1 + require.Len(t, series.Samples, wantSteps, labels) + for j, sample := range series.Samples { + ms := fromMs + int64(j)*stepMs + require.Equal(t, strconv.FormatInt(ms, 10), sample.TimestampMs, labels) + want := 0.0 + if values, ok := buckets[ms]; ok { + want = exactQuantile(values, q) + } + require.InDelta(t, want, sample.Value, 1e-9, "%s at %d", labels, ms) + } + } + } + + seen := map[string]int{} + for labels, series := range got { + for _, raw := range series.Exemplars { + b, err := json.Marshal(raw) + require.NoError(t, err) + var ex struct { + Labels []model.MetricsKeyValue `json:"labels"` + Value float64 `json:"value"` + TimestampMs string `json:"timestampMs"` + } + require.NoError(t, json.Unmarshal(b, &ex)) + i := slices.IndexFunc(spans, func(sp clusterSpan) bool { + return math.Abs(float64(sp.durNs)/1e9-ex.Value) < 1e-9 + }) + require.GreaterOrEqual(t, i, 0, "%s: exemplar %v is no selected span", labels, ex.Value) + sp := spans[i] + require.Equal(t, strconv.FormatInt(sp.tsNs/1e6, 10), ex.TimestampMs, labels) + group := spanGroup(sp, by) + nearest := clusterLevels[nearestQuantile(queryWide, ex.Value)] + require.Equal(t, wantLabels(group, by, nearest), labels, "exemplar %v of span %d, query-wide %v", ex.Value, sp.i, queryWide) + names := make([]string, 0, len(ex.Labels)) + for _, l := range ex.Labels { + names = append(names, l.Key) + if l.Key == "trace:id" { + require.EqualValues(t, fmt.Sprintf("%032x", sp.trace), strings.ToLower(l.Value.StringValue), labels) + } + } + require.NotContains(t, names, "p", labels) + seen[fmt.Sprintf("%s/%d", group, sp.tsNs/1e6/stepMs)]++ + } + } + require.Len(t, seen, wantExemplars, "one exemplar per bucket and group: %v", seen) + for key, count := range seen { + require.Equal(t, 1, count, key) + } +} + +func seriesNames(got map[string]model.MetricsTimeSeries) []string { + names := make([]string, 0, len(got)) + for name := range got { + names = append(names, name) + } + slices.Sort(names) + return names +} + +// checkClusterInstant compares an instant query against spans, the ones it selects. +func checkClusterInstant(t *testing.T, s *clusterStore, svc *TempoService, query string, spans []clusterSpan, by bool) { + t.Helper() + res, err := svc.MetricsQueryInstant(context.Background(), &model.MetricsQueryRequest{ + Query: query, From: s.from, To: s.to, Step: clusterStep}) + require.NoError(t, err) + groups := map[string][]float64{} + for _, sp := range spans { + group := spanGroup(sp, by) + groups[group] = append(groups[group], float64(sp.durNs)/1e9) + } + require.Len(t, res.Series, len(groups)*len(clusterLevels)) + seen := map[string]bool{} + for _, series := range res.Series { + wantLen, group := 1, "" + if by { + wantLen = 2 + require.Equal(t, ".x", series.Labels[0].Key) + group = series.Labels[0].Value.StringValue + } + require.Len(t, series.Labels, wantLen) + last := series.Labels[wantLen-1] + require.Equal(t, "p", last.Key) + require.NotNil(t, last.Value.DoubleValue) + key := wantLabels(group, by, *last.Value.DoubleValue) + require.False(t, seen[key], key) + seen[key] = true + require.Contains(t, groups, group) + require.InDelta(t, exactQuantile(groups[group], *last.Value.DoubleValue), series.Value, 1e-9, key) + } +} + +func checkAllShapes(t *testing.T, s *clusterStore, svc *TempoService, rec *recordingSession) { + t.Helper() + const fn = `quantile_over_time(duration, .5, .95, .99)` + all := s.spans + for _, shape := range []struct { + name string + query string + spans []clusterSpan + by bool + }{ + {"by", `{} | ` + fn + ` by (.x)`, all, true}, + {"no by", `{} | ` + fn, all, false}, + {"filter by", `{.x = "a"} | ` + fn + ` by (.x)`, filterSpans(all, func(sp clusterSpan) bool { return sp.group == "a" }), true}, + {"one trace, one shard empty", `{.t = "5"} | ` + fn + ` by (.x)`, filterSpans(all, func(sp clusterSpan) bool { return sp.trace == 5 }), true}, + {"one trace no by", `{.t = "5"} | ` + fn, filterSpans(all, func(sp clusterSpan) bool { return sp.trace == 5 }), false}, + } { + t.Run(shape.name+"/range", func(t *testing.T) { checkClusterRange(t, s, svc, shape.query, shape.spans, shape.by) }) + t.Run(shape.name+"/instant", func(t *testing.T) { checkClusterInstant(t, s, svc, shape.query, shape.spans, shape.by) }) + } + for _, f := range []string{"0.5", ".25"} { + fraction, err := strconv.ParseFloat(f, 64) + require.NoError(t, err) + threshold := uint64(math.Ldexp(fraction, 64)) + kept := filterSpans(all, func(sp clusterSpan) bool { return sp.spanHash < threshold }) + require.Greater(t, len(kept), 5) + require.Less(t, len(kept), len(all)) + hint := ` with(sample=` + f + `)` + t.Run("sample "+f+"/range by", func(t *testing.T) { checkClusterRange(t, s, svc, `{} | `+fn+` by (.x)`+hint, kept, true) }) + t.Run("sample "+f+"/range", func(t *testing.T) { checkClusterRange(t, s, svc, `{} | `+fn+hint, kept, false) }) + t.Run("sample "+f+"/instant by", func(t *testing.T) { checkClusterInstant(t, s, svc, `{} | `+fn+` by (.x)`+hint, kept, true) }) + t.Run("sample "+f+"/instant", func(t *testing.T) { checkClusterInstant(t, s, svc, `{} | `+fn+hint, kept, false) }) + } + t.Run("no span", func(t *testing.T) { + res, err := svc.MetricsQueryRange(context.Background(), &model.MetricsQueryRequest{ + Query: `{.x = "none"} | ` + fn + ` by (.x)`, From: s.from, To: s.to, Step: clusterStep}) + require.NoError(t, err) + require.Empty(t, res.Series) + }) + require.Empty(t, rec.errs) + joined := strings.Join(rec.queries, "\n") + require.Contains(t, joined, "tempo_traces_dist") + require.Contains(t, joined, "GROUPING SETS") +} + +func filterSpans(spans []clusterSpan, keep func(clusterSpan) bool) []clusterSpan { + return slices.DeleteFunc(slices.Clone(spans), func(sp clusterSpan) bool { return !keep(sp) }) +} + +func clusterProtocols(t *testing.T, run func(*testing.T, *clickhouse.Options)) { + t.Helper() + t.Run("native", func(t *testing.T) { + run(t, &clickhouse.Options{Addr: []string{os.Getenv(chtest.AddrEnv)}}) + }) + t.Run("http", func(t *testing.T) { + addr := os.Getenv(quantileHTTPEnv) + if addr == "" { + t.Skip(quantileHTTPEnv + " is not set") + } + run(t, &clickhouse.Options{Addr: []string{addr}, Protocol: clickhouse.HTTP}) + }) +} + +func TestQuantileListsOverNativeAndHTTPOnCluster(t *testing.T) { + start := time.Now().UTC().Add(-2 * time.Hour).Truncate(clusterStep) + s := openClusterStore(t, start) + clusterProtocols(t, func(t *testing.T, opts *clickhouse.Options) { + svc, rec := s.service(t, opts) + checkAllShapes(t, s, svc, rec) + }) + require.NoError(t, s.conn.Exec(context.Background(), "SYSTEM FLUSH LOGS")) + r, err := s.conn.Query(context.Background(), `SELECT toUInt8(interface), count() FROM system.query_log + WHERE type = 'QueryFinish' AND is_initial_query AND current_database = currentDatabase() + AND query LIKE '%quantiles(%' GROUP BY 1 ORDER BY 1`) + require.NoError(t, err) + defer r.Close() + interfaces := map[uint8]uint64{} + for r.Next() { + var iface uint8 + var count uint64 + require.NoError(t, r.Scan(&iface, &count)) + interfaces[iface] = count + } + t.Logf("statements per interface (1 tcp, 2 http): %v", interfaces) + require.NotZero(t, interfaces[1]) + if os.Getenv(quantileHTTPEnv) != "" { + require.NotZero(t, interfaces[2]) + } +} + +// A bucket at time 0 on both shards stays a sample beside the query-wide row. +func TestQuantileBucketAtTimeZeroOnCluster(t *testing.T) { + s := openClusterStore(t, time.Unix(0, 0).UTC()) + clusterProtocols(t, func(t *testing.T, opts *clickhouse.Options) { + svc, rec := s.service(t, opts) + const fn = `quantile_over_time(duration, .5, .95, .99)` + checkClusterRange(t, s, svc, `{} | `+fn+` by (.x)`, s.spans, true) + checkClusterRange(t, s, svc, `{} | `+fn, s.spans, false) + require.Empty(t, rec.errs) + }) +} diff --git a/reader/service/tempo_quantiles_test.go b/reader/service/tempo_quantiles_test.go new file mode 100644 index 00000000..5b5c088d --- /dev/null +++ b/reader/service/tempo_quantiles_test.go @@ -0,0 +1,339 @@ +package service + +import ( + "context" + stdsql "database/sql" + "database/sql/driver" + "encoding/json" + "io" + "slices" + "strings" + "testing" + "time" + + "github.com/metrico/cloki-config/config" + "github.com/metrico/qryn/v5/reader/model" + "github.com/stretchr/testify/require" +) + +// quantileRegistry serves one session. +type quantileRegistry struct{ db *model.DataDatabasesMap } + +func (r quantileRegistry) GetDB(context.Context) (*model.DataDatabasesMap, error) { return r.db, nil } +func (r quantileRegistry) Run() {} +func (r quantileRegistry) Stop() {} +func (r quantileRegistry) Ping() error { return nil } + +func serviceOver(name string, session model.ISqlxDB) *TempoService { + return &TempoService{ServiceData: model.ServiceData{Session: quantileRegistry{&model.DataDatabasesMap{ + Config: &config.ClokiBaseDataBase{Name: name}, Session: session}}}} +} + +// fakeRows are rows of a statement the fake reader answers. +type fakeRows struct { + columns []string + rows [][]driver.Value + i int +} + +func (r *fakeRows) Columns() []string { return r.columns } +func (r *fakeRows) Close() error { return nil } +func (r *fakeRows) Next(dest []driver.Value) error { + if r.i >= len(r.rows) { + return io.EOF + } + copy(dest, r.rows[r.i]) + r.i++ + return nil +} + +// fakeReader answers a metrics query's statements: exemplar rows when the SQL +// reads the exemplar span, series rows when it selects a value, nothing +// otherwise. +type fakeReader struct { + series, exemplars [][]driver.Value + db *stdsql.DB +} + +func newFakeReader(series, exemplars [][]driver.Value) *fakeReader { + f := &fakeReader{series: series, exemplars: exemplars} + f.db = stdsql.OpenDB(fakeConnector{f}) + return f +} + +func (f *fakeReader) answer(query string) driver.Rows { + switch { + case strings.Contains(query, "any(("): + columns := []string{"ts", "trace_id", "duration_ns", "span_ts"} + if len(f.exemplars) > 0 { + columns = make([]string, len(f.exemplars[0])) + } + return &fakeRows{columns: columns, rows: f.exemplars} + case strings.Contains(query, " as value"): + return &fakeRows{columns: make([]string, len(f.series[0])), rows: f.series} + } + return &fakeRows{columns: []string{"none"}} +} + +func (f *fakeReader) GetName() string { return "fake-quantiles" } +func (f *fakeReader) QueryCtx(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) { + return f.db.QueryContext(ctx, query, args...) +} +func (f *fakeReader) ExecCtx(ctx context.Context, query string, args ...any) error { + _, err := f.db.ExecContext(ctx, query, args...) + return err +} +func (f *fakeReader) Conn(ctx context.Context) (*stdsql.Conn, error) { return f.db.Conn(ctx) } +func (f *fakeReader) Begin() (*stdsql.Tx, error) { return f.db.Begin() } +func (f *fakeReader) Close() { f.db.Close() } + +type fakeConnector struct{ f *fakeReader } + +func (c fakeConnector) Connect(context.Context) (driver.Conn, error) { return fakeConn(c), nil } +func (c fakeConnector) Driver() driver.Driver { return fakeDriver{} } + +type fakeDriver struct{} + +func (fakeDriver) Open(string) (driver.Conn, error) { return nil, driver.ErrSkip } + +type fakeConn struct{ f *fakeReader } + +func (c fakeConn) Prepare(string) (driver.Stmt, error) { return nil, driver.ErrSkip } +func (c fakeConn) Close() error { return nil } +func (c fakeConn) Begin() (driver.Tx, error) { return nil, driver.ErrSkip } +func (c fakeConn) QueryContext(_ context.Context, query string, _ []driver.NamedValue) (driver.Rows, error) { + return c.f.answer(query), nil +} + +var ( + quantileStart = time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + quantileReq = func(query string) *model.MetricsQueryRequest { + return &model.MetricsQueryRequest{Query: query, From: quantileStart, + To: quantileStart.Add(19 * time.Second), Step: 20 * time.Second} + } +) + +// A query-wide row of [.25, .75, 1] and one bucket for groups a and b. +func twoGroupSeries() [][]driver.Value { + ts := quantileStart.UnixNano() + return [][]driver.Value{ + {int64(0), []float64{0.25, 0.75, 1}, uint64(1), ""}, + {ts, []float64{0.25, 0.5, 0.9}, uint64(0), "a"}, + {ts, []float64{0.3, 0.7, 1}, uint64(0), "b"}, + } +} + +func exemplarRow(group string, seconds float64) []driver.Value { + ts := quantileStart.UnixNano() + row := []driver.Value{ts, "t", int64(seconds * 1e9), ts} + if group != "" { + row = append(row, group) + } + return row +} + +// seriesExemplars is each exemplar value of a series, in seconds. +func seriesExemplars(t *testing.T, s model.MetricsTimeSeries) []float64 { + t.Helper() + res := []float64{} + for _, e := range s.Exemplars { + b, err := json.Marshal(e) + require.NoError(t, err) + var v struct { + Value float64 `json:"value"` + } + require.NoError(t, json.Unmarshal(b, &v)) + res = append(res, v.Value) + } + return res +} + +func rangeSeries(t *testing.T, svc *TempoService, query string) map[string]model.MetricsTimeSeries { + t.Helper() + res, err := svc.MetricsQueryRange(context.Background(), quantileReq(query)) + require.NoError(t, err) + byLabels := make(map[string]model.MetricsTimeSeries, len(res.Series)) + for _, s := range res.Series { + byLabels[s.PromLabels] = s + } + require.Len(t, byLabels, len(res.Series)) + return byLabels +} + +func TestQuantileListFansOutPerGroup(t *testing.T) { + svc := serviceOver("fake", newFakeReader(twoGroupSeries(), nil)) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .95, .99) by (.x)`) + want := map[string]float64{ + `{.x="a", p="0.5"}`: 0.25, `{.x="a", p="0.95"}`: 0.5, `{.x="a", p="0.99"}`: 0.9, + `{.x="b", p="0.5"}`: 0.3, `{.x="b", p="0.95"}`: 0.7, `{.x="b", p="0.99"}`: 1, + } + require.Len(t, got, len(want)) + for labels, value := range want { + require.Contains(t, got, labels) + s := got[labels] + require.Len(t, s.Samples, 1, labels) + require.Equal(t, value, s.Samples[0].Value, labels) + require.Len(t, s.Labels, 2, labels) + require.Equal(t, ".x", s.Labels[0].Key) + require.Equal(t, "p", s.Labels[1].Key) + require.NotNil(t, s.Labels[1].Value.DoubleValue) + } +} + +func TestQuantileWithoutByCarriesOnlyP(t *testing.T) { + ts := quantileStart.UnixNano() + svc := serviceOver("fake", newFakeReader([][]driver.Value{ + {int64(0), []float64{0, 1}, uint64(1)}, + {ts, []float64{0, 1}, uint64(0)}, + }, nil)) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, 0, 1)`) + require.Len(t, got, 2) + require.Equal(t, 0.0, got[`{p="0"}`].Samples[0].Value) + require.Equal(t, 1.0, got[`{p="1"}`].Samples[0].Value) + require.Len(t, got[`{p="0"}`].Labels, 1) + require.NotNil(t, got[`{p="0"}`].Labels[0].Value.DoubleValue) +} + +// A span in the bucket at time 0 is a sample, not the query-wide row. +func TestQuantileBucketAtTimeZeroIsASample(t *testing.T) { + svc := serviceOver("fake", newFakeReader([][]driver.Value{ + {int64(0), []float64{1}, uint64(1)}, + {int64(0), []float64{0.5}, uint64(0)}, + }, nil)) + res, err := svc.MetricsQueryRange(context.Background(), &model.MetricsQueryRequest{ + Query: `{} | quantile_over_time(duration, .5)`, + From: time.Unix(0, 0), To: time.Unix(19, 0), Step: 20 * time.Second}) + require.NoError(t, err) + require.Len(t, res.Series, 1) + require.Equal(t, 0.5, res.Series[0].Samples[0].Value) +} + +func TestExemplarGoesToNearestQueryWideQuantile(t *testing.T) { + svc := serviceOver("fake", newFakeReader(twoGroupSeries(), [][]driver.Value{ + exemplarRow("a", 0.3), + // Nearest .75 query-wide; a's own bucket has .9 nearer than .5. + exemplarRow("a", 0.72), + exemplarRow("a", 0.95), + // Halfway between .25 and .75. + exemplarRow("b", 0.5), + exemplarRow("b", 0.8), + })) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .95, .99) by (.x)`) + for labels, want := range map[string][]float64{ + `{.x="a", p="0.5"}`: {0.3}, + `{.x="a", p="0.95"}`: {0.72}, + `{.x="a", p="0.99"}`: {0.95}, + `{.x="b", p="0.5"}`: {0.5}, + `{.x="b", p="0.95"}`: {0.8}, + `{.x="b", p="0.99"}`: {}, + } { + require.Equal(t, want, seriesExemplars(t, got[labels]), labels) + } +} + +func TestExemplarWithoutByGoesToNearestQuantile(t *testing.T) { + ts := quantileStart.UnixNano() + svc := serviceOver("fake", newFakeReader([][]driver.Value{ + {int64(0), []float64{0.25, 1}, uint64(1)}, + {ts, []float64{0.25, 1}, uint64(0)}, + }, [][]driver.Value{exemplarRow("", 0.3), exemplarRow("", 0.9)})) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .99)`) + require.Equal(t, []float64{0.3}, seriesExemplars(t, got[`{p="0.5"}`])) + require.Equal(t, []float64{0.9}, seriesExemplars(t, got[`{p="0.99"}`])) +} + +// exemplars=N caps each series after exemplars are assigned to it. +func TestExemplarCapIsPerQuantileSeries(t *testing.T) { + svc := serviceOver("fake", newFakeReader(twoGroupSeries(), [][]driver.Value{ + exemplarRow("a", 0.2), exemplarRow("a", 0.3), exemplarRow("a", 0.7), exemplarRow("a", 0.8), + })) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .95, .99) by (.x) with(exemplars=1)`) + require.Len(t, seriesExemplars(t, got[`{.x="a", p="0.5"}`]), 1) + require.Len(t, seriesExemplars(t, got[`{.x="a", p="0.95"}`]), 1) +} + +// Exemplar labels are the by-labels, without p. +func TestExemplarLabelsCarryNoP(t *testing.T) { + svc := serviceOver("fake", newFakeReader(twoGroupSeries(), [][]driver.Value{exemplarRow("a", 0.3)})) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .95, .99) by (.x)`) + b, err := json.Marshal(got[`{.x="a", p="0.5"}`].Exemplars) + require.NoError(t, err) + require.Contains(t, string(b), `".x"`) + require.NotContains(t, string(b), `"p"`) +} + +// A by-label named p is told from the quantile label by position. +func TestByLabelNamedP(t *testing.T) { + ts := quantileStart.UnixNano() + svc := serviceOver("fake", newFakeReader([][]driver.Value{ + {int64(0), []float64{0.25, 1}, uint64(1), ""}, + {ts, []float64{0.25, 1}, uint64(0), "a"}, + }, [][]driver.Value{exemplarRow("a", 0.3), exemplarRow("a", 0.9), exemplarRow("z", 0.3)})) + got := rangeSeries(t, svc, `{} | quantile_over_time(duration, .5, .99) by (p)`) + require.Equal(t, []float64{0.3}, seriesExemplars(t, got[`{p="a", p="0.5"}`])) + require.Equal(t, []float64{0.9}, seriesExemplars(t, got[`{p="a", p="0.99"}`])) + + instant := serviceOver("fake", newFakeReader([][]driver.Value{{[]float64{0.25, 1}, "a"}}, nil)) + res, err := instant.MetricsQueryInstant(context.Background(), + quantileReq(`{} | quantile_over_time(duration, .5, .99) by (p)`)) + require.NoError(t, err) + require.Len(t, res.Series, 2) + require.Equal(t, "a", res.Series[0].Labels[0].Value.StringValue) + require.Equal(t, 0.5, *res.Series[0].Labels[1].Value.DoubleValue) +} + +func TestInstantQuantileListHasTheRangeShape(t *testing.T) { + svc := serviceOver("fake", newFakeReader([][]driver.Value{ + {[]float64{0.25, 0.5, 0.9}, "a"}, + {[]float64{0.3, 0.7, 1}, "b"}, + }, nil)) + res, err := svc.MetricsQueryInstant(context.Background(), + quantileReq(`{} | quantile_over_time(duration, .5, .95, .99) by (.x)`)) + require.NoError(t, err) + type row struct { + x string + p float64 + value float64 + } + var got []row + for _, s := range res.Series { + require.Len(t, s.Labels, 2) + require.Equal(t, ".x", s.Labels[0].Key) + require.Equal(t, "p", s.Labels[1].Key) + got = append(got, row{s.Labels[0].Value.StringValue, *s.Labels[1].Value.DoubleValue, s.Value}) + } + require.True(t, slices.Equal(got, []row{ + {"a", 0.5, 0.25}, {"a", 0.95, 0.5}, {"a", 0.99, 0.9}, + {"b", 0.5, 0.3}, {"b", 0.95, 0.7}, {"b", 0.99, 1}, + }), "%v", got) + + noBy := serviceOver("fake", newFakeReader([][]driver.Value{{[]float64{0.25, 1}}}, nil)) + res, err = noBy.MetricsQueryInstant(context.Background(), quantileReq(`{} | quantile_over_time(duration, .5, 1)`)) + require.NoError(t, err) + require.Len(t, res.Series, 2) + require.Len(t, res.Series[1].Labels, 1) + require.Equal(t, "p", res.Series[1].Labels[0].Key) + require.Equal(t, 1.0, *res.Series[1].Labels[0].Value.DoubleValue) +} + +// Other functions keep one value: named when ungrouped, every exemplar on its group. +func TestOtherFunctionsKeepOneValuePerSeries(t *testing.T) { + ts := quantileStart.UnixNano() + ungrouped := serviceOver("fake", newFakeReader([][]driver.Value{{ts, 2.5}}, [][]driver.Value{exemplarRow("", 0.3)})) + got := rangeSeries(t, ungrouped, `{} | rate()`) + require.Equal(t, 2.5, got[`{__name__="rate"}`].Samples[0].Value) + require.Len(t, got[`{__name__="rate"}`].Exemplars, 1) + + grouped := serviceOver("fake", newFakeReader([][]driver.Value{{ts, 0.5, "a"}, {ts, 0.75, "b"}}, + [][]driver.Value{exemplarRow("a", 0.3), exemplarRow("a", 0.9), exemplarRow("b", 0.3)})) + got = rangeSeries(t, grouped, `{} | avg_over_time(duration) by (.x)`) + require.Equal(t, []float64{0.3, 0.9}, seriesExemplars(t, got[`{.x="a"}`])) + require.Equal(t, []float64{0.3}, seriesExemplars(t, got[`{.x="b"}`])) + + instant := serviceOver("fake", newFakeReader([][]driver.Value{{2.5}}, nil)) + res, err := instant.MetricsQueryInstant(context.Background(), quantileReq(`{} | rate()`)) + require.NoError(t, err) + require.Len(t, res.Series, 1) + require.Empty(t, res.Series[0].Labels) + require.Equal(t, 2.5, res.Series[0].Value) +} diff --git a/reader/tempo/metrics_query.go b/reader/tempo/metrics_query.go index a3c23545..f710c290 100644 --- a/reader/tempo/metrics_query.go +++ b/reader/tempo/metrics_query.go @@ -37,7 +37,7 @@ type MetricsRequest struct { Fn string Attr string By []string - Percentile *float64 + Quantiles []float64 FromNS int64 ToNS int64 StepNS int64 @@ -46,30 +46,55 @@ type MetricsRequest struct { // BuildMetricsRangeQuery builds a ClickHouse SQL query for a metrics range request. // It returns the query and the list of by-label keys (for result grouping). +// A quantile_over_time query also returns one query-wide row, marked by a +// query_wide column of 1 after value: its value is the list over all the spans. func BuildMetricsRangeQuery(req *MetricsRequest) (sql.ISelect, []string, error) { - valueExpr, err := buildAggExpr(req.Fn, req.Attr, float64(req.StepNS)/1e9, req.Percentile) + valueExpr, err := buildAggExpr(req.Fn, req.Attr, float64(req.StepNS)/1e9, req.Quantiles) if err != nil { return nil, nil, err } tsBucket := fmt.Sprintf("intDiv(main.timestamp_ns, %d) * %d", req.StepNS, req.StepNS) - query := spansQuery(req.Spans).Select( + columns := []sql.SQLObject{ sql.NewCol(sql.NewRawObject(tsBucket), "ts"), sql.NewCol(sql.NewRawObject(valueExpr), "value"), - ) + } + queryWide := req.Fn == "quantile_over_time" + if queryWide { + columns = append(columns, sql.NewCol(sql.NewRawObject("grouping(ts)"), "query_wide")) + } + query := spansQuery(req.Spans).Select(columns...) groupBy := []sql.SQLObject{sql.NewRawObject("ts")} resolvedByLabels := addByLabels(query, &groupBy, req.By, req.FromNS, req.ToNS, req.AttrsTable) + if queryWide { + groupBy = []sql.SQLObject{groupingWithQueryWide(groupBy)} + } query.GroupBy(groupBy...). OrderBy(sql.NewOrderBy(sql.NewRawObject("ts"), sql.ORDER_BY_DIRECTION_ASC)) return query, resolvedByLabels, nil } +// groupingWithQueryWide groups by keys and over the whole query. +func groupingWithQueryWide(keys []sql.SQLObject) sql.SQLObject { + return sql.NewCustomCol(func(ctx *sql.Ctx, options ...int) (string, error) { + parts := make([]string, len(keys)) + for i, key := range keys { + part, err := key.String(ctx, options...) + if err != nil { + return "", err + } + parts[i] = part + } + return fmt.Sprintf("GROUPING SETS ((%s), ())", strings.Join(parts, ", ")), nil + }) +} + // BuildMetricsInstantQuery builds a ClickHouse SQL query for an instant metrics query. func BuildMetricsInstantQuery(req *MetricsRequest) (sql.ISelect, []string, error) { windowS := float64(req.ToNS-req.FromNS) / 1e9 if windowS <= 0 { windowS = 1 } - valueExpr, err := buildAggExpr(req.Fn, req.Attr, windowS, req.Percentile) + valueExpr, err := buildAggExpr(req.Fn, req.Attr, windowS, req.Quantiles) if err != nil { return nil, nil, err } @@ -130,7 +155,7 @@ func addByLabels(query sql.ISelect, groupBy *[]sql.SQLObject, byLabels []string, } // buildAggExpr returns the ClickHouse aggregation expression for a metrics function. -func buildAggExpr(fn string, attr string, divisor float64, percentile *float64) (string, error) { +func buildAggExpr(fn string, attr string, divisor float64, quantiles []float64) (string, error) { if fn == "rate" { return fmt.Sprintf("toFloat64(count(*)) / %f", divisor), nil } @@ -139,13 +164,13 @@ func buildAggExpr(fn string, attr string, divisor float64, percentile *float64) if col == "" { return "", fmt.Errorf("quantile_over_time requires an attribute argument") } - p := 0.5 - if percentile != nil { - p = *percentile + levels := make([]string, len(quantiles)) + for i, q := range quantiles { + levels[i] = fmt.Sprintf("%g", q) } - expr := fmt.Sprintf("quantile(%g)(%s)", p, col) + expr := fmt.Sprintf("quantiles(%s)(%s)", strings.Join(levels, ", "), col) if col == "main.duration_ns" { - expr += " / 1e9" + expr = "arrayMap(x -> x / 1e9, " + expr + ")" } return expr, nil } diff --git a/reader/tempo/metrics_query_test.go b/reader/tempo/metrics_query_test.go index e555ed69..45c8a735 100644 --- a/reader/tempo/metrics_query_test.go +++ b/reader/tempo/metrics_query_test.go @@ -30,10 +30,12 @@ func TestMetricsQueriesReadOnlyTheSpans(t *testing.T) { return &MetricsRequest{Spans: testSpans(), Fn: fn, Attr: attr, By: by, FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "tempo_traces_attrs_gin"} } + quantileReq := req("quantile_over_time", "duration", "service.name") + quantileReq.Quantiles = []float64{0.5} var queries []sql.ISelect for _, r := range []*MetricsRequest{ req("rate", ""), req("count_over_time", "", "name", "span.http.method"), - req("avg_over_time", "duration"), req("quantile_over_time", "duration", "service.name"), + req("avg_over_time", "duration"), quantileReq, } { q, _, err := BuildMetricsRangeQuery(r) if err != nil { @@ -70,6 +72,73 @@ func TestMetricsQueriesReadOnlyTheSpans(t *testing.T) { } } +func quantileRequest(by ...string) *MetricsRequest { + return &MetricsRequest{Spans: testSpans(), Fn: "quantile_over_time", Attr: "duration", By: by, + Quantiles: []float64{0.5, 0.95, 1e-7}, FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"} +} + +// A quantile list is one quantiles() over the spans, in seconds, with no log2 buckets. +func TestQuantileListIsOneAggregate(t *testing.T) { + for name, build := range map[string]func(*MetricsRequest) (sql.ISelect, []string, error){ + "range": BuildMetricsRangeQuery, "instant": BuildMetricsInstantQuery, + } { + t.Run(name, func(t *testing.T) { + q, labels, err := build(quantileRequest("name", ".x")) + if err != nil { + t.Fatal(err) + } + if got := strings.Join(labels, ","); got != "name,.x" { + t.Errorf("labels %s", got) + } + res := render(t, q) + if !strings.Contains(res, "arrayMap(x -> x / 1e9, quantiles(0.5, 0.95, 1e-07)(main.duration_ns))") { + t.Errorf("no quantile list in seconds:\n%s", res) + } + if n := strings.Count(res, "quantiles("); n != 1 { + t.Errorf("%d quantiles():\n%s", n, res) + } + if strings.Contains(res, "log2") { + t.Errorf("has log2 buckets:\n%s", res) + } + }) + } +} + +// The range statement also computes the list over the whole query. +func TestQuantileRangeCarriesAQueryWideRow(t *testing.T) { + q, _, err := BuildMetricsRangeQuery(quantileRequest("name", ".x")) + if err != nil { + t.Fatal(err) + } + res := render(t, q) + if !strings.Contains(res, "GROUP BY GROUPING SETS ((ts, by_0, by_custom_0), ())") { + t.Errorf("no query-wide grouping set:\n%s", res) + } + if !regexp.MustCompile(`value, grouping\(ts\) as query_wide, main\.name as by_0`).MatchString(res) { + t.Errorf("no query-wide marker before the by columns:\n%s", res) + } + if strings.Contains(res, "WITH TOTALS") { + t.Errorf("uses totals:\n%s", res) + } +} + +func TestOnlyQuantileRangeHasAQueryWideRow(t *testing.T) { + instant, _, err := BuildMetricsInstantQuery(quantileRequest("name")) + if err != nil { + t.Fatal(err) + } + rate, _, err := BuildMetricsRangeQuery(&MetricsRequest{Spans: testSpans(), Fn: "rate", By: []string{"name"}, + FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"}) + if err != nil { + t.Fatal(err) + } + for _, q := range []sql.ISelect{instant, rate} { + if res := render(t, q); strings.Contains(res, "GROUPING SETS") || strings.Contains(res, "query_wide") { + t.Errorf("query-wide row:\n%s", res) + } + } +} + func TestByLabelsComeInColumnOrder(t *testing.T) { r := &MetricsRequest{Spans: testSpans(), Fn: "rate", By: []string{"span.a", "name", ".b", "service.name"}, FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"} diff --git a/reader/traceql/traceql_ir/ir.go b/reader/traceql/traceql_ir/ir.go index d9598e6f..b44e85d8 100644 --- a/reader/traceql/traceql_ir/ir.go +++ b/reader/traceql/traceql_ir/ir.go @@ -229,11 +229,12 @@ func (s *Select) String() string { // MetricsFn is the terminal metrics function, e.g. `| rate() by (name)`. type MetricsFn struct { - Fn string - Attr string - Percentile *float64 - Compare *CompareArgs - By []string + Fn string + Attr string + // Quantiles holds the distinct levels of quantile_over_time, in query order. + Quantiles []float64 + Compare *CompareArgs + By []string } // CompareArgs are the arguments of `compare({filter}, count, from, to)`. diff --git a/reader/traceql/traceql_ir/lower.go b/reader/traceql/traceql_ir/lower.go index d3955407..061520d9 100644 --- a/reader/traceql/traceql_ir/lower.go +++ b/reader/traceql/traceql_ir/lower.go @@ -2,6 +2,8 @@ package traceql_ir import ( "errors" + "fmt" + "slices" traceql_parser "github.com/metrico/qryn/v5/reader/traceql/traceql_parser" ) @@ -222,7 +224,11 @@ func lowerMetricsFn(m *traceql_parser.MetricsPipelineStage) (*MetricsFn, error) if m == nil { return nil, nil } - res := &MetricsFn{Fn: m.Fn, Attr: m.Attr, Percentile: m.Percentile} + quantiles, err := lowerQuantiles(m) + if err != nil { + return nil, err + } + res := &MetricsFn{Fn: m.Fn, Attr: m.Attr, Quantiles: quantiles} if m.By != nil { res.By = m.By.Labels } @@ -241,6 +247,30 @@ func lowerMetricsFn(m *traceql_parser.MetricsPipelineStage) (*MetricsFn, error) return res, nil } +// lowerQuantiles checks m's quantile list: one or more levels in [0, 1] on +// quantile_over_time, and none on any other function. Repeats are dropped. +func lowerQuantiles(m *traceql_parser.MetricsPipelineStage) ([]float64, error) { + if m.Fn != "quantile_over_time" { + if len(m.Quantiles) > 0 { + return nil, fmt.Errorf("%s does not take quantiles", m.Fn) + } + return nil, nil + } + if len(m.Quantiles) == 0 { + return nil, errors.New("quantile_over_time requires at least one quantile") + } + res := make([]float64, 0, len(m.Quantiles)) + for _, q := range m.Quantiles { + if q < 0 || q > 1 { + return nil, fmt.Errorf("quantile must be between 0 and 1: %g", q) + } + if !slices.Contains(res, q) { + res = append(res, q) + } + } + return res, nil +} + func lowerHints(w *traceql_parser.WithClause) []Hint { if w == nil { return nil diff --git a/reader/traceql/traceql_ir/lower_test.go b/reader/traceql/traceql_ir/lower_test.go index d69c0c7a..b96f95cc 100644 --- a/reader/traceql/traceql_ir/lower_test.go +++ b/reader/traceql/traceql_ir/lower_test.go @@ -255,7 +255,6 @@ func TestLowerSpansetOperators(t *testing.T) { } func TestLowerMetrics(t *testing.T) { - p := 0.9 from, to := int64(1), int64(2) for _, tc := range []struct { query string @@ -265,7 +264,11 @@ func TestLowerMetrics(t *testing.T) { {`{.a = "a"} | count_over_time() by (span.x, name)`, &Query{Pipeline: pipeline(a()), Metrics: &MetricsFn{Fn: "count_over_time", By: []string{"span.x", "name"}}}}, {`{.a = "a"} | quantile_over_time(duration, 0.9)`, &Query{Pipeline: pipeline(a()), - Metrics: &MetricsFn{Fn: "quantile_over_time", Attr: "duration", Percentile: &p}}}, + Metrics: &MetricsFn{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.9}}}}, + {`{.a = "a"} | quantile_over_time(duration, .5, .95, 1)`, &Query{Pipeline: pipeline(a()), + Metrics: &MetricsFn{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.5, 0.95, 1}}}}, + {`{.a = "a"} | quantile_over_time(duration, 0.5, .5, .9)`, &Query{Pipeline: pipeline(a()), + Metrics: &MetricsFn{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.5, 0.9}}}}, {`{.a = "a"} | compare({.b = "b"}, 10, 1, 2)`, &Query{Pipeline: pipeline(a()), Metrics: &MetricsFn{Fn: "compare", Compare: &CompareArgs{ Filter: strCmp(".b", "=", `"b"`), Count: 10, BaselineFrom: &from, BaselineTo: &to}}}}, @@ -365,6 +368,27 @@ func TestParseNamesInvalidDurationLiteral(t *testing.T) { } } +func TestParseRejectsQuantileLists(t *testing.T) { + for query, want := range map[string]string{ + `{} | quantile_over_time(duration)`: `quantile_over_time requires at least one quantile`, + `{} | quantile_over_time()`: `quantile_over_time requires at least one quantile`, + `{} | quantile_over_time(duration, 1.5)`: `quantile must be between 0 and 1: 1.5`, + `{} | quantile_over_time(duration, .5, 2)`: `quantile must be between 0 and 1: 2`, + `{} | rate(, .5)`: `rate does not take quantiles`, + `{} | min_over_time(duration, .5)`: `min_over_time does not take quantiles`, + `{} | histogram_over_time(duration, .5, .9)`: `histogram_over_time does not take quantiles`, + } { + t.Run(query, func(t *testing.T) { + _, err := Parse(query) + require.ErrorContains(t, err, want) + }) + } + for _, query := range []string{`{} | quantile_over_time(duration, -.1)`, `{} | quantile_over_time(duration, .5s)`} { + _, err := Parse(query) + require.Error(t, err, query) + } +} + func TestHasStructural(t *testing.T) { for query, want := range map[string]bool{ `{.a = "a"}`: false, diff --git a/reader/traceql/traceql_parser/model_v2.go b/reader/traceql/traceql_parser/model_v2.go index a2316576..55486c08 100644 --- a/reader/traceql/traceql_parser/model_v2.go +++ b/reader/traceql/traceql_parser/model_v2.go @@ -346,18 +346,18 @@ func (q *QuotedString) Unquote() (string, error) { // MetricsPipelineStage represents: | rate(), | count_over_time(), | compare(), etc. type MetricsPipelineStage struct { - Fn string `"|" @Label_name` - Attr string `"(" @Label_name?` - Percentile *float64 `( "," @Float )?` - CompSel *CompareSelector `@@?` - Cb string `")"` - By *ByClause `@@?` + Fn string `"|" @Label_name` + Attr string `"(" @Label_name?` + Quantiles []float64 `( "," (@Float | @Integer) )*` + CompSel *CompareSelector `@@?` + Cb string `")"` + By *ByClause `@@?` } func (m MetricsPipelineStage) String() string { res := "| " + m.Fn + "(" + m.Attr - if m.Percentile != nil { - res += fmt.Sprintf(", %g", *m.Percentile) + for _, q := range m.Quantiles { + res += fmt.Sprintf(", %g", q) } if m.CompSel != nil { res += m.CompSel.String() diff --git a/reader/traceql/traceql_parser/parser_test.go b/reader/traceql/traceql_parser/parser_test.go index ed60bdbc..6930cef2 100644 --- a/reader/traceql/traceql_parser/parser_test.go +++ b/reader/traceql/traceql_parser/parser_test.go @@ -100,8 +100,6 @@ func selectOf(fields ...*FieldExpr) PipelineElement { return PipelineElement{Select: res} } -func f64(f float64) *float64 { return &f } - func i64(i int64) *int64 { return &i } func TestParseSelectors(t *testing.T) { @@ -498,9 +496,19 @@ func TestParseMetricsFunctions(t *testing.T) { {`{} | count_over_time() by (span.x, name)`, metrics(empty(), &MetricsPipelineStage{Fn: "count_over_time", By: &ByClause{Labels: []string{"span.x", "name"}}})}, {`{} | quantile_over_time(duration, 0.9)`, metrics(empty(), - &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Percentile: f64(0.9)})}, + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.9}})}, {`{} | quantile_over_time(duration, .95)`, metrics(empty(), - &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Percentile: f64(0.95)})}, + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.95}})}, + {`{} | quantile_over_time(duration, 0, .9, 1)`, metrics(empty(), + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0, 0.9, 1}})}, + {`{} | quantile_over_time(duration, 1e-1)`, metrics(empty(), + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.1}})}, + {`{} | quantile_over_time(duration, .5, .95, .99) by (x)`, metrics(empty(), + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.5, 0.95, 0.99}, + By: &ByClause{Labels: []string{"x"}}})}, + {`{} | quantile_over_time(duration, .5, .95) by (.x)`, metrics(empty(), + &MetricsPipelineStage{Fn: "quantile_over_time", Attr: "duration", Quantiles: []float64{0.5, 0.95}, + By: &ByClause{Labels: []string{".x"}}})}, {`{} | histogram_over_time(duration)`, metrics(empty(), &MetricsPipelineStage{Fn: "histogram_over_time", Attr: "duration"})}, {`{} | compare({.a = "b"}, 10, 1, 2)`, metrics(empty(), &MetricsPipelineStage{Fn: "compare", CompSel: &CompareSelector{ @@ -594,6 +602,9 @@ func TestParseRejects(t *testing.T) { `{} | avg(duration) > 5 s`, `{duration > 1μs}`, `{duration > 1.5.5s}`, + `{} | quantile_over_time(duration, -.1)`, + `{} | quantile_over_time(duration, .5s)`, + `{} | quantile_over_time(duration, .5,)`, } { t.Run(q, func(t *testing.T) { _, err := Parse(q)