diff --git a/reader/service/tempo_quoted_names_test.go b/reader/service/tempo_quoted_names_test.go new file mode 100644 index 00000000..95838966 --- /dev/null +++ b/reader/service/tempo_quoted_names_test.go @@ -0,0 +1,246 @@ +package service + +import ( + "slices" + "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" + "github.com/metrico/qryn/v5/reader/traceql/traceql_transpiler/clickhouse_transpiler" + dbversion "github.com/metrico/qryn/v5/reader/utils/dbVersion" + sql "github.com/metrico/qryn/v5/reader/utils/sql_select" + "github.com/stretchr/testify/require" +) + +const hostilePayload = `OR 1=1 --` + +// hostileNames each hold hostilePayload, spelled in a query and decoded. +var hostileNames = []struct{ title, spelled, decoded string }{ + {"backslash quote", `."a\\' OR 1=1 --"`, `a\' OR 1=1 --`}, + {"quote", `."a' OR 1=1 --"`, `a' OR 1=1 --`}, + {"trailing backslash", `."OR 1=1 --\\"`, `OR 1=1 --\`}, + {"NUL", ".\"a\x00' OR 1=1 --\"", "a\x00' OR 1=1 --"}, + {"newline", ".\"a\n' OR 1=1 --\"", "a\n' OR 1=1 --"}, +} + +func hostileContext() *shared.PlannerContext { + return &shared.PlannerContext{ + From: time.Unix(86390, 0).UTC(), + To: time.Unix(86410, 0).UTC(), + Limit: 5, + SpansPerSpanSet: 7, + TracesAttrsTable: "tempo_traces_attrs_gin", + TracesAttrsDistTable: "tempo_traces_attrs_gin_dist", + TracesTable: "tempo_traces", + TracesDistTable: "tempo_traces_dist", + VersionInfo: map[string]int64{dbversion.CapStructuralQueries: 0}, + } +} + +// outsideStringLiterals is query without its single-quoted literals, and those +// literals, under ClickHouse's backslash escapes. +func outsideStringLiterals(t *testing.T, query string) (outside string, literals []string) { + t.Helper() + var out, lit strings.Builder + inside := false + for i := 0; i < len(query); i++ { + c := query[i] + switch { + case !inside && c == '\'': + inside = true + lit.Reset() + case !inside: + out.WriteByte(c) + case c == '\\': + lit.WriteByte(c) + i++ + if i < len(query) { + lit.WriteByte(query[i]) + } + case c == '\'': + inside = false + literals = append(literals, lit.String()) + default: + lit.WriteByte(c) + } + } + require.False(t, inside, "unterminated string literal in:\n%s", query) + return out.String(), literals +} + +// requireNoEscape checks a name of plan's query stays inside string literals, +// and returns those literals. +func requireNoEscape(t *testing.T, plan shared.SQLRequestPlanner) []string { + t.Helper() + req, err := plan.Process(hostileContext()) + require.NoError(t, err) + res, err := req.String(sql.DefaultCtx()) + require.NoError(t, err) + outside, literals := outsideStringLiterals(t, res) + require.NotContains(t, outside, "1=1", "name escaped its string literal in:\n%s", res) + return literals +} + +// requireOneLiteral checks the name of plan's query reaches its SQL, only +// inside string literals. +func requireOneLiteral(t *testing.T, plan shared.SQLRequestPlanner) { + t.Helper() + for _, lit := range requireNoEscape(t, plan) { + if strings.Contains(lit, hostilePayload) { + return + } + } + require.Fail(t, "name does not reach the SQL") +} + +func hostileQuery(t *testing.T, tmpl, name string) *traceql_ir.Query { + t.Helper() + q, err := traceql_ir.Parse(strings.ReplaceAll(tmpl, "NAME", name)) + require.NoError(t, err) + return q +} + +func TestQuotedNameStaysOneStringLiteralInSearch(t *testing.T) { + for _, name := range hostileNames { + for _, tmpl := range []string{ + `{ NAME = 1 }`, + `{ NAME = "x" }`, + `{ NAME =~ "x" }`, + `{ NAME = nil }`, + `{ NAME = .b }`, + `{ NAME + 1 > 2 }`, + `{ NAME = 1 || .b = 2 }`, + `{ NAME = 1 } >> { NAME = 2 }`, + `{ NAME = 1 } && { NAME = 2 }`, + `{} | select(NAME)`, + `{} | by(NAME)`, + `{} | avg(NAME) > 1`, + `{} | by(NAME) | sum(NAME) > 1`, + } { + t.Run(name.title+" "+tmpl, func(t *testing.T) { + q := hostileQuery(t, tmpl, name.spelled) + plan, err := clickhouse_transpiler.Plan(q) + require.NoError(t, err) + requireOneLiteral(t, plan) + eval, err := clickhouse_transpiler.PlanEval(q) + require.NoError(t, err) + requireNoEscape(t, eval) + }) + } + } +} + +func TestQuotedNameStaysOneStringLiteralInUnresolvedProbes(t *testing.T) { + for _, name := range hostileNames { + for _, tmpl := range []string{ + `{ NAME = 1 } >> { NAME = 2 }`, + `{ .a = 1 } &>> { NAME = 2 }`, + `{ NAME = 1 } !~ { .a = 2 }`, + `{ NAME = 1 } >> { .a = 2 } | rate() by (.b)`, + } { + t.Run(name.title+" "+tmpl, func(t *testing.T) { + plan, err := clickhouse_transpiler.PlanUnresolvedProbes(hostileQuery(t, tmpl, name.spelled)) + require.NoError(t, err) + probes, err := plan.Process(hostileContext()) + require.NoError(t, err) + require.NotEmpty(t, probes) + for _, probe := range probes { + res, err := probe.Select.String(sql.DefaultCtx()) + require.NoError(t, err) + outside, literals := outsideStringLiterals(t, res) + require.NotContains(t, outside, "1=1", "name escaped its string literal in:\n%s", res) + require.True(t, slices.ContainsFunc(literals, func(lit string) bool { + return strings.Contains(lit, hostilePayload) + }), "name does not reach the probe:\n%s", res) + } + }) + } + } +} + +func TestQuotedNameStaysOneStringLiteralInMetricsBy(t *testing.T) { + builds := map[string]func(*tempo.MetricsRequest) (sql.ISelect, []string, error){ + "range": tempo.BuildMetricsRangeQuery, + "instant": tempo.BuildMetricsInstantQuery, + "exemplars": tempo.BuildGenericExemplarsQuery, + } + for _, name := range hostileNames { + for buildName, build := range builds { + for _, tmpl := range []string{ + `{} | rate() by (NAME)`, + `{ NAME = 1 } | rate() by (.b)`, + `{ NAME = 1 } >> { .b = 2 } | count_over_time() by (span.c, NAME)`, + } { + t.Run(name.title+" "+buildName+" "+tmpl, func(t *testing.T) { + q := hostileQuery(t, tmpl, name.spelled) + mreq := metricsRequest(q.Metrics, &model.MetricsQueryRequest{Step: time.Second}, hostileContext()) + plan, err := clickhouse_transpiler.PlanMetrics(q, func(spans *sql.With) (sql.ISelect, error) { + res, _, err := build(over(mreq, spans)) + return res, err + }) + require.NoError(t, err) + requireOneLiteral(t, plan) + }) + } + } + } +} + +func TestQuotedNameStaysOneStringLiteralInCompare(t *testing.T) { + for _, name := range hostileNames { + t.Run(name.title, func(t *testing.T) { + q := hostileQuery(t, `{ NAME = 1 } | compare({ NAME = 2 })`, name.spelled) + creq := compareRequest(q.Metrics, hostileContext()) + plan, err := clickhouse_transpiler.PlanCompare(q, q.Metrics.Compare.Filter, + time.Unix(0, creq.BaselineFromNS), time.Unix(0, creq.BaselineToNS), + func(baseline, selection *sql.With) (sql.ISelect, error) { + creq.Baseline, creq.Selection = baseline, selection + return tempo.BuildCompareQuery(&creq) + }) + require.NoError(t, err) + requireOneLiteral(t, plan) + }) + } +} + +func TestQuotedNameStaysOneStringLiteralInTagValues(t *testing.T) { + for _, name := range hostileNames { + t.Run(name.title, func(t *testing.T) { + q := hostileQuery(t, `{ NAME = 1 }`, name.spelled) + tags, err := clickhouse_transpiler.PlanTagsV2(q) + require.NoError(t, err) + requireOneLiteral(t, tags) + values, err := clickhouse_transpiler.PlanValuesV2(q, "x") + require.NoError(t, err) + requireOneLiteral(t, values) + values, err = clickhouse_transpiler.PlanValuesV2(nil, name.decoded) + require.NoError(t, err) + requireOneLiteral(t, values) + }) + } +} + +func TestMetricsByQuotedNameReadsItsKey(t *testing.T) { + for query, key := range map[string]string{ + `{} | rate() by (.foo)`: `foo`, + `{} | rate() by (."5xx")`: `5xx`, + `{} | rate() by (span."a b")`: `a b`, + `{} | rate() by (."foo")`: `foo`, + } { + t.Run(query, func(t *testing.T) { + q, err := traceql_ir.Parse(query) + require.NoError(t, err) + mreq := metricsRequest(q.Metrics, &model.MetricsQueryRequest{Step: time.Second}, hostileContext()) + mreq.Spans = sql.NewWith(sql.NewSelect().Select(sql.NewRawObject("trace_id")).From(sql.NewRawObject("s")), "metrics_spans") + build, _, err := tempo.BuildMetricsRangeQuery(&mreq) + require.NoError(t, err) + res, err := build.String(sql.DefaultCtx()) + require.NoError(t, err) + require.Contains(t, res, "anyIf(val, key = '"+key+"')") + }) + } +} diff --git a/reader/tempo/metrics_query.go b/reader/tempo/metrics_query.go index 445a1b58..a3c23545 100644 --- a/reader/tempo/metrics_query.go +++ b/reader/tempo/metrics_query.go @@ -7,6 +7,7 @@ import ( model "github.com/metrico/qryn/v5/reader/model" "github.com/metrico/qryn/v5/reader/traceql/timerange" + traceql_ir "github.com/metrico/qryn/v5/reader/traceql/traceql_ir" sql "github.com/metrico/qryn/v5/reader/utils/sql_select" ) @@ -197,13 +198,10 @@ func resolveAttrColumn(label string) string { return "" } -// stripAttrPrefix removes "span.", "resource." prefixes from attribute names for GIN lookup. +// stripAttrPrefix returns the storage key of a by label, without its scope. func stripAttrPrefix(label string) string { - if strings.HasPrefix(label, "span.") { - return label[5:] - } - if strings.HasPrefix(label, "resource.") { - return label[9:] + if key, ok := traceql_ir.AttributeKey(label); ok { + return key } return label } @@ -222,12 +220,9 @@ func buildByPivotCTE(labels []string, window sql.SQLCondition, attrsTable string for i, label := range labels { ginKeys[i] = stripAttrPrefix(label) aliases[i] = fmt.Sprintf("by_lbl_%d", i) + key, _ := sql.NewStringVal(ginKeys[i]).String(nil) selectCols = append(selectCols, - sql.NewCol( - sql.NewRawObject(fmt.Sprintf("anyIf(val, key = '%s')", - strings.ReplaceAll(ginKeys[i], "'", "\\'"))), - aliases[i], - ), + sql.NewCol(sql.NewRawObject("anyIf(val, key = "+key+")"), aliases[i]), ) } diff --git a/reader/tempo/metrics_query_test.go b/reader/tempo/metrics_query_test.go index b56948e5..e555ed69 100644 --- a/reader/tempo/metrics_query_test.go +++ b/reader/tempo/metrics_query_test.go @@ -94,6 +94,65 @@ func TestByLabelsComeInColumnOrder(t *testing.T) { } } +// A by attribute is pivoted on its storage key, without its scope. +func TestByAttributeReadsItsStorageKey(t *testing.T) { + for label, key := range map[string]string{ + ".foo": "foo", "span.foo": "foo", "resource.foo": "foo", ".5xx": "5xx", ".span.foo": "span.foo", + } { + t.Run(label, func(t *testing.T) { + r := &MetricsRequest{Spans: testSpans(), Fn: "rate", By: []string{label}, + FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"} + q, labels, err := BuildMetricsRangeQuery(r) + if err != nil { + t.Fatal(err) + } + if labels[0] != label { + t.Errorf("label %s", labels[0]) + } + res := render(t, q) + if want := "anyIf(val, key = '" + key + "')"; !strings.Contains(res, want) { + t.Errorf("want %s in:\n%s", want, res) + } + if want := "key IN ('" + key + "')"; !strings.Contains(res, want) { + t.Errorf("want %s in:\n%s", want, res) + } + }) + } +} + +// Series labels hold the plain name; the pivot reads its key. +func TestByLabelsHoldThePlainName(t *testing.T) { + r := &MetricsRequest{Spans: testSpans(), Fn: "rate", By: []string{"span.http status", ".5xx", `.a"b`}, + FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"} + for _, build := range []func(*MetricsRequest) (sql.ISelect, []string, error){ + BuildMetricsRangeQuery, BuildMetricsInstantQuery, BuildGenericExemplarsQuery} { + q, labels, err := build(r) + if err != nil { + t.Fatal(err) + } + if got := strings.Join(labels, ","); got != `span.http status,.5xx,.a"b` { + t.Errorf("labels %s", got) + } + if res := render(t, q); !strings.Contains(res, `key IN ('http status','5xx','a"b')`) { + t.Errorf("pivot keys in:\n%s", res) + } + } +} + +// A by key holding a backslash and a quote stays one string literal. +func TestByKeyRendersAsOneStringLiteral(t *testing.T) { + r := &MetricsRequest{Spans: testSpans(), Fn: "rate", By: []string{`span.a\' OR 1=1 --`}, + FromNS: 10e9, ToNS: 20e9, StepNS: 1e9, AttrsTable: "attrs"} + q, _, err := BuildMetricsRangeQuery(r) + if err != nil { + t.Fatal(err) + } + res := render(t, q) + if want := `anyIf(val, key = 'a\\\' OR 1=1 --')`; !strings.Contains(res, want) { + t.Errorf("want %s in:\n%s", want, res) + } +} + func TestCompareReadsBaselineAndSelection(t *testing.T) { baseline := sql.NewWith(sql.NewSelect().Select(sql.NewRawObject("trace_id")).From(sql.NewRawObject("b")), "baseline_spans") selection := sql.NewWith(sql.NewSelect().Select(sql.NewRawObject("trace_id")).From(sql.NewRawObject("s")), "selection_spans") diff --git a/reader/traceql/traceql_ir/field.go b/reader/traceql/traceql_ir/field.go index d97d75f3..870eb0c6 100644 --- a/reader/traceql/traceql_ir/field.go +++ b/reader/traceql/traceql_ir/field.go @@ -2,6 +2,7 @@ package traceql_ir import ( "strings" + "time" traceql_parser "github.com/metrico/qryn/v5/reader/traceql/traceql_parser" ) @@ -20,10 +21,11 @@ type Attribute struct { } // Static is a literal as written. A number is an integer or a float; strings -// keep their quotes. +// keep their quotes. Duration is the parsed value of a duration literal. type Static struct { - Kind ValueKind - Text string + Kind ValueKind + Text string + Duration time.Duration } // Unquote returns the content of a quoted string literal. diff --git a/reader/traceql/traceql_ir/lower.go b/reader/traceql/traceql_ir/lower.go index d13c5c42..d3955407 100644 --- a/reader/traceql/traceql_ir/lower.go +++ b/reader/traceql/traceql_ir/lower.go @@ -197,8 +197,8 @@ func lowerScalarAtom(a traceql_parser.ScalarAtom) (ScalarExpr, error) { case a.Aggregate != nil: return lowerAggregate(a.Aggregate) case a.Literal != nil: - if a.Literal.Unit != "" { - return &Static{Kind: ValueDuration, Text: a.Literal.Num + a.Literal.Unit}, nil + if a.Literal.Duration != "" { + return newDuration(a.Literal.Duration) } return &Static{Kind: ValueNumber, Text: a.Literal.Num}, nil } diff --git a/reader/traceql/traceql_ir/lower_field.go b/reader/traceql/traceql_ir/lower_field.go index a5844cb3..ef8411cb 100644 --- a/reader/traceql/traceql_ir/lower_field.go +++ b/reader/traceql/traceql_ir/lower_field.go @@ -2,7 +2,11 @@ package traceql_ir import ( "errors" + "fmt" "strings" + "time" + + "github.com/prometheus/common/model" traceql_parser "github.com/metrico/qryn/v5/reader/traceql/traceql_parser" ) @@ -116,8 +120,8 @@ func lowerAtom(a traceql_parser.FieldAtom) (FieldExpr, error) { case a.Str != nil: return &Static{Kind: ValueString, Text: a.Str.Str}, nil case a.Number != nil: - if a.Number.Unit != "" { - return &Static{Kind: ValueDuration, Text: a.Number.Num + a.Number.Unit}, nil + if a.Number.Duration != "" { + return newDuration(a.Number.Duration) } return &Static{Kind: ValueNumber, Text: a.Number.Num}, nil } @@ -161,9 +165,58 @@ func newUnary(op string, e FieldExpr) (FieldExpr, error) { } if s, ok := e.(*Static); ok && op == "-" && (s.Kind == ValueNumber || s.Kind == ValueDuration) { if text, negative := strings.CutPrefix(s.Text, "-"); negative { - return &Static{Kind: s.Kind, Text: text}, nil + return &Static{Kind: s.Kind, Text: text, Duration: -s.Duration}, nil } - return &Static{Kind: s.Kind, Text: "-" + s.Text}, nil + return &Static{Kind: s.Kind, Text: "-" + s.Text, Duration: -s.Duration}, nil } return &UnaryOp{Op: op, Expr: e}, nil } + +// newDuration builds a duration literal, with or without a leading minus. +func newDuration(text string) (*Static, error) { + literal, negative := strings.CutPrefix(text, "-") + if hasInvalidOctalPrefix(literal) { + return nil, fmt.Errorf("invalid duration %q", literal) + } + d, err := parseDuration(literal) + if err != nil { + return nil, fmt.Errorf("invalid duration %q", literal) + } + if negative { + d = -d + } + return &Static{Kind: ValueDuration, Text: text, Duration: d}, nil +} + +// hasInvalidOctalPrefix reports a leading integer written with a 0 and holding +// an 8 or 9, unless a dot makes it a float. +func hasInvalidOctalPrefix(literal string) bool { + end := 0 + for end < len(literal) && literal[end] >= '0' && literal[end] <= '9' { + end++ + } + if end == len(literal) || literal[end] == '.' { + return false + } + return literal[0] == '0' && strings.ContainsAny(literal[:end], "89") +} + +// parseDuration is copied from Tempo v3.1.0, pkg/traceql/lexer.go. +func parseDuration(d string) (time.Duration, error) { + var duration time.Duration + // Try to parse promql style durations first, to ensure that we support the same duration + // units as promql + prometheusDuration, err := model.ParseDuration(d) + if err != nil { + // Fall back to standard library's time.ParseDuration if a promql style + // duration couldn't be parsed. + duration, err = time.ParseDuration(d) + if err != nil { + return 0, err + } + } else { + duration = time.Duration(prometheusDuration) + } + + return duration, nil +} diff --git a/reader/traceql/traceql_ir/lower_test.go b/reader/traceql/traceql_ir/lower_test.go index b5b04539..d69c0c7a 100644 --- a/reader/traceql/traceql_ir/lower_test.go +++ b/reader/traceql/traceql_ir/lower_test.go @@ -2,6 +2,7 @@ package traceql_ir import ( "testing" + "time" "github.com/stretchr/testify/require" ) @@ -10,6 +11,10 @@ func cmp(attr, op string, kind ValueKind, text string) *BinaryOp { return &BinaryOp{Op: op, LHS: &Attribute{Name: attr}, RHS: &Static{Kind: kind, Text: text}} } +func durCmp(attr, op, text string, d time.Duration) *BinaryOp { + return &BinaryOp{Op: op, LHS: &Attribute{Name: attr}, RHS: &Static{Kind: ValueDuration, Text: text, Duration: d}} +} + func strCmp(attr, op, text string) *BinaryOp { return cmp(attr, op, ValueString, text) } func bin(op string, lhs, rhs FieldExpr) *BinaryOp { return &BinaryOp{Op: op, LHS: lhs, RHS: rhs} } @@ -47,8 +52,8 @@ func TestLowerFilters(t *testing.T) { {`{.a > - -3}`, cmp(".a", ">", ValueNumber, "3")}, {`{.a < 1.5}`, cmp(".a", "<", ValueNumber, "1.5")}, {`{.a = .95}`, cmp(".a", "=", ValueNumber, ".95")}, - {`{duration > 1.5ms}`, cmp("duration", ">", ValueDuration, "1.5ms")}, - {`{duration > -1ms}`, cmp("duration", ">", ValueDuration, "-1ms")}, + {`{duration > 1.5ms}`, durCmp("duration", ">", "1.5ms", 1500*time.Microsecond)}, + {`{duration > -1ms}`, durCmp("duration", ">", "-1ms", -time.Millisecond)}, {`{.a = true}`, cmp(".a", "=", ValueBool, "true")}, {`{status = error}`, cmp("status", "=", ValueIdent, "error")}, {`{span.foo = bar}`, cmp("span.foo", "=", ValueIdent, "bar")}, @@ -62,7 +67,7 @@ func TestLowerFilters(t *testing.T) { {`{nil = nil}`, &Static{Kind: ValueBool, Text: "false"}}, {`{!(.a = 1)}`, &UnaryOp{Op: "!", Expr: cmp(".a", "=", ValueNumber, "1")}}, {`{name = "x" && span:duration > 1s && rootServiceName = "y"}`, - bin("&&", bin("&&", strCmp("name", "=", `"x"`), cmp("span:duration", ">", ValueDuration, "1s")), + bin("&&", bin("&&", strCmp("name", "=", `"x"`), durCmp("span:duration", ">", "1s", time.Second)), strCmp("rootServiceName", "=", `"y"`))}, {`{(.a = 1 || .b = 2) && .c = 3}`, bin("&&", bin("||", cmp(".a", "=", ValueNumber, "1"), cmp(".b", "=", ValueNumber, "2")), @@ -134,7 +139,7 @@ func TestLowerScalarFilters(t *testing.T) { want Pipeline }{ {`{.a = "a"} | avg(duration) >= 1.5ms`, stages(a(), &ScalarFilter{Op: ">=", - LHS: &Aggregate{Fn: "avg", Arg: &Attribute{Name: "duration"}}, RHS: &Static{Kind: ValueDuration, Text: "1.5ms"}})}, + LHS: &Aggregate{Fn: "avg", Arg: &Attribute{Name: "duration"}}, RHS: &Static{Kind: ValueDuration, Text: "1.5ms", Duration: 1500 * time.Microsecond}})}, {`count() > 2`, stages(count(">", "2"))}, {`{.a = "a"} >> {.b = "b"} | count() > 2 | max(span.x) < -3`, stages(op(OpDescendant, a(), b()), count(">", "2"), &ScalarFilter{Op: "<", LHS: &Aggregate{Fn: "max", Arg: &Attribute{Name: "span.x"}}, RHS: &Static{Kind: ValueNumber, Text: "-3"}})}, @@ -313,6 +318,53 @@ func TestParseError(t *testing.T) { require.Error(t, err) } +func TestLowerDurationLiterals(t *testing.T) { + const day = 24 * time.Hour + for literal, want := range map[string]time.Duration{ + "1h30m": 90 * time.Minute, + "1d": day, + "1w": 7 * day, + "1y": 365 * day, + "1d12h": 36 * time.Hour, + ".5s": 500 * time.Millisecond, + "5.s": 5 * time.Second, + "1.5h": 90 * time.Minute, + "500ms": 500 * time.Millisecond, + "1µs": time.Microsecond, + "1us": time.Microsecond, + "1ns": time.Nanosecond, + "1s30m": 30*time.Minute + time.Second, + "1h15m30.918273645s": time.Hour + 15*time.Minute + 30*time.Second + 918273645*time.Nanosecond, + "-1d": -day, + "- -1d": day, + "07s": 7 * time.Second, + "010s": 10 * time.Second, + "00s": 0, + "09.5s": 9500 * time.Millisecond, + "09.s": 9 * time.Second, + "1h09m": time.Hour + 9*time.Minute, + } { + t.Run(literal, func(t *testing.T) { + got := mustParse(t, `{duration > `+literal+`}`).Pipeline.Elements[0].(*Selector).Filter.(*BinaryOp).RHS.(*Static) + require.Equal(t, ValueDuration, got.Kind) + require.Equal(t, want, got.Duration) + }) + } + got := mustParse(t, `{} | avg(duration) > -1h30m`).Pipeline.Elements[1].(*ScalarFilter).RHS.(*Static) + require.Equal(t, -90*time.Minute, got.Duration) +} + +func TestParseNamesInvalidDurationLiteral(t *testing.T) { + for _, literal := range []string{"1e3s", "1.5d", "1h30", "1x", "1hh", "1hx", "1000y", "1h.5", "08s", "019s", "09h30m"} { + for _, query := range []string{`{duration > ` + literal + `}`, `{} | avg(duration) > ` + literal} { + t.Run(query, func(t *testing.T) { + _, err := Parse(query) + require.ErrorContains(t, err, `"`+literal+`"`) + }) + } + } +} + func TestHasStructural(t *testing.T) { for query, want := range map[string]bool{ `{.a = "a"}`: false, @@ -335,3 +387,65 @@ func TestNumberLiteralTypes(t *testing.T) { require.Equal(t, want, TypeOf(&Static{Kind: ValueNumber, Text: text}), text) } } + +func TestLowerQuotedAttributeNames(t *testing.T) { + for q, want := range map[string]string{ + `{ ."5xx" = 1 }`: `.5xx`, + `{ span."http status" = 1 }`: `span.http status`, + `{ resource."http status" = 1 }`: `resource.http status`, + `{ ."foo".baz."bar" = 1 }`: `.foo.baz.bar`, + `{ ."foo.bar" = 1 }`: `.foo.bar`, + `{ .foo."bar \" baz" = 1 }`: `.foo.bar " baz`, + `{ .foo."baz \\".bar = 1 }`: `.foo.baz \.bar`, + `{ .foo"bar" = 1 }`: `.foobar`, + `{ ."foo"bar = 1 }`: `.foobar`, + `{ ."a""b" = 1 }`: `.ab`, + `{ .foo-"x" = 1 }`: `.foo-x`, + `{ .-"x" = 1 }`: `.-x`, + `{ ."" = 1 }`: `.`, + `{ span."" = 1 }`: `span.`, + `{ ."é" = 1 }`: `.é`, + "{ .\"a\nb\" = 1 }": ".a\nb", + `{ ."a'b" = 1 }`: `.a'b`, + `{ ."a\\'b" = 1 }`: `.a\'b`, + } { + t.Run(q, func(t *testing.T) { + got := mustParse(t, q).Pipeline.Elements[0].(*Selector).Filter + require.Equal(t, cmp(want, "=", ValueNumber, "1"), got) + }) + } +} + +func TestQuotedAndBareAttributeNamesLowerEqually(t *testing.T) { + for quoted, bare := range map[string]string{ + `{ ."foo" = 1 }`: `{ .foo = 1 }`, + `{ span."foo" = 1 }`: `{ span.foo = 1 }`, + `{ resource."service.name" = "a" }`: `{ resource.service.name = "a" }`, + `{ .a = ."b" }`: `{ .a = .b }`, + `{} | select(."foo", span."bar")`: `{} | select(.foo, span.bar)`, + `{} | by(."foo")`: `{} | by(.foo)`, + `{} | avg(."foo") > 1`: `{} | avg(.foo) > 1`, + `{} | rate() by (."foo", span."bar")`: `{} | rate() by (.foo, span.bar)`, + `{} | quantile_over_time(."foo", .5)`: `{} | quantile_over_time(.foo, .5)`, + `{} | compare({ ."foo" = 1 })`: `{} | compare({ .foo = 1 })`, + } { + t.Run(quoted, func(t *testing.T) { + require.Equal(t, mustParse(t, bare), mustParse(t, quoted)) + }) + } +} + +// Quoted names that spell a keyword or a scope stay attributes. +func TestQuotedNamesKeepTheirScope(t *testing.T) { + for q, want := range map[string]string{ + `{ ."duration" = 1 }`: `.duration`, + `{ ."true" = 1 }`: `.true`, + `{ ."span.foo" = 1 }`: `.span.foo`, + `{ span."name" = 1 }`: `span.name`, + } { + t.Run(q, func(t *testing.T) { + got := mustParse(t, q).Pipeline.Elements[0].(*Selector).Filter + require.Equal(t, cmp(want, "=", ValueNumber, "1"), got) + }) + } +} diff --git a/reader/traceql/traceql_parser/lexer_rules v2.go b/reader/traceql/traceql_parser/lexer_rules v2.go index 78f4d33b..50dd4df1 100644 --- a/reader/traceql/traceql_parser/lexer_rules v2.go +++ b/reader/traceql/traceql_parser/lexer_rules v2.go @@ -4,6 +4,13 @@ import ( "github.com/alecthomas/participle/v2/lexer" ) +// A quoted name part may run unclosed to the end of the input: the parser +// rejects it with its own error. +const ( + nameRune = `[.:a-zA-Z0-9_-]` + quotedNamePart = `"([^"\\]|\\(?s:.))*("|\\?\z)` +) + var TraceQLLexerRulesV2 = []lexer.SimpleRule{ {"Ocb", `\{`}, {"Ccb", `\}`}, @@ -41,12 +48,16 @@ var TraceQLLexerRulesV2 = []lexer.SimpleRule{ {"UnionSibling", `&~`}, {"Sibling", `~`}, + // A number directly followed by a duration unit, then more units and digits. + {"Duration", `([0-9]+\.?[0-9]*|\.[0-9]+)[nsumhµdwy][nsumhµdwy0-9.]*`}, // A digit right after a dot makes a number. {"Float", `([0-9]+\.[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?|[0-9]+[eE][-+]?[0-9]+`}, // Label_name supports dotted names and colon intrinsics (span:duration). // Keywords like true/false/nil are matched as Label_name and handled in the grammar. - {"Label_name", `(\.[a-zA-Z_][.:a-zA-Z0-9_-]*|[a-zA-Z_][.:a-zA-Z0-9_-]*)`}, + // After a dot scope a name mixes bare runes and quoted parts. + {"Label_name", `(\.|span\.|resource\.)` + nameRune + `*` + quotedNamePart + `(` + nameRune + `|` + quotedNamePart + `)*` + + `|\.[a-zA-Z_]` + nameRune + `*|[a-zA-Z_]` + nameRune + `*`}, {"Dot", `\.`}, {"And", `&&`}, diff --git a/reader/traceql/traceql_parser/lexer_rules_test.go b/reader/traceql/traceql_parser/lexer_rules_test.go index 70f7f8b8..0ee40725 100644 --- a/reader/traceql/traceql_parser/lexer_rules_test.go +++ b/reader/traceql/traceql_parser/lexer_rules_test.go @@ -44,8 +44,19 @@ func TestLexNumbersAndAttributes(t *testing.T) { {`.5e2`, []string{"Float:.5e2"}}, {`5`, []string{"Integer:5"}}, {`-.5`, []string{"Minus:-", "Float:.5"}}, - {`.5s`, []string{"Float:.5", "Label_name:s"}}, - {`5.s`, []string{"Float:5.", "Label_name:s"}}, + {`.5s`, []string{"Duration:.5s"}}, + {`5.s`, []string{"Duration:5.s"}}, + {`1h30m`, []string{"Duration:1h30m"}}, + {`1h15m30.918273645s`, []string{"Duration:1h15m30.918273645s"}}, + {`1µs`, []string{"Duration:1µs"}}, + {`1h30`, []string{"Duration:1h30"}}, + {`1.5d`, []string{"Duration:1.5d"}}, + {`1h.5`, []string{"Duration:1h.5"}}, + {`1hx`, []string{"Duration:1h", "Label_name:x"}}, + {`1e3s`, []string{"Float:1e3", "Label_name:s"}}, + {`1x`, []string{"Integer:1", "Label_name:x"}}, + {`5 s`, []string{"Integer:5", "Label_name:s"}}, + {`span.5s`, []string{"Label_name:span.5s"}}, {`.5xx`, []string{"Float:.5", "Label_name:xx"}}, {`.5.5`, []string{"Float:.5", "Float:.5"}}, {`1.2.3`, []string{"Float:1.2", "Float:.3"}}, @@ -62,3 +73,31 @@ func TestLexNumbersAndAttributes(t *testing.T) { }) } } + +// Quoted parts stay raw in the token; a name is one token whatever its parts hold. +func TestLexQuotedAttributeNames(t *testing.T) { + for _, tc := range []struct { + query string + want []string + }{ + {`."5xx"`, []string{`Label_name:."5xx"`}}, + {`span."http status"`, []string{`Label_name:span."http status"`}}, + {`resource."a"`, []string{`Label_name:resource."a"`}}, + {`."foo".baz."bar"`, []string{`Label_name:."foo".baz."bar"`}}, + {`.foo"bar"`, []string{`Label_name:.foo"bar"`}}, + {`."a""b"`, []string{`Label_name:."a""b"`}}, + {`.foo."bar \" baz"`, []string{`Label_name:.foo."bar \" baz"`}}, + {`."a <<& b"`, []string{`Label_name:."a <<& b"`}}, + {`."a b`, []string{`Label_name:."a b`}}, + {`."a\`, []string{`Label_name:."a\`}}, + {`.a = "b"`, []string{`Label_name:.a`, `Eq:=`, `Quoted_string:"b"`}}, + {`span:"name"`, []string{`Label_name:span:`, `Quoted_string:"name"`}}, + {`name"x"`, []string{`Label_name:name`, `Quoted_string:"x"`}}, + {`foo."x"`, []string{`Label_name:foo.`, `Quoted_string:"x"`}}, + {`parent."x"`, []string{`Label_name:parent.`, `Quoted_string:"x"`}}, + } { + t.Run(tc.query, func(t *testing.T) { + require.Equal(t, tc.want, lexTokens(t, tc.query)) + }) + } +} diff --git a/reader/traceql/traceql_parser/model_v2.go b/reader/traceql/traceql_parser/model_v2.go index 8ed35dda..a2316576 100644 --- a/reader/traceql/traceql_parser/model_v2.go +++ b/reader/traceql/traceql_parser/model_v2.go @@ -250,14 +250,14 @@ func (a Aggregate) String() string { return a.Fn + "(" + a.Arg.String() + ")" } -// ScalarLiteral is a number, with its duration unit if any. +// ScalarLiteral is a number or a duration. type ScalarLiteral struct { - Num string `@Minus? (@Float | @Integer)` - Unit string `@("ns"|"us"|"ms"|"s"|"m"|"h"|"d")?` + Num string `@Minus? (@Float | @Integer)` + Duration string `| @Minus? @Duration` } func (l ScalarLiteral) String() string { - return l.Num + l.Unit + return l.Num + l.Duration } // FieldExpr is a field expression as written: operands joined by binary @@ -312,14 +312,14 @@ func (a FieldAtom) String() string { return a.Name } -// NumberLiteral is an unsigned number, with its duration unit if any. +// NumberLiteral is an unsigned number or duration. type NumberLiteral struct { - Num string `(@Float | @Integer)` - Unit string `@("ns"|"us"|"ms"|"s"|"m"|"h"|"d")?` + Num string `(@Float | @Integer)` + Duration string `| @Duration` } func (l NumberLiteral) String() string { - return l.Num + l.Unit + return l.Num + l.Duration } type QuotedString struct { diff --git a/reader/traceql/traceql_parser/parser.go b/reader/traceql/traceql_parser/parser.go index 48025606..e2839cf1 100644 --- a/reader/traceql/traceql_parser/parser.go +++ b/reader/traceql/traceql_parser/parser.go @@ -1,6 +1,7 @@ package traceql_parser import ( + "errors" "fmt" "strings" @@ -9,24 +10,78 @@ import ( ) var parser = participle.MustBuild[TraceQLScript]( - participle.Lexer(TraceQLLexerDefinition), participle.UseLookahead(participle.MaxLookahead)) + participle.Lexer(TraceQLLexerDefinition), participle.UseLookahead(participle.MaxLookahead), + participle.Map(unquoteLabelName, "Label_name")) // misspeltOperators maps operators TraceQL lacks to the TraceQL spelling. var misspeltOperators = map[string]string{"<<&": "&<<", "<<~": "!<<"} +var ( + labelNameToken = TraceQLLexerDefinition.Symbols()["Label_name"] + spaceToken = TraceQLLexerDefinition.Symbols()["space"] + stringTokens = map[lexer.TokenType]bool{ + TraceQLLexerDefinition.Symbols()["Quoted_string"]: true, + TraceQLLexerDefinition.Symbols()["Ticked_string"]: true, + } + numberTokens = map[lexer.TokenType]bool{ + TraceQLLexerDefinition.Symbols()["Float"]: true, + TraceQLLexerDefinition.Symbols()["Integer"]: true, + TraceQLLexerDefinition.Symbols()["Duration"]: true, + } +) + func Parse(str string) (*TraceQLScript, error) { res, err := parser.ParseString("", str+" ") if err != nil { - if misspelt := misspeltOperatorError(str); misspelt != nil { - return nil, misspelt + if named := tokenError(str); named != nil { + return nil, named } return nil, err } return res, nil } -// misspeltOperatorError names the TraceQL spelling of a misspelt operator in str. -func misspeltOperatorError(str string) error { +// unquoteLabelName decodes the quoted parts of a name token into the plain name. +func unquoteLabelName(tok lexer.Token) (lexer.Token, error) { + if !strings.Contains(tok.Value, `"`) { + return tok, nil + } + name, err := unquoteName(tok.Value) + if err != nil { + return tok, participle.Errorf(tok.Pos, "%s", err) + } + tok.Value = name + return tok, nil +} + +// unquoteName drops the quotes of raw and decodes the escapes \" and \\ inside them. +func unquoteName(raw string) (string, error) { + var sb strings.Builder + quoted := false + for i := 0; i < len(raw); i++ { + c := raw[i] + switch { + case c == '"': + quoted = !quoted + case quoted && c == '\\': + i++ + if i == len(raw) || (raw[i] != '"' && raw[i] != '\\') { + return "", errors.New("invalid escape sequence") + } + sb.WriteByte(raw[i]) + default: + sb.WriteByte(c) + } + } + if quoted { + return "", errors.New(`unexpected EOF, expecting "`) + } + return sb.String(), nil +} + +// tokenError names a misspelt operator, a number directly followed by a name, +// or a string after a colon intrinsic's scope in str. +func tokenError(str string) error { lex, err := TraceQLLexerDefinition.Lex("", strings.NewReader(str)) if err != nil { return nil @@ -35,10 +90,21 @@ func misspeltOperatorError(str string) error { if err != nil { return nil } - for _, tok := range tokens { + var prev lexer.Token + for i, tok := range tokens { if spelling, ok := misspeltOperators[tok.Value]; ok { return fmt.Errorf("%s is not a TraceQL operator, use %s", tok.Value, spelling) } + if i > 0 && tok.Type == labelNameToken && numberTokens[tokens[i-1].Type] && + tokens[i-1].Pos.Offset+len(tokens[i-1].Value) == tok.Pos.Offset { + return fmt.Errorf("invalid literal %q", tokens[i-1].Value+tok.Value) + } + if stringTokens[tok.Type] && prev.Type == labelNameToken && strings.HasSuffix(prev.Value, ":") { + return errors.New("syntax error: unexpected STRING") + } + if tok.Type != spaceToken { + prev = tok + } } return nil } diff --git a/reader/traceql/traceql_parser/parser_test.go b/reader/traceql/traceql_parser/parser_test.go index f6cca56c..ed60bdbc 100644 --- a/reader/traceql/traceql_parser/parser_test.go +++ b/reader/traceql/traceql_parser/parser_test.go @@ -14,8 +14,8 @@ func str(s string) FieldOperand { return FieldOperand{Atom: FieldAtom{Str: &Quot func num(n string) FieldOperand { return FieldOperand{Atom: FieldAtom{Number: &NumberLiteral{Num: n}}} } -func dur(n, unit string) FieldOperand { - return FieldOperand{Atom: FieldAtom{Number: &NumberLiteral{Num: n, Unit: unit}}} +func dur(d string) FieldOperand { + return FieldOperand{Atom: FieldAtom{Number: &NumberLiteral{Duration: d}}} } func unary(ops string, o FieldOperand) FieldOperand { @@ -76,8 +76,12 @@ func agg(fn, attr string) ScalarExpr { return scalar(ScalarAtom{Aggregate: a}) } -func lit(num, unit string) ScalarExpr { - return scalar(ScalarAtom{Literal: &ScalarLiteral{Num: num, Unit: unit}}) +func lit(num string) ScalarExpr { + return scalar(ScalarAtom{Literal: &ScalarLiteral{Num: num}}) +} + +func litDur(d string) ScalarExpr { + return scalar(ScalarAtom{Literal: &ScalarLiteral{Duration: d}}) } func filter(lhs ScalarExpr, op string, rhs ScalarExpr) PipelineElement { @@ -120,13 +124,16 @@ func TestParseSelectors(t *testing.T) { {`{.a = 1.5e-3}`, term(".a", "=", num("1.5e-3"))}, {`{.a = .5e2}`, term(".a", "=", num(".5e2"))}, {`{.a = -.5}`, term(".a", "=", unary("-", num(".5")))}, - {`{duration > .5s}`, term("duration", ">", dur(".5", "s"))}, - {`{duration > 5.s}`, term("duration", ">", dur("5.", "s"))}, + {`{duration > .5s}`, term("duration", ">", dur(".5s"))}, + {`{duration > 5.s}`, term("duration", ">", dur("5.s"))}, {`{.foo.95 = 1}`, term(".foo.95", "=", num("1"))}, {`{span.5xx = 1}`, term("span.5xx", "=", num("1"))}, {`{.a <= 0}`, term(".a", "<=", num("0"))}, - {`{duration > 1.5ms}`, term("duration", ">", dur("1.5", "ms"))}, - {`{span:duration < 2s}`, term("span:duration", "<", dur("2", "s"))}, + {`{duration > 1.5ms}`, term("duration", ">", dur("1.5ms"))}, + {`{span:duration < 2s}`, term("span:duration", "<", dur("2s"))}, + {`{duration > 1h30m}`, term("duration", ">", dur("1h30m"))}, + {`{duration > 1d12h}`, term("duration", ">", dur("1d12h"))}, + {`{duration > 1µs}`, term("duration", ">", dur("1µs"))}, {`{.a = nil}`, term(".a", "=", name("nil"))}, {`{.a != nil}`, term(".a", "!=", name("nil"))}, {`{.a = true}`, term(".a", "=", name("true"))}, @@ -177,7 +184,7 @@ func TestParseFieldExpressions(t *testing.T) { {`{!-.a > 1}`, field(unary("!-", name(".a")), ">", num("1"))}, {`{nil != .a}`, field(name("nil"), "!=", name(".a"))}, {`{.a = .b || .c <= .d}`, field(name(".a"), "=", name(".b"), "||", name(".c"), "<=", name(".d"))}, - {`{(.a + .b) * 2 >= 1ms}`, field(parenField(field(name(".a"), "+", name(".b"))), "*", num("2"), ">=", dur("1", "ms"))}, + {`{(.a + .b) * 2 >= 1ms}`, field(parenField(field(name(".a"), "+", name(".b"))), "*", num("2"), ">=", dur("1ms"))}, } { t.Run(c.query, func(t *testing.T) { got, err := Parse(c.query) @@ -190,7 +197,7 @@ func TestParseFieldExpressions(t *testing.T) { got, err := Parse(`{} | avg(.a + -.b) > 2`) require.NoError(t, err) arg := field(name(".a"), "+", unary("-", name(".b"))) - require.Equal(t, script(expr(sel(nil)), filter(scalar(ScalarAtom{Aggregate: &Aggregate{Fn: "avg", Arg: arg}}), ">", lit("2", ""))), got) + require.Equal(t, script(expr(sel(nil)), filter(scalar(ScalarAtom{Aggregate: &Aggregate{Fn: "avg", Arg: arg}}), ">", lit("2"))), got) }) for _, q := range []string{ @@ -302,28 +309,29 @@ func TestParseScalarFilters(t *testing.T) { query string want *TraceQLScript }{ - {`{.a = "b"} | count() > 2`, script(expr(sel(a)), filter(agg("count", ""), ">", lit("2", "")))}, - {`{} | count() = 3.5`, script(expr(sel(nil)), filter(agg("count", ""), "=", lit("3.5", "")))}, - {`{} | avg(duration) >= 1.5ms`, script(expr(sel(nil)), filter(agg("avg", "duration"), ">=", lit("1.5", "ms")))}, - {`{} | max(span.x) < -3`, script(expr(sel(nil)), filter(agg("max", "span.x"), "<", lit("-3", "")))}, - {`{} | min(.x) != 0`, script(expr(sel(nil)), filter(agg("min", ".x"), "!=", lit("0", "")))}, - {`{} | sum(resource.x) <= 10s`, script(expr(sel(nil)), filter(agg("sum", "resource.x"), "<=", lit("10", "s")))}, - {`{} | avg(span:duration) > 1.5`, script(expr(sel(nil)), filter(agg("avg", "span:duration"), ">", lit("1.5", "")))}, - {`{} | avg(.foo) > .5`, script(expr(sel(nil)), filter(agg("avg", ".foo"), ">", lit(".5", "")))}, - {`{} | count() > -.5`, script(expr(sel(nil)), filter(agg("count", ""), ">", lit("-.5", "")))}, - {`{} | avg(duration) > .5s`, script(expr(sel(nil)), filter(agg("avg", "duration"), ">", lit(".5", "s")))}, + {`{.a = "b"} | count() > 2`, script(expr(sel(a)), filter(agg("count", ""), ">", lit("2")))}, + {`{} | count() = 3.5`, script(expr(sel(nil)), filter(agg("count", ""), "=", lit("3.5")))}, + {`{} | avg(duration) >= 1.5ms`, script(expr(sel(nil)), filter(agg("avg", "duration"), ">=", litDur("1.5ms")))}, + {`{} | max(span.x) < -3`, script(expr(sel(nil)), filter(agg("max", "span.x"), "<", lit("-3")))}, + {`{} | min(.x) != 0`, script(expr(sel(nil)), filter(agg("min", ".x"), "!=", lit("0")))}, + {`{} | sum(resource.x) <= 10s`, script(expr(sel(nil)), filter(agg("sum", "resource.x"), "<=", litDur("10s")))}, + {`{} | avg(span:duration) > 1.5`, script(expr(sel(nil)), filter(agg("avg", "span:duration"), ">", lit("1.5")))}, + {`{} | avg(.foo) > .5`, script(expr(sel(nil)), filter(agg("avg", ".foo"), ">", lit(".5")))}, + {`{} | count() > -.5`, script(expr(sel(nil)), filter(agg("count", ""), ">", lit("-.5")))}, + {`{} | avg(duration) > .5s`, script(expr(sel(nil)), filter(agg("avg", "duration"), ">", litDur(".5s")))}, + {`{} | avg(duration) > -1h30m`, script(expr(sel(nil)), filter(agg("avg", "duration"), ">", litDur("-1h30m")))}, // A scalar filter applies to the whole expression before it. {`{.a = "b"} && {} | count() > 1`, script(expr(sel(a), then("&&", sel(nil))), - filter(agg("count", ""), ">", lit("1", "")))}, + filter(agg("count", ""), ">", lit("1")))}, {`{.a = "b"} >> {} | count() > 1 | avg(duration) > 2ms`, script(expr(sel(a), then(">>", sel(nil))), - filter(agg("count", ""), ">", lit("1", "")), filter(agg("avg", "duration"), ">", lit("2", "ms")))}, + filter(agg("count", ""), ">", lit("1")), filter(agg("avg", "duration"), ">", litDur("2ms")))}, // Forms that parse and fail validation. - {`{} | 2 < count()`, script(expr(sel(nil)), filter(lit("2", ""), "<", agg("count", "")))}, + {`{} | 2 < count()`, script(expr(sel(nil)), filter(lit("2"), "<", agg("count", "")))}, {`{} | count() > count()`, script(expr(sel(nil)), filter(agg("count", ""), ">", agg("count", "")))}, {`{} | sum(.a) + 1 > 0`, script(expr(sel(nil)), filter(ScalarExpr{ Head: ScalarTerm{Head: ScalarFactor{Base: ScalarAtom{Aggregate: &Aggregate{Fn: "sum", Arg: field(name(".a"))}}}}, Ops: []ScalarSumOp{{Op: "+", Term: ScalarTerm{Head: ScalarFactor{Base: ScalarAtom{Literal: &ScalarLiteral{Num: "1"}}}}}}, - }, ">", lit("0", "")))}, + }, ">", lit("0")))}, } { t.Run(c.query, func(t *testing.T) { got, err := Parse(c.query) @@ -335,7 +343,7 @@ func TestParseScalarFilters(t *testing.T) { t.Run("a bare scalar filter", func(t *testing.T) { got, err := Parse(`count() > 2`) require.NoError(t, err) - require.Equal(t, &TraceQLScript{Pipeline: Pipeline{Head: filter(agg("count", ""), ">", lit("2", ""))}}, got) + require.Equal(t, &TraceQLScript{Pipeline: Pipeline{Head: filter(agg("count", ""), ">", lit("2"))}}, got) }) t.Run("arithmetic precedence", func(t *testing.T) { @@ -376,7 +384,7 @@ func TestParseScalarFilters(t *testing.T) { func TestParsePipelines(t *testing.T) { a := func() Operand { return sel(term(".a", "=", str(`"b"`))) } c := func() Operand { return sel(term(".c", "=", str(`"d"`))) } - count := filter(agg("count", ""), ">", lit("2", "")) + count := filter(agg("count", ""), ">", lit("2")) for _, tc := range []struct { query string want *TraceQLScript @@ -402,7 +410,7 @@ func TestParsePipelines(t *testing.T) { func TestParseGroupingStages(t *testing.T) { a := func() Operand { return sel(term(".a", "=", str(`"b"`))) } - count := filter(agg("count", ""), ">", lit("2", "")) + count := filter(agg("count", ""), ">", lit("2")) for _, tc := range []struct { query string want *TraceQLScript @@ -452,7 +460,7 @@ func TestParseSelectStages(t *testing.T) { {`{.a = "b"} | select(.x)`, script(expr(a()), selectOf(field(name(".x"))))}, {`{} | select(span.x, resource.y, duration, span:name) | count() > 2`, script(expr(sel(nil)), selectOf(field(name("span.x")), field(name("resource.y")), field(name("duration")), field(name("span:name"))), - filter(agg("count", ""), ">", lit("2", "")))}, + filter(agg("count", ""), ">", lit("2")))}, {`select(.x)`, &TraceQLScript{Pipeline: Pipeline{Head: selectOf(field(name(".x")))}}}, {`select(.x) | {.a = "b"}`, &TraceQLScript{Pipeline: Pipeline{Head: selectOf(field(name(".x"))), Stages: []PipelineElement{spanset(expr(a()))}}}}, {`({.a = "b"} | select(.x)) >> {}`, script(expr(paren(expr(a()), selectOf(field(name(".x")))), then(">>", sel(nil))))}, @@ -500,9 +508,9 @@ func TestParseMetricsFunctions(t *testing.T) { }})}, {`{} | compare({})`, metrics(empty(), &MetricsPipelineStage{Fn: "compare", CompSel: &CompareSelector{}})}, {`{.a = "b"} | count() > 2 | rate()`, metrics(a(), &MetricsPipelineStage{Fn: "rate"}, - filter(agg("count", ""), ">", lit("2", "")))}, + filter(agg("count", ""), ">", lit("2")))}, {`count() > 2 | rate()`, &TraceQLScript{ - Pipeline: Pipeline{Head: filter(agg("count", ""), ">", lit("2", ""))}, + Pipeline: Pipeline{Head: filter(agg("count", ""), ">", lit("2"))}, MetricsFn: &MetricsPipelineStage{Fn: "rate"}, }}, {`({} &>> {}) | rate()`, metrics(expr(paren(expr(sel(nil), then("&>>", sel(nil))))), @@ -580,6 +588,12 @@ func TestParseRejects(t *testing.T) { `{.a = "b"`, `{.a = "b"} {.c = "d"}`, `({.a = "b"}) ({.c = "d"})`, + `{duration > 5 s}`, + `{duration > .5 s}`, + `{duration > 5. s}`, + `{} | avg(duration) > 5 s`, + `{duration > 1μs}`, + `{duration > 1.5.5s}`, } { t.Run(q, func(t *testing.T) { _, err := Parse(q) @@ -588,6 +602,24 @@ func TestParseRejects(t *testing.T) { } } +func TestParseNamesNumberFollowedByLetter(t *testing.T) { + for q, literal := range map[string]string{ + `{ .a = 1x }`: `"1x"`, + `{ duration > 1e3s }`: `"1e3s"`, + `{ duration > 1hx }`: `"1hx"`, + `{ .a = .5xx }`: `".5xx"`, + `{} | topk(5x)`: `"5x"`, + `{} | count() > 1by(x)`: `"1by"`, + `{} | count() > 1with(sample=1)`: `"1with"`, + `{} | avg(duration) > 1x`: `"1x"`, + } { + t.Run(q, func(t *testing.T) { + _, err := Parse(q) + require.ErrorContains(t, err, literal) + }) + } +} + func TestParseConcurrent(t *testing.T) { queries := []string{`{.a = "b"} &>> {.c = "d"}`, `{} | rate() by (name)`, `{duration > 1s} | count() > 2`} var wg sync.WaitGroup @@ -601,3 +633,57 @@ func TestParseConcurrent(t *testing.T) { } wg.Wait() } + +func TestParseRejectsQuotedAttributeNames(t *testing.T) { + for q, want := range map[string]string{ + `{ ."5xx`: `1:3: unexpected EOF, expecting "`, + `{ ."5xx = 1 }`: `1:3: unexpected EOF, expecting "`, + `{ span."5xx`: `1:3: unexpected EOF, expecting "`, + `{ .foo."5xx`: `1:3: unexpected EOF, expecting "`, + `."5xx`: `1:1: unexpected EOF, expecting "`, + `{ ."a\b" = 1 }`: `1:3: invalid escape sequence`, + `{ ."a\n" = 1 }`: `1:3: invalid escape sequence`, + `{ ."a\`: `1:3: invalid escape sequence`, + "{ .\"a\\\nb\" = 1 }": `1:3: invalid escape sequence`, + `{} | rate() by (."a\b")`: `1:17: invalid escape sequence`, + `{ span:"name" = 1 }`: `syntax error: unexpected STRING`, + `{ span: "name" = 1 }`: `syntax error: unexpected STRING`, + "{ span:`name` = 1 }": `syntax error: unexpected STRING`, + `{ resource:"x" = 1 }`: `syntax error: unexpected STRING`, + } { + t.Run(q, func(t *testing.T) { + _, err := Parse(q) + require.EqualError(t, err, want) + }) + } +} + +// Only the scopes Gigapipe parses take a quoted name. +func TestParseRejectsQuotedNamesOutsideDotScopes(t *testing.T) { + for _, q := range []string{ + `{ parent."x" = 1 }`, + `{ parent.span."x" = 1 }`, + `{ event."x" = 1 }`, + `{ link."x" = 1 }`, + `{ instrumentation."x" = 1 }`, + `{ foo."x" = 1 }`, + `{ name"x" = 1 }`, + `{ .foo "x" = 1 }`, + `{ . "x" = 1 }`, + `{ .foo. "x" = 1 }`, + `{ ."x" "y" = 1 }`, + `{ 1."x" = 1 }`, + `{ .5"x" = 1 }`, + } { + t.Run(q, func(t *testing.T) { + _, err := Parse(q) + require.Error(t, err) + }) + } +} + +// A number directly followed by a quoted name is named by its raw spelling. +func TestParseNamesNumberFollowedByQuotedName(t *testing.T) { + _, err := Parse(`{ 1.5."x" = 1 }`) + require.ErrorContains(t, err, `invalid literal "1.5.\"x\""`) +} diff --git a/reader/traceql/traceql_transpiler/clickhouse_transpiler/attr_condition.go b/reader/traceql/traceql_transpiler/clickhouse_transpiler/attr_condition.go index 15b3aafd..df6e0a99 100644 --- a/reader/traceql/traceql_transpiler/clickhouse_transpiler/attr_condition.go +++ b/reader/traceql/traceql_transpiler/clickhouse_transpiler/attr_condition.go @@ -4,7 +4,6 @@ import ( "fmt" "strconv" "strings" - "time" "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared" traceql_ir "github.com/metrico/qryn/v5/reader/traceql/traceql_ir" @@ -306,17 +305,12 @@ func (a *AttrConditionPlanner) getTermDuration(t *attrComparison) (sql.SQLCondit if t.Value.Kind != traceql_ir.ValueDuration { return nil, fmt.Errorf(" is not a time duration value (%s)", t.String()) } - fVal, err := time.ParseDuration(t.Value.Text) - if err != nil { - return nil, err - } - fn, err := getComparisonFn(t.Op) if err != nil { return nil, err } - return fn(sql.NewRawObject("traces_idx.duration"), sql.NewIntVal(fVal.Nanoseconds())), nil + return fn(sql.NewRawObject("traces_idx.duration"), sql.NewIntVal(t.Value.Duration.Nanoseconds())), nil } type bitSet struct { diff --git a/reader/traceql/traceql_transpiler/clickhouse_transpiler/autocomplete_plan_test.go b/reader/traceql/traceql_transpiler/clickhouse_transpiler/autocomplete_plan_test.go index abeb2b7d..02ffe8ce 100644 --- a/reader/traceql/traceql_transpiler/clickhouse_transpiler/autocomplete_plan_test.go +++ b/reader/traceql/traceql_transpiler/clickhouse_transpiler/autocomplete_plan_test.go @@ -227,3 +227,22 @@ func TestAutocompleteReadsDistributedTablesOnClusters(t *testing.T) { } } } + +func TestAutocompleteTreatsQuotedNamesLikeBareOnes(t *testing.T) { + for quoted, bare := range map[string]string{ + `{ ."foo" = "a" }`: `{ .foo = "a" }`, + `{ span."foo".bar = 1 }`: `{ span.foo.bar = 1 }`, + `{ .a = ."b" }`: `{ .a = .b }`, + `{ ."foo" = 1 } >> { .x"bar" = 2 }`: `{ .foo = 1 } >> { .xbar = 2 }`, + } { + bares := autocompletePlans(t, bare) + for kind, plan := range autocompletePlans(t, quoted) { + t.Run(kind+" "+quoted, func(t *testing.T) { + got, want := renderPlan(t, plan, testPlannerContext(7)), renderPlan(t, bares[kind], testPlannerContext(7)) + if got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } + }) + } + } +} diff --git a/reader/traceql/traceql_transpiler/clickhouse_transpiler/field_sql.go b/reader/traceql/traceql_transpiler/clickhouse_transpiler/field_sql.go index 4761133b..5ebaea30 100644 --- a/reader/traceql/traceql_transpiler/clickhouse_transpiler/field_sql.go +++ b/reader/traceql/traceql_transpiler/clickhouse_transpiler/field_sql.go @@ -3,7 +3,6 @@ package clickhouse_transpiler import ( "fmt" "strconv" - "time" traceql_ir "github.com/metrico/qryn/v5/reader/traceql/traceql_ir" ) @@ -343,11 +342,7 @@ func domainOf(e traceql_ir.FieldExpr) domain { func staticNumber(s *traceql_ir.Static) (number, error) { switch s.Kind { case traceql_ir.ValueDuration: - d, err := time.ParseDuration(s.Text) - if err != nil { - return number{}, err - } - return number{val: floatLiteral(float64(d.Nanoseconds())), isInt: "0"}, nil + return number{val: floatLiteral(float64(s.Duration.Nanoseconds())), isInt: "0"}, nil case traceql_ir.ValueNumber: f, err := strconv.ParseFloat(s.Text, 64) if err != nil { diff --git a/reader/traceql/traceql_transpiler/clickhouse_transpiler/scalar_filter.go b/reader/traceql/traceql_transpiler/clickhouse_transpiler/scalar_filter.go index b0bae26e..a008d73a 100644 --- a/reader/traceql/traceql_transpiler/clickhouse_transpiler/scalar_filter.go +++ b/reader/traceql/traceql_transpiler/clickhouse_transpiler/scalar_filter.go @@ -5,7 +5,6 @@ import ( "fmt" "math" "strconv" - "time" "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared" traceql_ir "github.com/metrico/qryn/v5/reader/traceql/traceql_ir" @@ -87,11 +86,7 @@ func checkAggregates(e traceql_ir.ScalarExpr) error { // staticValue is a literal as a float: a duration in nanoseconds. func staticValue(lit *traceql_ir.Static) (float64, error) { if lit.Kind == traceql_ir.ValueDuration { - d, err := time.ParseDuration(lit.Text) - if err != nil { - return 0, err - } - return float64(d.Nanoseconds()), nil + return float64(lit.Duration.Nanoseconds()), nil } return strconv.ParseFloat(lit.Text, 64) } diff --git a/reader/traceql/traceql_transpiler/clickhouse_transpiler/search_plan_test.go b/reader/traceql/traceql_transpiler/clickhouse_transpiler/search_plan_test.go index b54c4191..860482f2 100644 --- a/reader/traceql/traceql_transpiler/clickhouse_transpiler/search_plan_test.go +++ b/reader/traceql/traceql_transpiler/clickhouse_transpiler/search_plan_test.go @@ -245,6 +245,13 @@ func TestSearchRendersNumberLiterals(t *testing.T) { {`{ .foo = 1e3 }`, `1000.000000`}, {`{ duration > .5s }`, `duration) > (500000000)`}, {`{ duration > 5.s }`, `duration) > (5000000000)`}, + {`{ duration > 1d }`, `duration) > (86400000000000)`}, + {`{ duration > 1h30m }`, `duration) > (5400000000000)`}, + {`{ duration > -1d }`, `duration) > (-86400000000000)`}, + {`{ duration * 2 > 1d }`, `toFloat64(8.64e+13)`}, + {`{} | avg(duration) > 1d`, `toFloat64(8.64e+13)`}, + {`{} | avg(duration) > 1h30m`, `toFloat64(5.4e+12)`}, + {`{} | avg(duration) > -1d`, `toFloat64(-8.64e+13)`}, {`{} | count() > -.5`, `-0.5`}, } { t.Run(tc.query, func(t *testing.T) { @@ -254,3 +261,35 @@ func TestSearchRendersNumberLiterals(t *testing.T) { }) } } + +func TestSearchReadsTheKeyOfAQuotedName(t *testing.T) { + for query, want := range map[string]string{ + `{ ."5xx" = 1 }`: `(key) == ('5xx')`, + `{ span."http status" = 1 }`: `(key) == ('http status')`, + `{ ."a'b" = 1 }`: `(key) == ('a\'b')`, + `{ ."" = 1 }`: `(key) == ('')`, + } { + t.Run(query, func(t *testing.T) { + if res := renderPlan(t, planSearch(t, query), testPlannerContext(7)); !strings.Contains(res, want) { + t.Errorf("want %s in %s", want, res) + } + }) + } +} + +// Result attributes are named by the plain name. +func TestSearchNamesResultsByThePlainName(t *testing.T) { + for query, want := range map[string][]string{ + `{} | by(."http status")`: {`'by(.http status)'`, `'http status'`}, + `{} | avg(span."a b") > 1`: {`'avg(span.a b)'`, `'a b'`}, + } { + t.Run(query, func(t *testing.T) { + res := renderPlan(t, planSearch(t, query), testPlannerContext(7)) + for _, w := range want { + if !strings.Contains(res, w) { + t.Errorf("want %s in %s", w, res) + } + } + }) + } +} diff --git a/reader/traceql/traceql_transpiler/quoted_names_behaviour_test.go b/reader/traceql/traceql_transpiler/quoted_names_behaviour_test.go new file mode 100644 index 00000000..f3ec9e25 --- /dev/null +++ b/reader/traceql/traceql_transpiler/quoted_names_behaviour_test.go @@ -0,0 +1,122 @@ +package traceql_transpiler + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + "github.com/metrico/cloki-config/config" + "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared" + "github.com/metrico/qryn/v5/reader/model" + "github.com/metrico/qryn/v5/reader/tempo" + "github.com/metrico/qryn/v5/reader/traceql/traceql_ir" + "github.com/metrico/qryn/v5/reader/traceql/traceql_transpiler/clickhouse_transpiler" + dbversion "github.com/metrico/qryn/v5/reader/utils/dbVersion" + sql "github.com/metrico/qryn/v5/reader/utils/sql_select" + "github.com/metrico/qryn/v5/reader/utils/tables" + "github.com/metrico/qryn/v5/shared/distconfig" +) + +// byValues runs the instant metrics query and returns the values of its first +// by label. +func (s *searchStore) byValues(t *testing.T, query string) []string { + t.Helper() + q, err := traceql_ir.Parse(query) + if err != nil { + t.Fatal(err) + } + ctx := &shared.PlannerContext{ + Ctx: context.Background(), CHDb: s.db, + From: spanStart.Add(-time.Minute), To: spanStart.Add(time.Minute), + Limit: searchLimit, SpansPerSpanSet: 100, + VersionInfo: dbversion.VersionInfo{dbversion.CapStructuralQueries: 0}, + } + distconfig.Init() + tables.PopulateTableNames(ctx, &model.DataDatabasesMap{Config: &config.ClokiBaseDataBase{Name: s.name}}) + planner, err := clickhouse_transpiler.PlanMetrics(q, func(spans *sql.With) (sql.ISelect, error) { + res, _, err := tempo.BuildMetricsInstantQuery(&tempo.MetricsRequest{ + Spans: spans, Fn: q.Metrics.Fn, By: q.Metrics.By, + FromNS: ctx.From.UnixNano(), ToNS: ctx.To.UnixNano(), StepNS: int64(time.Minute), + AttrsTable: ctx.TracesAttrsTable, + }) + return res, err + }) + if err != nil { + t.Fatal(err) + } + req, err := planner.Process(ctx) + if err != nil { + t.Fatal(err) + } + text, err := req.String(sql.DefaultCtx()) + if err != nil { + t.Fatal(err) + } + rows, err := s.conn.Query(context.Background(), + "SELECT DISTINCT toString(by_custom_0) FROM ("+text+")") + if err != nil { + t.Fatalf("%v\n%s", err, text) + } + defer rows.Close() + var res []string + for rows.Next() { + var v string + if err := rows.Scan(&v); err != nil { + t.Fatal(err) + } + res = append(res, v) + } + slices.Sort(res) + return res +} + +// traceIDs runs a search and returns the matched trace ids. +func (s *searchStore) traceIDs(t *testing.T, query string) []string { + t.Helper() + var got []string + for _, line := range s.result(t, query, searchRun{limit: searchLimit}) { + if id, ok := strings.CutPrefix(line, "trace "); ok { + got = append(got, strings.Fields(id)[0]) + } else if strings.HasPrefix(line, "error:") { + t.Fatalf("%s: %s", query, line) + } + } + return got +} + +func TestQuotedNamesReadTheirAttributes(t *testing.T) { + s := openSearchStore(t, false, false) + s.seed(t, []span{ + {trace: 1, id: 1, attrs: []string{"5xx", "foo"}}, + {trace: 2, id: 2, attrs: []string{"http status"}}, + {trace: 3, id: 3, attrs: []string{`a\\\' OR 1=1 --`}}, + {trace: 4, id: 4, attrs: []string{"other"}}, + }) + for query, want := range map[string][]string{ + `{ ."5xx" = "1" }`: {"1"}, + `{ span."http status" = "1" }`: {"2"}, + `{ ."a\\' OR 1=1 --" = "1" }`: {"3"}, + `{ ."nothing" = "1" }`: nil, + } { + t.Run(query, func(t *testing.T) { + if got := s.traceIDs(t, query); !slices.Equal(got, want) { + t.Errorf("traces %q, want %q", got, want) + } + }) + } + for query, want := range map[string][]string{ + `{} | rate() by (.foo)`: {"", "1"}, + `{} | rate() by (."5xx")`: {"", "1"}, + `{} | rate() by (span."http status")`: {"", "1"}, + `{} | rate() by (."a\\' OR 1=1 --")`: {"", "1"}, + `{} | rate() by (.nothing)`: {""}, + } { + t.Run(query, func(t *testing.T) { + if got := s.byValues(t, query); !slices.Equal(got, want) { + t.Errorf("by values %q, want %q", got, want) + } + }) + } +}