Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,10 @@ gigapipe returns the spans Tempo returns, except in the cases listed here.
- `sample=f` keeps a deterministic hash sample. Queries that relate spans
across a trace sample whole traces by trace ID, and other queries sample
spans by span ID. Tempo keeps one item in N with a counter.
- Sampled metrics values are returned unscaled. Tempo scales them up by the
observed sampling ratio, except `min_over_time` and `max_over_time`.
- Sampled metrics are scaled up by `1/f`: counts, sums, histogram bucket
counts and `compare()` counts. `min_over_time`, `max_over_time`,
`avg_over_time` and `quantile_over_time` are not scaled. Tempo scales by
the sampling ratio it observes, so values can differ slightly.
- `exemplars=N` caps exemplars per series, spread over the buckets that have
one. Tempo applies the cap per query evaluator, not per series.

Expand Down
63 changes: 39 additions & 24 deletions reader/service/tempo_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics
return executeHistogramRange(tq, req, planCtx)
}

mreq := metricsRequest(metricsFn, req, planCtx)
mreq := metricsRequest(tq, req, planCtx)
var resolvedByLabels []string
planner, err := clickhouse_transpiler.PlanMetrics(tq, func(spans *sql.With) (sql.ISelect, error) {
query, byLabels, err := tempo.BuildMetricsRangeQuery(over(mreq, spans))
Expand Down Expand Up @@ -206,7 +206,7 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics
}

if len(exemplarRows) > 0 {
includeDuration := metricsFn.Fn != "rate" && metricsFn.Fn != "count_over_time"
includeDuration := exemplarHasDuration(metricsFn.Fn)

exByGroup := make(map[string][]exRow)
for _, ex := range exemplarRows {
Expand Down Expand Up @@ -254,20 +254,14 @@ func (t *TempoService) MetricsQueryRange(ctx context.Context, req *model.Metrics
})
}
exTsMs := ex.spanTs / 1e6
val := float64(0)
if stepMs > 0 {
bucketMs := (exTsMs / stepMs) * stepMs
val = tsToValue[bucketMs]
}
if includeDuration {
labels = append(labels, model.MetricsKeyValue{
Key: "duration", Value: model.MetricsLabelValue{StringValue: metricsFormatDuration(ex.durNs)},
})
val = float64(ex.durNs) / 1e9
}
exList = append(exList, tempo.HistogramExemplar{
Labels: labels,
Value: val,
Value: exemplarValue(includeDuration, ex.durNs, exTsMs, stepMs, tsToValue),
TimestampMs: strconv.FormatInt(exTsMs, 10),
})
}
Expand Down Expand Up @@ -304,7 +298,7 @@ func (t *TempoService) MetricsQueryInstant(ctx context.Context, req *model.Metri
return executeCompareInstant(tq, req, planCtx)
}

mreq := metricsRequest(metricsFn, req, planCtx)
mreq := metricsRequest(tq, req, planCtx)
var resolvedByLabels []string
planner, err := clickhouse_transpiler.PlanMetrics(tq, func(spans *sql.With) (sql.ISelect, error) {
query, byLabels, err := tempo.BuildMetricsInstantQuery(over(mreq, spans))
Expand Down Expand Up @@ -382,8 +376,9 @@ func (t *TempoService) metricsPlannerContext(ctx context.Context, req *model.Met
return tq, planCtx, nil
}

// metricsRequest is the metrics request of fn over the planner context's range.
func metricsRequest(fn *traceql_ir.MetricsFn, req *model.MetricsQueryRequest, planCtx *shared.PlannerContext) tempo.MetricsRequest {
// metricsRequest is the metrics request of tq over the planner context's range.
func metricsRequest(tq *traceql_ir.Query, req *model.MetricsQueryRequest, planCtx *shared.PlannerContext) tempo.MetricsRequest {
fn := tq.Metrics
return tempo.MetricsRequest{
Fn: fn.Fn,
Attr: fn.Attr,
Expand All @@ -393,6 +388,7 @@ func metricsRequest(fn *traceql_ir.MetricsFn, req *model.MetricsQueryRequest, pl
ToNS: planCtx.To.UnixNano(),
StepNS: req.Step.Nanoseconds(),
AttrsTable: attrsTable(planCtx),
Scale: clickhouse_transpiler.SampleScale(tq),
}
}

Expand Down Expand Up @@ -439,7 +435,7 @@ func executeHistogramRange(
req *model.MetricsQueryRequest,
planCtx *shared.PlannerContext,
) (*model.MetricsQueryRangeResponse, error) {
mreq := metricsRequest(tq.Metrics, req, planCtx)
mreq := metricsRequest(tq, req, planCtx)
planner, err := clickhouse_transpiler.PlanMetrics(tq, func(spans *sql.With) (sql.ISelect, error) {
return tempo.BuildHistogramRangeQuery(over(mreq, spans))
})
Expand All @@ -453,7 +449,7 @@ func executeHistogramRange(
err = queryMetrics(planCtx, planner, func(rows *stdsql.Rows) error {
var ts int64
var bucketNs uint64
var count uint64
var count float64
if err := rows.Scan(&ts, &bucketNs, &count); err != nil {
return err
}
Expand All @@ -474,7 +470,7 @@ func executeHistogramRange(

series.Samples = append(series.Samples, model.MetricsSample{
TimestampMs: strconv.FormatInt(ts/1e6, 10),
Value: float64(count),
Value: count,
})
return nil
})
Expand Down Expand Up @@ -579,6 +575,24 @@ func executeHistogramRange(
}, nil
}

// exemplarHasDuration reports whether fn's exemplars carry their span's duration.
func exemplarHasDuration(fn string) bool {
return fn != "rate" && fn != "count_over_time"
}

// exemplarValue is the span's duration in seconds, unscaled, when the exemplar
// carries one. Otherwise it is the series point of the exemplar's step, scaled
// like the series, so the exemplar sits on the plotted line.
func exemplarValue(hasDuration bool, durNs, tsMs, stepMs int64, series map[int64]float64) float64 {
if hasDuration {
return float64(durNs) / 1e9
}
if stepMs <= 0 {
return 0
}
return series[(tsMs/stepMs)*stepMs]
}

// wantsExemplars reports whether tq's exemplars hint allows any exemplar.
func wantsExemplars(tq *traceql_ir.Query) bool {
limit, ok := tq.ExemplarLimit()
Expand Down Expand Up @@ -619,7 +633,7 @@ func executeCompareRange(
{Key: "__meta_type", Value: model.MetricsLabelValue{StringValue: "selection"}},
{Key: row.Key, Value: model.MetricsLabelValue{StringValue: row.Val}},
},
Samples: []model.MetricsSample{{TimestampMs: strconv.FormatInt(midpointMs, 10), Value: float64(row.SelectionCount)}},
Samples: []model.MetricsSample{{TimestampMs: strconv.FormatInt(midpointMs, 10), Value: row.SelectionCount}},
Exemplars: []any{},
})
}
Expand All @@ -629,7 +643,7 @@ func executeCompareRange(
{Key: "__meta_type", Value: model.MetricsLabelValue{StringValue: "baseline"}},
{Key: row.Key, Value: model.MetricsLabelValue{StringValue: row.Val}},
},
Samples: []model.MetricsSample{{TimestampMs: strconv.FormatInt(midpointMs, 10), Value: float64(row.BaselineCount)}},
Samples: []model.MetricsSample{{TimestampMs: strconv.FormatInt(midpointMs, 10), Value: row.BaselineCount}},
Exemplars: []any{},
})
}
Expand Down Expand Up @@ -660,7 +674,7 @@ func executeCompareInstant(
{Key: "__meta_type", Value: model.MetricsLabelValue{StringValue: "selection"}},
{Key: row.Key, Value: model.MetricsLabelValue{StringValue: row.Val}},
},
Value: float64(row.SelectionCount),
Value: row.SelectionCount,
})
}
if row.BaselineCount > 0 {
Expand All @@ -669,7 +683,7 @@ func executeCompareInstant(
{Key: "__meta_type", Value: model.MetricsLabelValue{StringValue: "baseline"}},
{Key: row.Key, Value: model.MetricsLabelValue{StringValue: row.Val}},
},
Value: float64(row.BaselineCount),
Value: row.BaselineCount,
})
}
})
Expand All @@ -686,7 +700,7 @@ func executeCompareInstant(

// queryCompare runs the compare() query of tq, passing each row to add.
func queryCompare(tq *traceql_ir.Query, planCtx *shared.PlannerContext, add func(tempo.CompareResultRow)) error {
creq := compareRequest(tq.Metrics, planCtx)
creq := compareRequest(tq, planCtx)
var selection traceql_ir.FieldExpr
if tq.Metrics.Compare != nil {
selection = tq.Metrics.Compare.Filter
Expand All @@ -710,17 +724,18 @@ func queryCompare(tq *traceql_ir.Query, planCtx *shared.PlannerContext, add func
})
}

// compareRequest is the compare() request of fn over the planner context's
// compareRequest is the compare() request of tq over the planner context's
// range. The baseline window defaults to that range.
func compareRequest(fn *traceql_ir.MetricsFn, planCtx *shared.PlannerContext) tempo.CompareRequest {
func compareRequest(tq *traceql_ir.Query, planCtx *shared.PlannerContext) tempo.CompareRequest {
res := tempo.CompareRequest{
FromNS: planCtx.From.UnixNano(),
ToNS: planCtx.To.UnixNano(),
BaselineFromNS: planCtx.From.UnixNano(),
BaselineToNS: planCtx.To.UnixNano(),
AttrsTable: attrsTable(planCtx),
Scale: clickhouse_transpiler.SampleScale(tq),
}
if c := fn.Compare; c != nil {
if c := tq.Metrics.Compare; c != nil {
res.TopN = c.Count
if c.BaselineFrom != nil && *c.BaselineFrom > 0 {
res.BaselineFromNS = *c.BaselineFrom
Expand All @@ -738,7 +753,7 @@ func unresolvedProbeContext(tq *traceql_ir.Query, planCtx *shared.PlannerContext
if tq.Metrics == nil || tq.Metrics.Fn != "compare" {
return planCtx
}
creq := compareRequest(tq.Metrics, planCtx)
creq := compareRequest(tq, planCtx)
res := *planCtx
res.From, res.To = time.Unix(0, creq.BaselineFromNS), time.Unix(0, creq.BaselineToNS)
return &res
Expand Down
111 changes: 109 additions & 2 deletions reader/service/tempo_metrics_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package service

import (
"regexp"
"slices"
"strconv"
"strings"
"testing"
"time"

"github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared"
"github.com/metrico/qryn/v5/reader/model"
"github.com/metrico/qryn/v5/reader/tempo"
traceql_ir "github.com/metrico/qryn/v5/reader/traceql/traceql_ir"
sql "github.com/metrico/qryn/v5/reader/utils/sql_select"
"github.com/stretchr/testify/require"
)

Expand All @@ -19,7 +25,7 @@ func TestMetricsCompareRequest(t *testing.T) {
}
q, err := traceql_ir.Parse(`{.a = "x"} | compare({.b = "y" || .c = 3}, 5)`)
require.NoError(t, err)
got := compareRequest(q.Metrics, ctx)
got := compareRequest(q, ctx)
require.Equal(t, 5, got.TopN)
require.Equal(t, int64(100e9), got.BaselineFromNS)
require.Equal(t, int64(200e9), got.BaselineToNS)
Expand All @@ -28,7 +34,7 @@ func TestMetricsCompareRequest(t *testing.T) {
q, err = traceql_ir.Parse(`{} | compare({.b = "y"}, 2, 50000000000, 150000000000)`)
require.NoError(t, err)
ctx.IsCluster = true
got = compareRequest(q.Metrics, ctx)
got = compareRequest(q, ctx)
require.Equal(t, int64(50e9), got.BaselineFromNS)
require.Equal(t, int64(150e9), got.BaselineToNS)
require.Equal(t, int64(100e9), got.FromNS)
Expand Down Expand Up @@ -87,3 +93,104 @@ func TestCapExemplars(t *testing.T) {
}
}
}

// with(sample=f) reaches metrics and compare() requests as 1/f, under span and
// trace hashing alike; any other hint, or one that keeps no spans, leaves them
// at 1.
func TestSampleHintSetsRequestScale(t *testing.T) {
ctx := &shared.PlannerContext{From: time.Unix(100, 0), To: time.Unix(200, 0)}
req := &model.MetricsQueryRequest{Step: time.Second}
for _, tc := range []struct {
selector string
hint string
want float64
}{
{`{.a = 1}`, ` with(sample=0.25)`, 4},
{`{.a = 1} >> {.b = 2}`, ` with(sample=0.25)`, 4},
{`{.a = 1}`, ``, 1},
{`{.a = 1}`, ` with(sample=1)`, 1},
{`{.a = 1}`, ` with(sample=true)`, 1},
{`{.a = 1}`, ` with(sample=0.` + strings.Repeat("0", 319) + `1)`, 1},
} {
q, err := traceql_ir.Parse(tc.selector + ` | rate()` + tc.hint)
require.NoError(t, err)
require.Equal(t, tc.want, metricsRequest(q, req, ctx).Scale, q)

q, err = traceql_ir.Parse(tc.selector + ` | compare({.c = 3})` + tc.hint)
require.NoError(t, err)
require.Equal(t, tc.want, compareRequest(q, ctx).Scale, q)
}
}

// A hint that keeps no spans renders the aggregate unscaled.
func TestHintKeepingNoSpansRendersUnscaled(t *testing.T) {
ctx := &shared.PlannerContext{From: time.Unix(100, 0), To: time.Unix(200, 0)}
spans := sql.NewWith(sql.NewSelect().Select(sql.NewRawObject("trace_id")).From(sql.NewRawObject("result")), "spans")
for name, build := range map[string]func(*tempo.MetricsRequest) (sql.ISelect, []string, error){
"range": tempo.BuildMetricsRangeQuery,
"instant": tempo.BuildMetricsInstantQuery,
} {
for _, step := range []time.Duration{time.Millisecond, time.Second, 15 * time.Second} {
req := &model.MetricsQueryRequest{Step: step}
render := func(query string) string {
q, err := traceql_ir.Parse(query)
require.NoError(t, err)
sel, _, err := build(over(metricsRequest(q, req, ctx), spans))
require.NoError(t, err)
str, err := sel.String(sql.DefaultCtx())
require.NoError(t, err)
return str
}
for _, fn := range []string{`rate()`, `count_over_time()`, `sum_over_time(duration)`} {
query := `{.a = 1} | ` + fn
for _, zeros := range []int{20, 305, 307, 319} {
got := render(query + ` with(sample=0.` + strings.Repeat("0", zeros) + `1)`)
require.Equal(t, render(query), got, "%s %s %d zeros at %s", name, fn, zeros, step)
}
}
}
}
}

// The smallest hint that keeps spans folds rate's divisor to a normal double
// at a small step.
func TestSmallestKeptSampleHintRendersNormalDivisor(t *testing.T) {
ctx := &shared.PlannerContext{From: time.Unix(100, 0), To: time.Unix(200, 0)}
req := &model.MetricsQueryRequest{Step: time.Millisecond}
spans := sql.NewWith(sql.NewSelect().Select(sql.NewRawObject("trace_id")).From(sql.NewRawObject("result")), "spans")
q, err := traceql_ir.Parse(`{.a = 1} | rate() with(sample=0.0000000000000000000542101086242752217003726400434970855712890625)`)
require.NoError(t, err)
sel, _, err := tempo.BuildMetricsRangeQuery(over(metricsRequest(q, req, ctx), spans))
require.NoError(t, err)
str, err := sel.String(sql.DefaultCtx())
require.NoError(t, err)

m := regexp.MustCompile(`count\(\*\)\) / ([0-9.e+-]+)`).FindStringSubmatch(str)
require.NotNil(t, m, str)
divisor, err := strconv.ParseFloat(m[1], 64)
require.NoError(t, err)
require.GreaterOrEqual(t, divisor, 0x1p-1022, str)
}

// Exemplars of rate and count_over_time sit on the scaled series point of their
// step; those of other functions keep their span's duration, unscaled.
func TestExemplarValueUnderScaling(t *testing.T) {
const (
stepMs = int64(1000)
tsMs = int64(5500)
durNs = int64(1500e6)
)
scaledSeries := map[int64]float64{5000: 8, 6000: 12}
for fn, want := range map[string]float64{
"rate": 8,
"count_over_time": 8,
"sum_over_time": 1.5,
"min_over_time": 1.5,
"max_over_time": 1.5,
"avg_over_time": 1.5,
"quantile_over_time": 1.5,
} {
require.Equal(t, want, exemplarValue(exemplarHasDuration(fn), durNs, tsMs, stepMs, scaledSeries), fn)
}
require.Zero(t, exemplarValue(false, durNs, tsMs, 0, scaledSeries))
}
Loading