You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2026/09/20 23:13:32 UTC
(skywalking-banyandb) branch main updated: feat(bydbql): expose COUNT_DISTINCT and time-bucket grouping in BydbQL (#1366)
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 89403f921 feat(bydbql): expose COUNT_DISTINCT and time-bucket grouping in BydbQL (#1366)
89403f921 is described below
commit 89403f9211cbd9c56c37f37a1526610591cb1c55
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Mon Sep 21 07:13:25 2026 +0800
feat(bydbql): expose COUNT_DISTINCT and time-bucket grouping in BydbQL (#1366)
---
bydbctl/internal/tui/bridge/plan_schema.go | 60 ++++--
bydbctl/internal/tui/bridge/plan_schema_test.go | 124 +++++++++++
.../tui/bydbql/semantic_projection_test.go | 27 +++
bydbctl/internal/tui/planner/golden_test.go | 20 +-
bydbctl/internal/tui/planner/plan_types.go | 43 ++--
bydbctl/internal/tui/planner/planner.go | 97 ++++++++-
bydbctl/internal/tui/planner/planner_test.go | 240 +++++++++++++++++++++
docs/api-reference.md | 32 +--
docs/interacting/bydbql.md | 43 +++-
pkg/bydbql/bydbql_test.go | 86 ++++++++
pkg/bydbql/grammar.go | 24 ++-
pkg/bydbql/parser.go | 47 +++-
pkg/bydbql/transformer.go | 107 ++++++---
pkg/bydbql/transformer_measure_test.go | 176 +++++++++++++++
pkg/test/helpers/constant.go | 5 +-
.../testdata/measures/cardinality_metric.json | 36 ++++
test/cases/init.go | 26 +++
test/cases/measure/cmd/generate/ql_renderer.go | 35 ++-
.../gen_feat_count_distinct_group_order_desc_10.ql | 2 +-
...p_order_desc_10.ql => group_count_by_entity.ql} | 5 +-
.../measure/data/input/group_count_by_entity.yaml | 4 +
..._desc_10.ql => group_count_composite_entity.ql} | 5 +-
.../data/input/group_count_composite_entity.yaml | 4 +
...esc_10.ql => group_count_distinct_by_entity.ql} | 5 +-
.../data/input/group_count_distinct_by_entity.yaml | 4 +
...ql => group_count_distinct_composite_entity.ql} | 5 +-
.../group_count_distinct_composite_entity.yaml | 4 +
...sc_10.ql => group_count_distinct_index_mode.ql} | 5 +-
.../input/group_count_distinct_index_mode.yaml | 4 +
...c_10.ql => group_count_distinct_off_cadence.ql} | 5 +-
...c_10.ql => group_count_distinct_time_bucket.ql} | 5 +-
....yaml => group_count_distinct_time_bucket.yaml} | 12 +-
....ql => group_count_distinct_time_bucket_30s.ql} | 5 +-
...l => group_count_distinct_time_bucket_30s.yaml} | 12 +-
...> group_count_distinct_time_bucket_with_tag.ql} | 5 +-
...group_count_distinct_time_bucket_with_tag.yaml} | 10 +-
...c_10.ql => group_count_distinct_top_by_user.ql} | 7 +-
....yaml => group_count_distinct_top_by_user.yaml} | 16 +-
..._order_desc_10.ql => group_count_index_mode.ql} | 5 +-
.../measure/data/input/group_count_index_mode.yaml | 4 +
...order_desc_10.ql => group_count_off_cadence.ql} | 5 +-
...group_order_desc_10.ql => group_time_bucket.ql} | 5 +-
...er_desc_10.ql => group_time_bucket_with_tag.ql} | 5 +-
.../testdata/cardinality_metric_u1_b0_data.json | 35 +++
.../testdata/cardinality_metric_u1_b2_data.json | 35 +++
.../testdata/cardinality_metric_u2_b1_data.json | 24 +++
.../group_count_distinct_time_bucket.yaml} | 38 +++-
.../want/group_count_distinct_time_bucket_30s.yaml | 78 +++++++
...group_count_distinct_time_bucket_with_tag.yaml} | 50 ++++-
.../group_count_distinct_top_by_user.yaml} | 14 +-
test/cases/measure/measure.go | 72 ++++---
51 files changed, 1565 insertions(+), 157 deletions(-)
diff --git a/bydbctl/internal/tui/bridge/plan_schema.go b/bydbctl/internal/tui/bridge/plan_schema.go
index 7c386960d..3002d81b7 100644
--- a/bydbctl/internal/tui/bridge/plan_schema.go
+++ b/bydbctl/internal/tui/bridge/plan_schema.go
@@ -75,6 +75,7 @@ func selectPlanSchema() map[string]any {
"order_by": selectOrderSchema(),
"time_range": timeRangeSchema(),
"group_by": stringArraySchema(1),
+ "time_bucket": timeBucketSchema(),
"limit": boundedIntegerSchema(1, 1000),
"id": map[string]any{"type": "string", "minLength": 1},
},
@@ -138,15 +139,35 @@ func projectionSchema() map[string]any {
}
}
+// timeBucketSchema exposes GROUP BY TIME_BUCKET(width). The width is optional
+// -- an omitted one defers to the measure's own interval -- and, when given,
+// must be a duration the server accepts (ns, us, ms, s, m, h, or the custom d
+// suffix). Only SELECT plans over a MEASURE carry it, and only alongside
+// exactly one aggregate; Compile enforces both.
+func timeBucketSchema() map[string]any {
+ return map[string]any{
+ "type": "object",
+ "additionalProperties": false,
+ "properties": map[string]any{
+ "width": map[string]any{"type": "string", "minLength": 1},
+ },
+ }
+}
+
+// aggregateSchema describes one aggregation. COUNT_DISTINCT is offered only
+// where a column is required: it always needs an explicit target, and
+// compileTopN rejects it outright because the TOPN grammar has no DISTINCT
+// production to render into.
func aggregateSchema(requireColumn bool) map[string]any {
+ functions := []string{"MEAN", "COUNT", "MAX", "MIN", "SUM"}
required := []string{"function"}
- properties := map[string]any{
- "function": map[string]any{"type": "string", "enum": []string{"MEAN", "COUNT", "MAX", "MIN", "SUM"}},
- }
+ properties := map[string]any{}
if requireColumn {
+ functions = append(functions, "COUNT_DISTINCT")
required = append(required, "column")
properties["column"] = map[string]any{"type": "string", "minLength": 1}
}
+ properties["function"] = map[string]any{"type": "string", "enum": functions}
return map[string]any{
"type": "object",
"required": required,
@@ -257,6 +278,8 @@ func queryPlanSchemaHint() string {
return "Submit exactly one strict SelectPlan or TopNPlan. " +
"SelectPlan uses MEASURE|STREAM|TRACE|PROPERTY and order_by.index_rule. " +
"TopNPlan uses a real TOPN aggregation resource, top_n, aggregate.function, and direction-only order_by. " +
+ "COUNT_DISTINCT targets a count_distinct_columns entry and is unavailable to TopNPlan. " +
+ "time_bucket groups a MEASURE SelectPlan by time and requires exactly one aggregate. " +
"Unknown fields and structural coercions are rejected."
}
@@ -265,6 +288,10 @@ func planConstraintsForSnapshot(snapshot session.SchemaSnapshot) map[string]any
filterColumns := make([]string, 0, len(snapshot.Columns)+1)
numericFields := make([]string, 0, len(snapshot.Fields))
groupByColumns := make([]string, 0, len(snapshot.Columns))
+ // COUNT_DISTINCT accepts a wider target set than every other function --
+ // numeric fields plus any tag that is not an array or a timestamp -- so it
+ // needs its own advertised list. numeric_fields alone would understate it.
+ countDistinctColumns := make([]string, 0, len(snapshot.Columns))
for _, column := range snapshot.Columns {
projectionColumns = append(projectionColumns, column.Name)
if column.Kind == session.SchemaColumnTag || column.Kind == session.SchemaColumnEntityTag {
@@ -272,11 +299,17 @@ func planConstraintsForSnapshot(snapshot session.SchemaSnapshot) map[string]any
filterColumns = append(filterColumns, column.Name)
}
groupByColumns = append(groupByColumns, column.Name)
+ switch column.Type {
+ case session.SchemaValueTypeStringArray, session.SchemaValueTypeIntArray, session.SchemaValueTypeTimestamp:
+ default:
+ countDistinctColumns = append(countDistinctColumns, column.Name)
+ }
}
if column.Kind == session.SchemaColumnField {
groupByColumns = append(groupByColumns, column.Name)
if column.Type == session.SchemaValueTypeInt || column.Type == session.SchemaValueTypeFloat {
numericFields = append(numericFields, column.Name)
+ countDistinctColumns = append(countDistinctColumns, column.Name)
}
}
}
@@ -296,16 +329,17 @@ func planConstraintsForSnapshot(snapshot session.SchemaSnapshot) map[string]any
"name": snapshot.Name,
"groups": append([]string(nil), snapshot.Groups...),
},
- "projection_columns": projectionColumns,
- "filter_columns": filterColumns,
- "numeric_fields": numericFields,
- "group_by_columns": groupByColumns,
- "sortable_indexes": sortableIndexes,
- "source_measure": snapshot.SourceMeasure,
- "source_group": snapshot.SourceMeasureGroup,
- "topn_field_sort": snapshot.FieldValueSort,
- "schema_fingerprint": snapshot.Fingerprint,
- "limit_maximum": 1000,
+ "projection_columns": projectionColumns,
+ "filter_columns": filterColumns,
+ "numeric_fields": numericFields,
+ "count_distinct_columns": countDistinctColumns,
+ "group_by_columns": groupByColumns,
+ "sortable_indexes": sortableIndexes,
+ "source_measure": snapshot.SourceMeasure,
+ "source_group": snapshot.SourceMeasureGroup,
+ "topn_field_sort": snapshot.FieldValueSort,
+ "schema_fingerprint": snapshot.Fingerprint,
+ "limit_maximum": 1000,
}
if snapshot.Type == session.ResourceTypeTrace {
constraints["trace_scan_requirement"] = traceScanRequirement(snapshot)
diff --git a/bydbctl/internal/tui/bridge/plan_schema_test.go b/bydbctl/internal/tui/bridge/plan_schema_test.go
new file mode 100644
index 000000000..b8cbe6f89
--- /dev/null
+++ b/bydbctl/internal/tui/bridge/plan_schema_test.go
@@ -0,0 +1,124 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package bridge
+
+import (
+ "testing"
+
+ "github.com/apache/skywalking-banyandb/bydbctl/internal/tui/session"
+)
+
+func selectPlanProperties(t *testing.T) map[string]any {
+ t.Helper()
+ properties, ok := selectPlanSchema()["properties"].(map[string]any)
+ if !ok {
+ t.Fatal("selectPlanSchema has no properties map")
+ }
+ return properties
+}
+
+func aggregateFunctionEnum(t *testing.T, schema map[string]any) []string {
+ t.Helper()
+ properties, ok := schema["properties"].(map[string]any)
+ if !ok {
+ t.Fatal("aggregate schema has no properties map")
+ }
+ function, ok := properties["function"].(map[string]any)
+ if !ok {
+ t.Fatal("aggregate schema has no function property")
+ }
+ values, ok := function["enum"].([]string)
+ if !ok {
+ t.Fatalf("aggregate function enum is %T, want []string", function["enum"])
+ }
+ return values
+}
+
+func containsString(values []string, target string) bool {
+ for _, value := range values {
+ if value == target {
+ return true
+ }
+ }
+ return false
+}
+
+// TestSelectPlanSchemaExposesTimeBucket pins that time_bucket is advertised on
+// the SELECT plan. selectPlanSchema sets additionalProperties:false, so an
+// omitted property is not merely undiscoverable -- a plan carrying it is
+// invalid against the tool contract, which would leave QueryPlan.TimeBucket
+// unreachable from the structured path no matter what Compile supports.
+func TestSelectPlanSchemaExposesTimeBucket(t *testing.T) {
+ properties := selectPlanProperties(t)
+ timeBucket, ok := properties["time_bucket"].(map[string]any)
+ if !ok {
+ t.Fatal("selectPlanSchema does not advertise time_bucket")
+ }
+ bucketProperties, ok := timeBucket["properties"].(map[string]any)
+ if !ok {
+ t.Fatal("time_bucket schema has no properties map")
+ }
+ if _, hasWidth := bucketProperties["width"]; !hasWidth {
+ t.Fatal("time_bucket schema does not advertise width")
+ }
+}
+
+// TestAggregateSchemaOffersCountDistinctOnlyWithAColumn pins both halves of the
+// rule: COUNT_DISTINCT always needs an explicit target, and compileTopN rejects
+// it outright because the TOPN grammar has no DISTINCT production.
+func TestAggregateSchemaOffersCountDistinctOnlyWithAColumn(t *testing.T) {
+ withColumn := aggregateFunctionEnum(t, aggregateSchema(true))
+ if !containsString(withColumn, "COUNT_DISTINCT") {
+ t.Fatalf("column-bearing aggregate enum omits COUNT_DISTINCT: %v", withColumn)
+ }
+ withoutColumn := aggregateFunctionEnum(t, aggregateSchema(false))
+ if containsString(withoutColumn, "COUNT_DISTINCT") {
+ t.Fatalf("TOPN aggregate enum must not offer COUNT_DISTINCT: %v", withoutColumn)
+ }
+}
+
+// TestPlanConstraintsListCountDistinctColumns pins that the advertised target
+// list follows compileAggregate's own gate: numeric fields plus every tag that
+// is not an array or a timestamp. numeric_fields alone would understate it.
+func TestPlanConstraintsListCountDistinctColumns(t *testing.T) {
+ snapshot := session.SchemaSnapshot{
+ Type: session.ResourceTypeMeasure,
+ Name: "service_latency",
+ Groups: []string{"production"},
+ Columns: []session.SchemaColumn{
+ {Name: "service", Kind: session.SchemaColumnTag, Type: session.SchemaValueTypeString},
+ {Name: "tags", Kind: session.SchemaColumnTag, Type: session.SchemaValueTypeStringArray},
+ {Name: "seen_at", Kind: session.SchemaColumnTag, Type: session.SchemaValueTypeTimestamp},
+ {Name: "latency", Kind: session.SchemaColumnField, Type: session.SchemaValueTypeFloat},
+ {Name: "payload", Kind: session.SchemaColumnField, Type: session.SchemaValueTypeBinary},
+ },
+ }
+ columns, ok := planConstraintsForSnapshot(snapshot)["count_distinct_columns"].([]string)
+ if !ok {
+ t.Fatal("constraints omit count_distinct_columns")
+ }
+ for _, allowed := range []string{"service", "latency"} {
+ if !containsString(columns, allowed) {
+ t.Fatalf("count_distinct_columns omits %q: %v", allowed, columns)
+ }
+ }
+ for _, rejected := range []string{"tags", "seen_at", "payload"} {
+ if containsString(columns, rejected) {
+ t.Fatalf("count_distinct_columns must not offer %q: %v", rejected, columns)
+ }
+ }
+}
diff --git a/bydbctl/internal/tui/bydbql/semantic_projection_test.go b/bydbctl/internal/tui/bydbql/semantic_projection_test.go
index 10fc5720b..ef1977689 100644
--- a/bydbctl/internal/tui/bydbql/semantic_projection_test.go
+++ b/bydbctl/internal/tui/bydbql/semantic_projection_test.go
@@ -68,6 +68,33 @@ func TestSemanticValidatorAcceptsKnownProjection(t *testing.T) {
}
}
+// TestSemanticValidatorHandlesCountDistinctAndTimeBucket pins that adding
+// GrammarAggregateFunction.Distinct and the TIME_BUCKET(...) pseudo-column
+// (apache/skywalking#14091) didn't introduce a nil-pointer panic here.
+// selectIdentifiers only reads column.Aggregate.Column (unaffected by the
+// new Distinct field), and groupByIdentifiers already guards
+// column.Identifier == nil before dereferencing it — a TIME_BUCKET column
+// (Identifier is nil, TimeBucket is set) is silently skipped, not a crash.
+func TestSemanticValidatorHandlesCountDistinctAndTimeBucket(t *testing.T) {
+ validator := NewSemanticValidator()
+ schema := &session.SchemaSnapshot{
+ Type: session.ResourceTypeMeasure,
+ Tags: []string{"endpoint"},
+ Fields: []string{"latency"},
+ }
+ report, validateErr := validator.Validate(
+ context.Background(),
+ "SELECT endpoint, COUNT(DISTINCT endpoint) FROM MEASURE service_latency IN production TIME > '-30m' GROUP BY TIME_BUCKET('5m'), endpoint LIMIT 10",
+ schema,
+ )
+ if validateErr != nil {
+ t.Fatalf("Validate returned error: %v", validateErr)
+ }
+ if !report.Valid {
+ t.Fatalf("expected valid report, got %q", report.Message)
+ }
+}
+
func TestSemanticValidatorAcceptsUnambiguousTagFamilySuffix(t *testing.T) {
validator := NewSemanticValidator()
report, validateErr := validator.Validate(context.Background(),
diff --git a/bydbctl/internal/tui/planner/golden_test.go b/bydbctl/internal/tui/planner/golden_test.go
index 899dfba06..7c148d18a 100644
--- a/bydbctl/internal/tui/planner/golden_test.go
+++ b/bydbctl/internal/tui/planner/golden_test.go
@@ -159,6 +159,22 @@ func TestE2EDerivedGoldenPlans(t *testing.T) {
schema: measure,
want: "SELECT endpoint, MAX(latency) FROM MEASURE service_latency IN production TIME > '-30m' GROUP BY endpoint::TAG LIMIT 10",
},
+ {
+ name: "measure/group_count_distinct",
+ plan: QueryPlan{
+ Resource: measureResource, Projection: aggregateProjection(AggregateCountDistinct, "service"), GroupBy: []string{"endpoint"}, TimeRange: defaultRange, Limit: 10,
+ },
+ schema: measure,
+ want: "SELECT endpoint, COUNT(DISTINCT service) FROM MEASURE service_latency IN production TIME > '-30m' GROUP BY endpoint::TAG LIMIT 10",
+ },
+ {
+ name: "measure/group_time_bucket",
+ plan: QueryPlan{
+ Resource: measureResource, Projection: aggregateProjection(AggregateSum, "cpm"), TimeBucket: &GroupByTimeBucket{Width: "5m"}, TimeRange: defaultRange, Limit: 10,
+ },
+ schema: measure,
+ want: "SELECT endpoint, SUM(cpm) FROM MEASURE service_latency IN production TIME > '-30m' GROUP BY TIME_BUCKET('5m') LIMIT 10",
+ },
{
name: "measure/order_tag_asc",
plan: QueryPlan{
@@ -334,8 +350,8 @@ func TestE2EDerivedGoldenPlans(t *testing.T) {
want: "SHOW TOP 3 FROM MEASURE service_latency_topn IN production TIME > '-30m' AGGREGATE BY COUNT ORDER BY DESC",
},
}
- if len(goldens) != 41 {
- t.Fatalf("expected 41 e2e-derived golden cases, got %d", len(goldens))
+ if len(goldens) != 43 {
+ t.Fatalf("expected 43 e2e-derived golden cases, got %d", len(goldens))
}
for _, golden := range goldens {
t.Run(golden.name, func(t *testing.T) {
diff --git a/bydbctl/internal/tui/planner/plan_types.go b/bydbctl/internal/tui/planner/plan_types.go
index 7800c7e4a..f05148e72 100644
--- a/bydbctl/internal/tui/planner/plan_types.go
+++ b/bydbctl/internal/tui/planner/plan_types.go
@@ -31,11 +31,12 @@ type AggregateFunction string
// Aggregate functions.
const (
- AggregateMean AggregateFunction = "MEAN"
- AggregateCount AggregateFunction = "COUNT"
- AggregateMax AggregateFunction = "MAX"
- AggregateMin AggregateFunction = "MIN"
- AggregateSum AggregateFunction = "SUM"
+ AggregateMean AggregateFunction = "MEAN"
+ AggregateCount AggregateFunction = "COUNT"
+ AggregateMax AggregateFunction = "MAX"
+ AggregateMin AggregateFunction = "MIN"
+ AggregateSum AggregateFunction = "SUM"
+ AggregateCountDistinct AggregateFunction = "COUNT_DISTINCT"
)
// Operator is a supported deterministic filter operator.
@@ -112,19 +113,27 @@ type TimeRange struct {
End string `json:"end,omitempty"`
}
+// GroupByTimeBucket buckets a MEASURE query's GroupBy by time, in addition to
+// (or instead of) any tag/field GroupBy columns. Width is a BYDBQL duration
+// string (e.g. "5m"); an empty Width defers to the measure's own interval.
+type GroupByTimeBucket struct {
+ Width string `json:"width,omitempty"`
+}
+
// QueryPlan describes one query without embedding any BYDBQL text.
type QueryPlan struct {
- Filter *Predicate `json:"filter,omitempty"`
- Aggregate *Aggregate `json:"aggregate,omitempty"`
- OrderBy *Order `json:"order_by,omitempty"`
- TimeRange TimeRange `json:"time_range,omitempty"`
- ProjectionMode ProjectionMode `json:"projection_mode,omitempty"`
- ID string `json:"id,omitempty"`
- Resource Resource `json:"resource"`
- Projection []Projection `json:"projection,omitempty"`
- GroupBy []string `json:"group_by,omitempty"`
- Limit int `json:"limit,omitempty"`
- TopN int `json:"top_n,omitempty"`
+ Filter *Predicate `json:"filter,omitempty"`
+ Aggregate *Aggregate `json:"aggregate,omitempty"`
+ OrderBy *Order `json:"order_by,omitempty"`
+ TimeBucket *GroupByTimeBucket `json:"time_bucket,omitempty"`
+ TimeRange TimeRange `json:"time_range,omitempty"`
+ ProjectionMode ProjectionMode `json:"projection_mode,omitempty"`
+ ID string `json:"id,omitempty"`
+ Resource Resource `json:"resource"`
+ Projection []Projection `json:"projection,omitempty"`
+ GroupBy []string `json:"group_by,omitempty"`
+ Limit int `json:"limit,omitempty"`
+ TopN int `json:"top_n,omitempty"`
}
// WorkflowPlan describes a sequence of independently approved query plans.
@@ -170,7 +179,7 @@ func diagnosticError(code, path, message string, allowed ...string) error {
func isAggregateFunction(function AggregateFunction) bool {
switch function {
- case AggregateMean, AggregateCount, AggregateMax, AggregateMin, AggregateSum:
+ case AggregateMean, AggregateCount, AggregateMax, AggregateMin, AggregateSum, AggregateCountDistinct:
return true
default:
return false
diff --git a/bydbctl/internal/tui/planner/planner.go b/bydbctl/internal/tui/planner/planner.go
index 6857b7356..7744886a5 100644
--- a/bydbctl/internal/tui/planner/planner.go
+++ b/bydbctl/internal/tui/planner/planner.go
@@ -27,6 +27,7 @@ import (
"time"
"github.com/apache/skywalking-banyandb/bydbctl/internal/tui/session"
+ "github.com/apache/skywalking-banyandb/pkg/timestamp"
)
const (
@@ -111,18 +112,40 @@ func validateSelectShape(plan QueryPlan) error {
if plan.Resource.Type != session.ResourceTypeMeasure && aggregateCount != 0 {
return fmt.Errorf("aggregations are supported only for MEASURE queries")
}
- if plan.Resource.Type != session.ResourceTypeMeasure && len(plan.GroupBy) != 0 {
+ if plan.Resource.Type != session.ResourceTypeMeasure && (len(plan.GroupBy) != 0 || plan.TimeBucket != nil) {
return fmt.Errorf("GROUP BY is supported only for MEASURE queries")
}
- if len(plan.GroupBy) != 0 && aggregateCount != 1 {
+ if (len(plan.GroupBy) != 0 || plan.TimeBucket != nil) && aggregateCount != 1 {
return fmt.Errorf("GROUP BY requires exactly one aggregate")
}
+ if orderingErr := validateBucketedOrdering(plan); orderingErr != nil {
+ return orderingErr
+ }
if plan.ProjectionMode == ProjectionModeNone && aggregateCount != 0 {
return fmt.Errorf("projection_mode NONE cannot be combined with an aggregate")
}
return nil
}
+// validateBucketedOrdering mirrors the server's own validateBucketableOrdering:
+// a bucketed query may name no index rule, because a non-time rule resolves to
+// a different scan order entirely, and may not order descending, because
+// BatchTimeBucket's streaming path assumes ascending time specifically rather
+// than merely time-ordered input. Rejecting here keeps the planner from
+// compiling a query that could only fail once it reached the server.
+func validateBucketedOrdering(plan QueryPlan) error {
+ if plan.TimeBucket == nil || plan.OrderBy == nil {
+ return nil
+ }
+ if strings.TrimSpace(plan.OrderBy.IndexRule) != "" {
+ return fmt.Errorf("time_bucket requires time ordering; order_by.index_rule is not supported on a bucketed query")
+ }
+ if plan.OrderBy.Direction == OrderDescending {
+ return fmt.Errorf("time_bucket requires ascending time order; order_by.direction DESC is not supported on a bucketed query")
+ }
+ return nil
+}
+
// validateTraceScanBounds rejects a TRACE plan that BanyanDB cannot plan a scan for.
//
// A TRACE scan starts from an ORDER BY index rule or from an equality filter on the trace-ID tag.
@@ -181,7 +204,7 @@ func compileSelect(plan QueryPlan, schema session.SchemaSnapshot) (string, error
if projectionErr != nil {
return "", projectionErr
}
- groups, groupsErr := compileGroups(plan.GroupBy, plan.Projection, plan.ProjectionMode, schema)
+ groups, groupsErr := compileGroups(plan.GroupBy, plan.TimeBucket, plan.Projection, plan.ProjectionMode, schema)
if groupsErr != nil {
return "", groupsErr
}
@@ -219,8 +242,10 @@ func compileSelect(plan QueryPlan, schema session.SchemaSnapshot) (string, error
}
func compileTopN(plan QueryPlan, schema session.SchemaSnapshot) (string, error) {
- if len(plan.Projection) != 0 || plan.ProjectionMode != "" || len(plan.GroupBy) != 0 || plan.Limit != 0 {
- return "", fmt.Errorf("TOPN plans do not support projection, projection_mode, group_by, or limit")
+ // TimeBucket belongs here too: compileTopN never renders it, so a TOPN
+ // plan carrying one would otherwise drop it silently.
+ if len(plan.Projection) != 0 || plan.ProjectionMode != "" || len(plan.GroupBy) != 0 || plan.Limit != 0 || plan.TimeBucket != nil {
+ return "", fmt.Errorf("TOPN plans do not support projection, projection_mode, group_by, time_bucket, or limit")
}
if plan.Aggregate != nil && strings.TrimSpace(plan.Aggregate.Column) != "" {
return "", fmt.Errorf("TOPN aggregation cannot select a column")
@@ -242,6 +267,12 @@ func compileTopN(plan QueryPlan, schema session.SchemaSnapshot) (string, error)
if !isAggregateFunction(function) {
return "", fmt.Errorf("unsupported TOPN aggregation %q", function)
}
+ // GrammarTopNAggregateFunction (the legacy SHOW TOP N ... AGGREGATE BY
+ // grammar) has no DISTINCT production at all — isAggregateFunction alone
+ // would let this compile to text the parser can't accept.
+ if function == AggregateCountDistinct {
+ return "", fmt.Errorf("TOPN aggregation does not support COUNT_DISTINCT")
+ }
direction := OrderDescending
if plan.OrderBy != nil {
direction = plan.OrderBy.Direction
@@ -329,6 +360,29 @@ func compileAggregate(aggregate Aggregate, resource Resource, schema session.Sch
if columnErr != nil {
return "", columnErr
}
+ // COUNT_DISTINCT is the one function that accepts either column kind
+ // (design §6 matrix: numeric fields plus every tag type that is not an
+ // array or a timestamp), so it must branch before the field-only checks
+ // below rather than extend them.
+ if aggregate.Function == AggregateCountDistinct {
+ if column.Kind == session.SchemaColumnField {
+ if column.Type != session.SchemaValueTypeInt && column.Type != session.SchemaValueTypeFloat {
+ return "", diagnosticError("AGGREGATE_FIELD_NOT_NUMERIC", "/aggregate/column", fmt.Sprintf("aggregation field %q must be numeric", aggregate.Column))
+ }
+ return fmt.Sprintf("COUNT(DISTINCT %s)", column.Name), nil
+ }
+ switch column.Type {
+ case session.SchemaValueTypeStringArray, session.SchemaValueTypeIntArray, session.SchemaValueTypeTimestamp:
+ return "", diagnosticError("AGGREGATE_TAG_TYPE_UNSUPPORTED", "/aggregate/column",
+ fmt.Sprintf("COUNT_DISTINCT column %q has an unsupported tag type %q", aggregate.Column, column.Type))
+ default:
+ // Every other tag type is supported (design §6 matrix: COUNT_DISTINCT
+ // accepts any tag type that isn't an array or a timestamp).
+ }
+ // COUNT(DISTINCT col), not COUNT_DISTINCT(col) — the generic
+ // "%s(%s)" formatter below would emit invalid BYDBQL syntax.
+ return fmt.Sprintf("COUNT(DISTINCT %s)", column.Name), nil
+ }
if column.Kind != session.SchemaColumnField {
return "", diagnosticError("AGGREGATE_COLUMN_NOT_FIELD", "/aggregate/column", fmt.Sprintf("aggregation column %q must be a field", aggregate.Column))
}
@@ -338,11 +392,38 @@ func compileAggregate(aggregate Aggregate, resource Resource, schema session.Sch
return fmt.Sprintf("%s(%s)", aggregate.Function, column.Name), nil
}
-func compileGroups(groups []string, projections []Projection, projectionMode ProjectionMode, schema session.SchemaSnapshot) (string, error) {
- if len(groups) == 0 {
+func compileGroups(
+ groups []string, timeBucket *GroupByTimeBucket, projections []Projection, projectionMode ProjectionMode, schema session.SchemaSnapshot,
+) (string, error) {
+ if len(groups) == 0 && timeBucket == nil {
return "", nil
}
- compiled := make([]string, 0, len(groups))
+ compiled := make([]string, 0, len(groups)+1)
+ // TIME_BUCKET is the leading group key when present — a synthetic
+ // pseudo-column, not a real schema column, so it bypasses typedColumn
+ // resolution and the "must also be projected" check below.
+ if timeBucket != nil {
+ if timeBucket.Width != "" {
+ // Apply the server's own rule (plan.resolveTimeBucket) before the
+ // width reaches the rendered literal: it must parse as a duration
+ // and be positive. Every other value compiled here is resolved
+ // against the schema, so this is the one free-form string that
+ // would otherwise be interpolated unchecked -- a non-duration or
+ // quote-bearing width would render BYDBQL the parser rejects.
+ width, widthErr := timestamp.ParseDuration(timeBucket.Width)
+ if widthErr != nil {
+ return "", diagnosticError("GROUP_BY_TIME_BUCKET_WIDTH_INVALID", "/time_bucket/width",
+ fmt.Sprintf("time_bucket width %q is not a valid duration", timeBucket.Width))
+ }
+ if width <= 0 {
+ return "", diagnosticError("GROUP_BY_TIME_BUCKET_WIDTH_INVALID", "/time_bucket/width",
+ fmt.Sprintf("time_bucket width %q must be positive", timeBucket.Width))
+ }
+ compiled = append(compiled, fmt.Sprintf("TIME_BUCKET('%s')", timeBucket.Width))
+ } else {
+ compiled = append(compiled, "TIME_BUCKET()")
+ }
+ }
fieldCount := 0
for _, group := range groups {
column, columnErr := typedColumn(group, schema)
diff --git a/bydbctl/internal/tui/planner/planner_test.go b/bydbctl/internal/tui/planner/planner_test.go
index dfc6e5f16..0055aeb3c 100644
--- a/bydbctl/internal/tui/planner/planner_test.go
+++ b/bydbctl/internal/tui/planner/planner_test.go
@@ -188,6 +188,175 @@ func TestCompileRejectsFieldFiltersAndTagAggregations(t *testing.T) {
}
}
+func countDistinctSchema() session.SchemaSnapshot {
+ return session.SchemaSnapshot{
+ Type: session.ResourceTypeMeasure,
+ Name: "service_latency",
+ Groups: []string{"production"},
+ Columns: []session.SchemaColumn{
+ {Name: "service", Kind: session.SchemaColumnTag, Type: session.SchemaValueTypeString},
+ {Name: "tags", Kind: session.SchemaColumnTag, Type: session.SchemaValueTypeStringArray},
+ {Name: "latency", Kind: session.SchemaColumnField, Type: session.SchemaValueTypeFloat},
+ {Name: "payload", Kind: session.SchemaColumnField, Type: session.SchemaValueTypeBinary},
+ },
+ }
+}
+
+func TestCompileCountDistinctOverTag_RendersCountDistinctSyntax(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ compiled, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "service"}}},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("Compile returned error: %v", compileErr)
+ }
+ // COUNT(DISTINCT service), not the generic "%s(%s)" shape (which would
+ // render the invalid COUNT_DISTINCT(service)).
+ if !strings.Contains(compiled.Query, "COUNT(DISTINCT service)") {
+ t.Fatalf("expected COUNT(DISTINCT service) in query, got: %s", compiled.Query)
+ }
+}
+
+// TestCompileCountDistinctOverNumericField_RendersCountDistinctSyntax pins the
+// design §6 matrix cell "Field INT / FLOAT x COUNT_DISTINCT": the server
+// analyzer accepts a field-targeted COUNT_DISTINCT (translateAgg routes it
+// through validateAggField, which does not gate on the function), so the
+// planner must compile it rather than insist on a tag.
+func TestCompileCountDistinctOverNumericField_RendersCountDistinctSyntax(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ compiled, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "latency"}}},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("Compile returned error: %v", compileErr)
+ }
+ if !strings.Contains(compiled.Query, "COUNT(DISTINCT latency)") {
+ t.Fatalf("expected COUNT(DISTINCT latency) in query, got: %s", compiled.Query)
+ }
+}
+
+// TestCompileCountDistinctOverNonNumericField_Rejects keeps the field arm
+// bounded by the same numeric rule every other field aggregation obeys.
+func TestCompileCountDistinctOverNonNumericField_Rejects(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ _, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "payload"}}},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr == nil || DescribeError(compileErr).Code != "AGGREGATE_FIELD_NOT_NUMERIC" {
+ t.Fatalf("expected AGGREGATE_FIELD_NOT_NUMERIC diagnostic, got %v", compileErr)
+ }
+}
+
+func TestCompileCountDistinctOverArrayTag_Rejects(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ _, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "tags"}}},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr == nil || DescribeError(compileErr).Code != "AGGREGATE_TAG_TYPE_UNSUPPORTED" {
+ t.Fatalf("expected AGGREGATE_TAG_TYPE_UNSUPPORTED diagnostic, got %v", compileErr)
+ }
+}
+
+func TestCompileTopNRejectsCountDistinct(t *testing.T) {
+ schema := session.SchemaSnapshot{
+ Type: session.ResourceTypeTopN,
+ Name: "service_latency_topn",
+ Groups: []string{"production"},
+ }
+ resource := Resource{Type: session.ResourceTypeTopN, Name: "service_latency_topn", Groups: []string{"production"}}
+ _, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Aggregate: &Aggregate{Function: AggregateCountDistinct},
+ TimeRange: TimeRange{Start: "-30m"},
+ TopN: 5,
+ }, schema)
+ if compileErr == nil || !strings.Contains(compileErr.Error(), "COUNT_DISTINCT") {
+ t.Fatalf("expected a COUNT_DISTINCT rejection, got %v", compileErr)
+ }
+}
+
+func TestCompileGroupByTimeBucket_RendersLeadingGroupKey(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ compiled, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateSum, Column: "latency"}}},
+ TimeBucket: &GroupByTimeBucket{Width: "5m"},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("Compile returned error: %v", compileErr)
+ }
+ if !strings.Contains(compiled.Query, "GROUP BY TIME_BUCKET('5m')") {
+ t.Fatalf("expected a leading TIME_BUCKET('5m') group key, got: %s", compiled.Query)
+ }
+}
+
+func TestCompileGroupByTimeBucketNoWidth_RendersEmptyArgs(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ compiled, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Aggregate: &Aggregate{Function: AggregateSum, Column: "latency"}}},
+ TimeBucket: &GroupByTimeBucket{},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("Compile returned error: %v", compileErr)
+ }
+ if !strings.Contains(compiled.Query, "GROUP BY TIME_BUCKET()") {
+ t.Fatalf("expected a leading TIME_BUCKET() group key, got: %s", compiled.Query)
+ }
+}
+
+func TestCompileGroupByTimeBucketAndTag_OrdersTimeBucketFirst(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ compiled, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Column: "service"}, {Aggregate: &Aggregate{Function: AggregateSum, Column: "latency"}}},
+ GroupBy: []string{"service"},
+ TimeBucket: &GroupByTimeBucket{Width: "1h"},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("Compile returned error: %v", compileErr)
+ }
+ if !strings.Contains(compiled.Query, "GROUP BY TIME_BUCKET('1h'), service::TAG") {
+ t.Fatalf("expected TIME_BUCKET to lead the group list, got: %s", compiled.Query)
+ }
+}
+
+func TestCompileGroupByTimeBucketWithoutAggregate_Rejects(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ _, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ TimeBucket: &GroupByTimeBucket{Width: "5m"},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr == nil || !strings.Contains(compileErr.Error(), "GROUP BY requires exactly one aggregate") {
+ t.Fatalf("expected a missing-aggregate rejection, got %v", compileErr)
+ }
+}
+
+func TestCompileGroupByTimeBucketOnNonMeasure_Rejects(t *testing.T) {
+ stream := session.SchemaSnapshot{Type: session.ResourceTypeStream, Name: "logs", Groups: []string{"production"}}
+ resource := Resource{Type: session.ResourceTypeStream, Name: "logs", Groups: []string{"production"}}
+ _, compileErr := Compile(QueryPlan{
+ Resource: resource,
+ TimeBucket: &GroupByTimeBucket{Width: "5m"},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, stream)
+ if compileErr == nil || !strings.Contains(compileErr.Error(), "GROUP BY is supported only for MEASURE queries") {
+ t.Fatalf("expected a MEASURE-only rejection, got %v", compileErr)
+ }
+}
+
func TestCompileUsesIndexRuleNameForOrderBy(t *testing.T) {
schema := session.SchemaSnapshot{
Type: session.ResourceTypeStream,
@@ -352,3 +521,74 @@ func TestCompileTopNUsesRealAggregationCapabilities(t *testing.T) {
t.Fatalf("expected non-equality TopN filter rejection, got %v", operatorErr)
}
}
+
+// TestCompileTimeBucketWidthValidation pins that a width is checked with the
+// same duration rule the server applies (plan.resolveTimeBucket) instead of
+// being interpolated into the rendered literal unchecked. A quote-bearing
+// width is the case that would otherwise emit BYDBQL the parser rejects.
+func TestCompileTimeBucketWidthValidation(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ plan := func(width string) QueryPlan {
+ return QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Column: "service"}, {Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "service"}}},
+ GroupBy: []string{"service"},
+ TimeBucket: &GroupByTimeBucket{Width: width},
+ TimeRange: TimeRange{Start: "-30m"},
+ }
+ }
+ for _, width := range []string{"nonsense", "0s", "-5m", "1m') OR '"} {
+ _, compileErr := Compile(plan(width), countDistinctSchema())
+ if compileErr == nil || DescribeError(compileErr).Code != "GROUP_BY_TIME_BUCKET_WIDTH_INVALID" {
+ t.Fatalf("width %q: expected GROUP_BY_TIME_BUCKET_WIDTH_INVALID, got %v", width, compileErr)
+ }
+ }
+ compiled, compileErr := Compile(plan("5m"), countDistinctSchema())
+ if compileErr != nil {
+ t.Fatalf("valid width rejected: %v", compileErr)
+ }
+ if !strings.Contains(compiled.Query, "TIME_BUCKET('5m')") {
+ t.Fatalf("expected TIME_BUCKET('5m') in query, got: %s", compiled.Query)
+ }
+}
+
+// TestCompileBucketedOrderingRejected mirrors the server's own
+// validateBucketableOrdering: a bucketed query may not name an index rule and
+// may not order descending. Compiling either would produce a query that only
+// fails once it reaches the server.
+func TestCompileBucketedOrderingRejected(t *testing.T) {
+ resource := Resource{Type: session.ResourceTypeMeasure, Name: "service_latency", Groups: []string{"production"}}
+ plan := func(order *Order) QueryPlan {
+ return QueryPlan{
+ Resource: resource,
+ Projection: []Projection{{Column: "service"}, {Aggregate: &Aggregate{Function: AggregateCountDistinct, Column: "service"}}},
+ GroupBy: []string{"service"},
+ TimeBucket: &GroupByTimeBucket{Width: "5m"},
+ OrderBy: order,
+ TimeRange: TimeRange{Start: "-30m"},
+ }
+ }
+ if _, compileErr := Compile(plan(&Order{IndexRule: "latency_index", Direction: OrderAscending}), countDistinctSchema()); compileErr == nil {
+ t.Fatal("expected an index-rule order on a bucketed query to be rejected")
+ }
+ if _, compileErr := Compile(plan(&Order{Direction: OrderDescending}), countDistinctSchema()); compileErr == nil {
+ t.Fatal("expected a descending order on a bucketed query to be rejected")
+ }
+ if _, compileErr := Compile(plan(&Order{Direction: OrderAscending}), countDistinctSchema()); compileErr != nil {
+ t.Fatalf("ascending time order on a bucketed query must compile: %v", compileErr)
+ }
+}
+
+// TestCompileTopNRejectsTimeBucket pins that a TOPN plan cannot carry a
+// time_bucket, which compileTopN has no way to render and would drop.
+func TestCompileTopNRejectsTimeBucket(t *testing.T) {
+ _, compileErr := Compile(QueryPlan{
+ Resource: Resource{Type: session.ResourceTypeTopN, Name: "service_latency_topn", Groups: []string{"production"}},
+ TopN: 5,
+ TimeBucket: &GroupByTimeBucket{Width: "5m"},
+ TimeRange: TimeRange{Start: "-30m"},
+ }, countDistinctSchema())
+ if compileErr == nil {
+ t.Fatal("expected a TOPN plan carrying time_bucket to be rejected")
+ }
+}
diff --git a/docs/api-reference.md b/docs/api-reference.md
index ed6cef7a0..a94360ae1 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -3536,7 +3536,7 @@ GroupDeletionTask represents the status of a group deletion operation.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -3571,7 +3571,7 @@ GroupRegistryServiceDeleteResponse is the response for deleting a group.
| ----- | ---- | ----- | ----------- |
| schema_info | [SchemaInfo](#banyandb-database-v1-SchemaInfo) | | schema_info contains the schema resources that would be deleted (populated in dry-run mode). |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -3749,7 +3749,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -3779,7 +3779,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -3811,7 +3811,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -3932,7 +3932,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -3962,7 +3962,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -3994,7 +3994,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -4115,7 +4115,7 @@ GroupRegistryServiceQueryResponse is the response for querying a group deletion
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -4212,7 +4212,7 @@ LiaisonInfo contains information about pending operations in liaison.
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -4418,7 +4418,7 @@ materialized yet -- the agent then takes the runtime fingerprint from cache.
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -4885,7 +4885,7 @@ error).
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -5036,7 +5036,7 @@ error).
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -5068,7 +5068,7 @@ error).
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
@@ -5189,7 +5189,7 @@ error).
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision assigned by the server on successful create/update. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision assigned by the server on successful create/update. |
@@ -5251,7 +5251,7 @@ error).
| ----- | ---- | ----- | ----------- |
| deleted | [bool](#bool) | | |
| delete_time | [int64](#int64) | | delete_time is the server-assigned tombstone timestamp in unix nanos. |
-| mod_revision | [int64](#int64) | | mod_revision is the etcd revision of the tombstone; zero if the server did not record one. |
+| mod_revision | [int64](#int64) | | mod_revision is the schema revision of the tombstone; zero if the server did not record one. |
diff --git a/docs/interacting/bydbql.md b/docs/interacting/bydbql.md
index 2910a6677..8743407c8 100644
--- a/docs/interacting/bydbql.md
+++ b/docs/interacting/bydbql.md
@@ -531,14 +531,20 @@ BydbQL for measures is tailored for analytical queries on aggregated numerical d
### 5.1. Grammar
```
-measure_query ::= SELECT projection from_measure_clause TIME time_condition [WHERE criteria] [GROUP BY column_list] [ORDER BY order_expression] [LIMIT integer] [OFFSET integer] [WITH QUERY_TRACE]
-from_measure_clause ::= "FROM MEASURE" identifier "IN" ["("] group_list [")"] [ON ["("] stage_list [")"] STAGES]
-projection ::= "*" | (column_list | agg_function "(" identifier ")" | top_clause)
+measure_query ::= SELECT projection from_measure_clause TIME time_condition [WHERE criteria] [GROUP BY group_list] [ORDER BY order_expression] [LIMIT integer] [OFFSET integer] [WITH QUERY_TRACE]
+from_measure_clause ::= "FROM MEASURE" identifier "IN" ["("] group_list_id [")"] [ON ["("] stage_list [")"] STAGES]
+projection ::= "*" | (column_list | agg_function "(" ["DISTINCT"] identifier ")" | top_clause)
top_clause ::= "TOP" integer identifier ["ASC" | "DESC"] ["," column_list]
column_list ::= identifier ("," identifier)* ["::tag" | "::field"]
stage_list ::= identifier ("," identifier)+
agg_function ::= "SUM" | "MEAN" | "COUNT" | "MAX" | "MIN"
-group_list ::= identifier ("," identifier)+
+ /* "DISTINCT" is only valid with COUNT: COUNT(DISTINCT identifier) */
+group_list ::= group_column ("," group_column)+
+group_column ::= identifier | time_bucket_function
+time_bucket_function ::= "TIME_BUCKET" "(" [string_literal] ")"
+ /* at most one TIME_BUCKET(...) per GROUP BY clause; empty width defers
+ to the measure's own interval */
+group_list_id ::= identifier ("," identifier)+
criteria ::= condition (("AND" | "OR") condition)*
condition ::= identifier binary_op (value | value_list)
time_condition ::= "=" timestamp | ">" timestamp | "<" timestamp | ">=" timestamp | "<=" timestamp | "BETWEEN" timestamp "AND" timestamp
@@ -564,12 +570,14 @@ The `SELECT` clause for measures is highly flexible, allowing for the selection
- `SELECT <field_key>, <tag_key>`: Returns specific fields and tags. The parser will infer the type of each identifier from the measure's schema.
- `SELECT <identifier>::field, <identifier>::tag`: If a field and a tag share the same name, the `::field` or `::tag` syntax **must** be used to disambiguate the identifier's type.
- The clause also supports aggregation functions (`SUM`, `MEAN`, `COUNT`, `MAX`, `MIN`) and a `TOP N` clause for ranked results.
+- An aggregate function's column resolves against both tags and fields, not just fields — `SUM(latency)` aggregates a field, `COUNT(DISTINCT user_id)` aggregates a tag. `DISTINCT` is only accepted inside `COUNT`; `SUM(DISTINCT x)` and similar are rejected as a parse error.
### 5.3. Mapping to `measure.v1.QueryRequest`
- **`FROM MEASURE name IN groups`** or **`FROM MEASURE name IN (groups)`**: Maps to the `name` and `groups` fields. Both are required.
- **`SELECT <tag1>, <field1>, <field2>`**: The transformer inspects each identifier. Those identified as tags (either by schema lookup or `::tag`) are added to `tag_projection`. Those identified as fields (by schema lookup or `::field`) are added to `field_projection`.
-- **`SELECT SUM(field)`**: Maps to `agg`.
+- **`SELECT SUM(field)`**: Maps to `agg`, setting `agg.field_name`.
+- **`SELECT COUNT(DISTINCT tag)`**: Maps to `agg` with `function = AGGREGATION_FUNCTION_COUNT_DISTINCT`, setting `agg.tag_name` and `agg.tag_family` instead of `agg.field_name`. The output column is named after the tag (`tag`), not after the function. A `COUNT(DISTINCT field)` over an INT or FLOAT field is also accepted, and sets `agg.field_name` as any other field aggregation does.
- **`TIME` clause (required)**: Maps to `time_range`:
- **`TIME = '2023-01-01T00:00:00Z'`**: Sets `begin` and `end` to the same timestamp.
- **`TIME > '2023-01-01T00:00:00Z'`**: Sets `begin` to the timestamp.
@@ -579,11 +587,13 @@ The `SELECT` clause for measures is highly flexible, allowing for the selection
- **`TIME BETWEEN '2023-01-01T00:00:00Z' AND '2023-01-02T00:00:00Z'`**: Sets `begin` and `end` to the respective timestamps.
- **`TIME > '-30m'`**: Sets `begin` to 30 minutes ago.
- **`TIME BETWEEN '-1h' AND 'now'`**: Sets `begin` to 1 hour ago and `end` to current time.
-- **`GROUP BY <tag1>, <tag2>`**: The `GROUP BY` clause takes a simple list of tags and maps to `group_by.tag_projection`.
- - **Note**: When the query contains an aggregate function (e.g., `SUM`, `AVG`, `COUNT`, `MAX`, `MIN`) with `GROUP BY`, the `GROUP BY` clause **must include at least one field**. This ensures proper aggregation behavior in measure queries.
-- **`SELECT TOP N ...`**: Maps to the `top` message.
+- **`GROUP BY <tag1>, <tag2>`**: The `GROUP BY` clause takes a list of tags and maps to `group_by.tag_projection`. Each grouped tag must also appear in the query's own `SELECT` projection.
+- **`GROUP BY TIME_BUCKET(width), <tag>`**: Maps to `group_by.time_bucket`, setting `group_by.time_bucket.width`. An empty `width` (`TIME_BUCKET()`) defers to the measure's own `interval`; a duration string (e.g. `'5m'`) uses the same units as `Measure.interval` (`ns`, `us`/`µs`, `ms`, `s`, `m`, `h`, plus the custom `d` suffix — see `pkg/timestamp.ParseDuration`). At most one `TIME_BUCKET(...)` is allowed per `GROUP BY` clause. Results are pre-ordered by bucket ascending, so a bucketed q [...]
+- **`SELECT TOP N ...`**: Maps to the `top` message. `TOP` can rank by a tag-targeted aggregation's own output column (e.g. `TOP 10 user_id DESC` when `COUNT(DISTINCT user_id)` is projected), not only by a field.
- **`WITH QUERY_TRACE`**: Maps to the `trace` field to enable distributed tracing of query execution.
+**Note on `LIMIT` and `TIME_BUCKET`**: `LIMIT` defaults to 100 when omitted. A bucketed `GROUP BY` returns one row per (bucket, tag-group), so a wide time window with a narrow bucket width can produce far more than 100 rows; without an explicit `LIMIT` sized to the expected row count, the response is silently truncated to the first 100 rows in bucket-ascending order rather than returning an error. Always set `LIMIT` explicitly for a bucketed query.
+
### 5.4. Examples
```sql
@@ -701,6 +711,23 @@ SELECT
FROM MEASURE service_cpm IN us-west ON (warn, cold) STAGES
TIME > '-30m'
GROUP BY region;
+
+-- Count distinct users per region
+SELECT
+ region,
+ COUNT(DISTINCT user_id)
+FROM MEASURE service_cpm IN us-west
+TIME > '-30m'
+GROUP BY region;
+
+-- Bucket a metric into 5-minute windows, per region
+SELECT
+ region,
+ SUM(latency)
+FROM MEASURE service_cpm IN us-west
+TIME > '-2h'
+GROUP BY TIME_BUCKET('5m'), region
+LIMIT 500;
```
## 6. BydbQL for Top-N
diff --git a/pkg/bydbql/bydbql_test.go b/pkg/bydbql/bydbql_test.go
index 28947e2dd..5e8c04afc 100644
--- a/pkg/bydbql/bydbql_test.go
+++ b/pkg/bydbql/bydbql_test.go
@@ -1506,6 +1506,42 @@ var _ = Describe("Parser", func() {
Expect(aggColName).To(Equal("metrics.response.latency"))
})
+ It("parses COUNT(DISTINCT ...)", func() {
+ grammar, err := ParseQuery("SELECT COUNT(DISTINCT entity_id) FROM MEASURE m IN default TIME > '-30m'")
+ Expect(err).To(BeNil())
+ Expect(grammar).NotTo(BeNil())
+
+ stmt := grammar.Select
+ Expect(stmt.Projection.Columns).To(HaveLen(1))
+ agg := stmt.Projection.Columns[0].Aggregate
+ Expect(agg).NotTo(BeNil())
+ Expect(strings.ToUpper(agg.Function)).To(Equal("COUNT"))
+ Expect(agg.Distinct).To(BeTrue())
+ aggColName, aggErr := agg.Column.ToString(false)
+ Expect(aggErr).To(BeNil())
+ Expect(aggColName).To(Equal("entity_id"))
+ })
+
+ It("parses COUNT(col) without DISTINCT", func() {
+ grammar, err := ParseQuery("SELECT COUNT(entity_id) FROM MEASURE m IN default TIME > '-30m'")
+ Expect(err).To(BeNil())
+ Expect(grammar).NotTo(BeNil())
+
+ Expect(grammar.Select.Projection.Columns[0].Aggregate.Distinct).To(BeFalse())
+ })
+
+ It("rejects SUM(DISTINCT ...)", func() {
+ _, err := ParseQuery("SELECT SUM(DISTINCT value) FROM MEASURE m IN default TIME > '-30m'")
+ Expect(err).NotTo(BeNil())
+ Expect(err.Error()).To(ContainSubstring("DISTINCT is only valid inside COUNT"))
+ })
+
+ It("rejects MEAN(DISTINCT ...)", func() {
+ _, err := ParseQuery("SELECT MEAN(DISTINCT value) FROM MEASURE m IN default TIME > '-30m'")
+ Expect(err).NotTo(BeNil())
+ Expect(err.Error()).To(ContainSubstring("DISTINCT is only valid inside COUNT"))
+ })
+
It("parses complex query with multiple nested paths", func() {
grammar, err := ParseQuery(`SELECT
trace.span.id,
@@ -1778,6 +1814,56 @@ var _ = Describe("Parser", func() {
})
})
+ Describe("TIME_BUCKET in GROUP BY", func() {
+ It("parses TIME_BUCKET with an explicit width", func() {
+ grammar, err := ParseQuery("SELECT SUM(value) FROM MEASURE m IN default TIME > '-30m' GROUP BY TIME_BUCKET('5m')")
+ Expect(err).To(BeNil())
+ Expect(grammar).NotTo(BeNil())
+
+ stmt := grammar.Select
+ Expect(stmt.GroupBy).NotTo(BeNil())
+ Expect(stmt.GroupBy.Columns).To(HaveLen(1))
+ tb := stmt.GroupBy.Columns[0].TimeBucket
+ Expect(tb).NotTo(BeNil())
+ Expect(stmt.GroupBy.Columns[0].Identifier).To(BeNil())
+ Expect(tb.Width).NotTo(BeNil())
+ Expect(*tb.Width).To(Equal("5m"))
+ })
+
+ It("parses TIME_BUCKET with no width", func() {
+ grammar, err := ParseQuery("SELECT SUM(value) FROM MEASURE m IN default TIME > '-30m' GROUP BY TIME_BUCKET()")
+ Expect(err).To(BeNil())
+ Expect(grammar).NotTo(BeNil())
+
+ tb := grammar.Select.GroupBy.Columns[0].TimeBucket
+ Expect(tb).NotTo(BeNil())
+ Expect(tb.Width).To(BeNil())
+ })
+
+ It("parses TIME_BUCKET combined with a tag key", func() {
+ grammar, err := ParseQuery("SELECT region, SUM(value) FROM MEASURE m IN default TIME > '-30m' GROUP BY TIME_BUCKET('1h'), region")
+ Expect(err).To(BeNil())
+ Expect(grammar).NotTo(BeNil())
+
+ stmt := grammar.Select
+ Expect(stmt.GroupBy.Columns).To(HaveLen(2))
+ Expect(stmt.GroupBy.Columns[0].TimeBucket).NotTo(BeNil())
+ Expect(stmt.GroupBy.Columns[1].TimeBucket).To(BeNil())
+ Expect(stmt.GroupBy.Columns[1].Identifier).NotTo(BeNil())
+ })
+
+ It("rejects a second TIME_BUCKET in the same GROUP BY", func() {
+ _, err := ParseQuery("SELECT SUM(value) FROM MEASURE m IN default TIME > '-30m' GROUP BY TIME_BUCKET('1h'), TIME_BUCKET('5m')")
+ Expect(err).NotTo(BeNil())
+ Expect(err.Error()).To(ContainSubstring("at most one TIME_BUCKET"))
+ })
+
+ It("rejects TIME_BUCKET in the SELECT projection", func() {
+ _, err := ParseQuery("SELECT TIME_BUCKET('1m') FROM MEASURE m IN default TIME > '-30m'")
+ Expect(err).NotTo(BeNil())
+ })
+ })
+
Describe("Case Insensitivity", func() {
// Test that keywords are case-insensitive
queries := []string{
diff --git a/pkg/bydbql/grammar.go b/pkg/bydbql/grammar.go
index e0022a139..4a80e1225 100644
--- a/pkg/bydbql/grammar.go
+++ b/pkg/bydbql/grammar.go
@@ -96,10 +96,14 @@ type GrammarColumn struct {
TypeSpec *string `parser:"( '::' @('TAG'|'FIELD') )?"`
}
-// GrammarAggregateFunction represents aggregate functions.
+// GrammarAggregateFunction represents aggregate functions. DISTINCT is
+// grammatically accepted after any function — participle struct tags can't
+// express a per-alternative semantic predicate — ParseQuery's post-parse
+// check (checkAggregateAndGroupByShape) rejects it outside COUNT.
type GrammarAggregateFunction struct {
Function string `parser:"@('SUM'|'MEAN'|'AVG'|'COUNT'|'MAX'|'MIN')"`
- Column *GrammarIdentifierPath `parser:"'(' @@ ')'"`
+ Distinct bool `parser:"'(' @'DISTINCT'?"`
+ Column *GrammarIdentifierPath `parser:"@@ ')'"`
}
// GrammarTopNAggregateFunction represents aggregate functions without column (for TOP N).
@@ -301,12 +305,24 @@ type GrammarGroupByClause struct {
Columns []*GrammarGroupByColumn `parser:"@@ ( ',' @@ )*"`
}
-// GrammarGroupByColumn represents a column in GROUP BY.
+// GrammarGroupByColumn represents a column in GROUP BY: a plain tag/field
+// identifier, or the TIME_BUCKET(...) pseudo-column.
type GrammarGroupByColumn struct {
- Identifier *GrammarIdentifierPath `parser:"@@"`
+ TimeBucket *GrammarTimeBucket `parser:"( @@"`
+ Identifier *GrammarIdentifierPath `parser:" | @@ )"`
TypeSpec *string `parser:"( '::' @('TAG'|'FIELD') )?"`
}
+// GrammarTimeBucket represents TIME_BUCKET(<duration>), valid only inside
+// GROUP BY. Width is optional; an empty width defers to the measure's own
+// interval (design §5.3).
+type GrammarTimeBucket struct {
+ TimeBucket string `parser:"@'TIME_BUCKET'"`
+ LParen string `parser:"'('"`
+ Width *string `parser:"@String?"`
+ RParen string `parser:"')'"`
+}
+
// GrammarSelectOrderByClause represents ORDER BY clause in SELECT statement.
type GrammarSelectOrderByClause struct {
Order string `parser:"@'ORDER'"`
diff --git a/pkg/bydbql/parser.go b/pkg/bydbql/parser.go
index 9596e41d8..b832a7df2 100644
--- a/pkg/bydbql/parser.go
+++ b/pkg/bydbql/parser.go
@@ -31,7 +31,7 @@ var bydbqlKeywords = []string{
"IN", "ON", "STAGES", "TIME", "BETWEEN", "AND", "OR", "WHERE", "GROUP", "BY", "ORDER",
"ASC", "DESC", "LIMIT", "OFFSET", "WITH", "QUERY_TRACE", "SUM", "MEAN",
"AVG", "COUNT", "MAX", "MIN", "TAG", "FIELD", "NOT", "HAVING", "MATCH",
- "AGGREGATE", "NULL",
+ "AGGREGATE", "NULL", "DISTINCT", "TIME_BUCKET",
}
// Lexer and parser are initialized in init().
@@ -95,10 +95,55 @@ func ParseQuery(query string) (*Grammar, error) {
if err != nil {
return nil, fmt.Errorf("syntax error: %w", err)
}
+ if err := checkAggregateAndGroupByShape(grammar); err != nil {
+ return nil, err
+ }
return grammar, nil
}
+// checkAggregateAndGroupByShape enforces two constraints participle's
+// struct-tag grammar cannot express as per-alternative predicates:
+// - DISTINCT is only valid inside COUNT — SUM(DISTINCT x) etc. is rejected.
+// - At most one TIME_BUCKET(...) pseudo-column is allowed per GROUP BY.
+//
+// Both are semantic rules, but are enforced here (rather than at transform
+// time) so a malformed query fails exactly like any other syntax error, one
+// step after the raw participle parse — the same precedent checkParenDepth
+// already set for a pre-parse check.
+func checkAggregateAndGroupByShape(g *Grammar) error {
+ if g.Select == nil {
+ return nil
+ }
+ if proj := g.Select.Projection; proj != nil {
+ var columns []*GrammarColumn
+ columns = append(columns, proj.Columns...)
+ if proj.TopN != nil {
+ columns = append(columns, proj.TopN.OtherColumns...)
+ }
+ for _, col := range columns {
+ if col.Aggregate == nil {
+ continue
+ }
+ if col.Aggregate.Distinct && !strings.EqualFold(col.Aggregate.Function, "COUNT") {
+ return fmt.Errorf("syntax error: DISTINCT is only valid inside COUNT, got %s(DISTINCT ...)", col.Aggregate.Function)
+ }
+ }
+ }
+ if gb := g.Select.GroupBy; gb != nil {
+ bucketCount := 0
+ for _, col := range gb.Columns {
+ if col.TimeBucket != nil {
+ bucketCount++
+ }
+ }
+ if bucketCount > 1 {
+ return fmt.Errorf("syntax error: at most one TIME_BUCKET(...) is allowed in GROUP BY, got %d", bucketCount)
+ }
+ }
+ return nil
+}
+
// checkParenDepth rejects queries whose parenthesis nesting exceeds maxParenDepth.
// It skips over quoted string content — which may contain unbalanced or
// backslash-escaped quote characters, per the String lexer rule — so literal
diff --git a/pkg/bydbql/transformer.go b/pkg/bydbql/transformer.go
index 2167a9283..b8db6334f 100644
--- a/pkg/bydbql/transformer.go
+++ b/pkg/bydbql/transformer.go
@@ -363,21 +363,22 @@ func (r *transformRun) transformMeasureQuery(ctx context.Context, grammar *Gramm
}
// convert aggregation
- agg, err := r.convertAggregation(statement.Projection, allFields)
+ agg, err := r.convertAggregation(statement.Projection, allTags, allFields)
if err != nil {
return nil, fmt.Errorf("failed to convert aggregation: %w", err)
}
- // convert group by
+ // convert group by. Unlike the deleted row-path engine, the vectorized
+ // engine never reads GroupBy.field_name (confirmed: zero references in
+ // plan/analyzer.go / plan.go) — a tag-only or time-bucket-only GroupBy
+ // is a valid, already-shipped shape (#14089/#14090), so there is no
+ // "GroupBy must include a field" requirement to enforce here.
groupBy, err := r.convertGroupBy(statement.GroupBy, projection, fields)
if err != nil {
return nil, fmt.Errorf("failed to convert group by: %w", err)
}
- if agg != nil && groupBy != nil && groupBy.FieldName == "" {
- return nil, errors.New("when aggregation and group by are both present, group by must include a field")
- }
- top, err := r.convertTOP(statement.Projection, allFields)
+ top, err := r.convertTOP(statement.Projection, allFields, agg)
if err != nil {
return nil, fmt.Errorf("failed to convert top: %w", err)
}
@@ -652,7 +653,7 @@ func (r *transformRun) transformTopNMeasureQuery(ctx context.Context, grammar *G
// convert agg
var aggFunc modelv1.AggregationFunction
if statement.AggregateBy != nil {
- aggFunc, err = r.convertAggregationFunc(statement.AggregateBy.Function.Function)
+ aggFunc, err = r.convertAggregationFunc(statement.AggregateBy.Function.Function, false)
if err != nil {
return nil, err
}
@@ -772,6 +773,21 @@ func (r *transformRun) convertGroupBy(g *GrammarGroupByClause, queryTags *modelv
}
for _, c := range g.Columns {
+ if c.TimeBucket != nil {
+ if c.TypeSpec != nil {
+ return nil, errors.New("TIME_BUCKET does not support ::TAG/::FIELD")
+ }
+ if groupBy.TimeBucket != nil {
+ return nil, errors.New("only one TIME_BUCKET is allowed in GROUP BY")
+ }
+ width := ""
+ if c.TimeBucket.Width != nil {
+ width = *c.TimeBucket.Width
+ }
+ groupBy.TimeBucket = &measurev1.QueryRequest_GroupBy_TimeBucket{Width: width}
+ continue
+ }
+
colName, nameErr := c.Identifier.ToString(c.TypeSpec != nil)
if nameErr != nil {
return nil, fmt.Errorf("failed to parse column identifier: %w", nameErr)
@@ -836,14 +852,29 @@ func (r *transformRun) convertGroupBy(g *GrammarGroupByClause, queryTags *modelv
Tags: names,
})
}
- groupBy.TagProjection = &modelv1.TagProjection{
- TagFamilies: tagFamilies,
+ // Only set TagProjection when there's actually a tag key — a nil field
+ // (no GROUP BY tag key at all, e.g. a TIME_BUCKET-only or field-only
+ // GROUP BY) must stay nil, not a non-nil-but-empty message: the QL
+ // fixture comparison (test/cases/measure/data/data.go) does a strict
+ // protocmp.Equal against a hand-written request, and a YAML fixture
+ // with no tagProjection key unmarshals to nil, which never
+ // protocmp-equals a present-but-empty TagProjection.
+ if len(tagFamilies) > 0 {
+ groupBy.TagProjection = &modelv1.TagProjection{
+ TagFamilies: tagFamilies,
+ }
}
return groupBy, nil
}
-func (r *transformRun) convertAggregation(projection *GrammarProjection, allFields map[string]*databasev1.FieldSpec) (*measurev1.QueryRequest_Aggregation, error) {
+// convertAggregation resolves the projection's single aggregation column
+// against both tags and fields (design §5.4: an aggregate target can be a
+// tag, not just a field), mirroring the ambiguity rule
+// checkOrAddGrammarTagOrField already applies to plain projection columns.
+func (r *transformRun) convertAggregation(
+ projection *GrammarProjection, allTags map[string]*tagSpecWithFamily, allFields map[string]*databasev1.FieldSpec,
+) (*measurev1.QueryRequest_Aggregation, error) {
var columns []*GrammarColumn
if projection != nil && len(projection.Columns) > 0 {
columns = append(columns, projection.Columns...)
@@ -867,29 +898,43 @@ func (r *transformRun) convertAggregation(projection *GrammarProjection, allFiel
return nil, nil
}
- // check the aggregation column in the field list
aggColName, nameErr := aggCol.Aggregate.Column.ToString(true)
if nameErr != nil {
return nil, fmt.Errorf("failed to parse aggregate column identifier: %w", nameErr)
}
- _, exist := allFields[aggColName]
- if !exist {
- return nil, fmt.Errorf("field %s not found in schema", aggColName)
- }
-
- aggFunc, err := r.convertAggregationFunc(aggCol.Aggregate.Function)
+ aggFunc, err := r.convertAggregationFunc(aggCol.Aggregate.Function, aggCol.Aggregate.Distinct)
if err != nil {
return nil, err
}
- return &measurev1.QueryRequest_Aggregation{
- Function: aggFunc,
- FieldName: aggColName,
- }, nil
+ tag, tagExists := allTags[aggColName]
+ _, fieldExists := allFields[aggColName]
+ switch {
+ case tagExists && fieldExists:
+ return nil, fmt.Errorf("ambiguous aggregation column %s found in both tags and fields", aggColName)
+ case fieldExists:
+ return &measurev1.QueryRequest_Aggregation{
+ Function: aggFunc,
+ FieldName: aggColName,
+ }, nil
+ case tagExists:
+ return &measurev1.QueryRequest_Aggregation{
+ Function: aggFunc,
+ TagName: aggColName,
+ TagFamily: tag.family,
+ }, nil
+ default:
+ return nil, fmt.Errorf("column %s not found in schema", aggColName)
+ }
}
-func (r *transformRun) convertAggregationFunc(f string) (modelv1.AggregationFunction, error) {
+// convertAggregationFunc maps a grammar aggregate function name to its proto
+// value. distinct is true only for a COUNT(DISTINCT ...) — the grammar
+// accepts DISTINCT after any function (ParseQuery's checkAggregateAndGroupByShape
+// rejects it outside COUNT before this is ever called), so distinct is
+// meaningless for every other case here.
+func (r *transformRun) convertAggregationFunc(f string, distinct bool) (modelv1.AggregationFunction, error) {
switch strings.ToUpper(f) {
case "MEAN", "AVG":
return modelv1.AggregationFunction_AGGREGATION_FUNCTION_MEAN, nil
@@ -898,6 +943,9 @@ func (r *transformRun) convertAggregationFunc(f string) (modelv1.AggregationFunc
case "MIN":
return modelv1.AggregationFunction_AGGREGATION_FUNCTION_MIN, nil
case "COUNT":
+ if distinct {
+ return modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT_DISTINCT, nil
+ }
return modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT, nil
case "SUM":
return modelv1.AggregationFunction_AGGREGATION_FUNCTION_SUM, nil
@@ -1651,7 +1699,14 @@ func (r *transformRun) convertCompareOp(op string) modelv1.Condition_BinaryOp {
}
}
-func (r *transformRun) convertTOP(projection *GrammarProjection, fields map[string]*databasev1.FieldSpec) (*measurev1.QueryRequest_Top, error) {
+// convertTOP resolves a SELECT TOP N <col> ranking column against either the
+// field list or, when the query aggregates over a tag (e.g. COUNT_DISTINCT),
+// the aggregation's own output column name — the server's HideTag convention
+// (#14088) names a tag-targeted agg's output after the tag itself, so
+// ranking by that tag name refers to the agg's result, not a raw projection.
+func (r *transformRun) convertTOP(
+ projection *GrammarProjection, fields map[string]*databasev1.FieldSpec, agg *measurev1.QueryRequest_Aggregation,
+) (*measurev1.QueryRequest_Top, error) {
if projection == nil || projection.TopN == nil {
return nil, nil
}
@@ -1662,9 +1717,9 @@ func (r *transformRun) convertTOP(projection *GrammarProjection, fields map[stri
return nil, fmt.Errorf("failed to parse order field identifier: %w", nameErr)
}
- // check the field exists in the field list
- _, exist := fields[orderFieldName]
- if !exist {
+ _, existsAsField := fields[orderFieldName]
+ matchesAggTagOutput := agg != nil && agg.GetTagName() != "" && agg.GetTagName() == orderFieldName
+ if !existsAsField && !matchesAggTagOutput {
return nil, fmt.Errorf("field %s not found in schema", orderFieldName)
}
diff --git a/pkg/bydbql/transformer_measure_test.go b/pkg/bydbql/transformer_measure_test.go
new file mode 100644
index 000000000..91032a997
--- /dev/null
+++ b/pkg/bydbql/transformer_measure_test.go
@@ -0,0 +1,176 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package bydbql_test
+
+import (
+ "context"
+
+ "github.com/google/go-cmp/cmp"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "go.uber.org/mock/gomock"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ measurev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/measure/v1"
+ modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+ "github.com/apache/skywalking-banyandb/banyand/metadata"
+ "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
+ . "github.com/apache/skywalking-banyandb/pkg/bydbql"
+)
+
+// measureTagAggSchema mirrors the composite_entity_metric/time_bucket_metric
+// fixtures used elsewhere in this repo's vec-engine test suite: two string
+// tags (one plays the entity/routing role) and one INT field, enough to
+// exercise tag-vs-field ambiguity, tag-targeted aggregation, and
+// GROUP BY TIME_BUCKET without pulling in a live schema registry.
+func measureTagAggSchema() *databasev1.Measure {
+ return &databasev1.Measure{
+ Metadata: &commonv1.Metadata{Name: "tag_agg_metrics", Group: "default"},
+ TagFamilies: []*databasev1.TagFamilySpec{{
+ Name: "default",
+ Tags: []*databasev1.TagSpec{
+ {Name: "entity_id", Type: databasev1.TagType_TAG_TYPE_STRING},
+ {Name: "id", Type: databasev1.TagType_TAG_TYPE_STRING},
+ },
+ }},
+ Fields: []*databasev1.FieldSpec{{Name: "value", FieldType: databasev1.FieldType_FIELD_TYPE_INT}},
+ Entity: &databasev1.Entity{TagNames: []string{"entity_id"}},
+ Interval: "1m",
+ }
+}
+
+var _ = Describe("Transform: COUNT_DISTINCT and TIME_BUCKET for measures", func() {
+ var transformer *Transformer
+
+ BeforeEach(func() {
+ ctrl := gomock.NewController(GinkgoT())
+ measureRegistry := schema.NewMockMeasure(ctrl)
+ measureRegistry.EXPECT().GetMeasure(gomock.Any(), gomock.Any()).Return(measureTagAggSchema(), nil).AnyTimes()
+ mockRepo := metadata.NewMockRepo(ctrl)
+ mockRepo.EXPECT().MeasureRegistry().AnyTimes().Return(measureRegistry)
+ transformer = NewTransformer(mockRepo)
+ })
+
+ transform := func(query string) (*measurev1.QueryRequest, error) {
+ grammar, parseErr := ParseQuery(query)
+ Expect(parseErr).To(BeNil())
+ Expect(BindParams(grammar, nil)).To(Succeed())
+ result, transformErr := transformer.Transform(context.Background(), grammar)
+ if transformErr != nil {
+ return nil, transformErr
+ }
+ req, ok := result.QueryRequest.(*measurev1.QueryRequest)
+ Expect(ok).To(BeTrue(), "expected a measure QueryRequest, got %T", result.QueryRequest)
+ return req, nil
+ }
+
+ diffOpts := []cmp.Option{
+ protocmp.Transform(),
+ protocmp.IgnoreFields(&measurev1.QueryRequest{}, "time_range"),
+ protocmp.SortRepeatedFields(&modelv1.TagProjection_TagFamily{}, "tags"),
+ }
+
+ It("resolves COUNT(DISTINCT tag) to a tag-targeted Aggregation", func() {
+ req, err := transform(
+ "SELECT entity_id, COUNT(DISTINCT entity_id) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY entity_id",
+ )
+ Expect(err).To(BeNil())
+ entityIDProjection := &modelv1.TagProjection{
+ TagFamilies: []*modelv1.TagProjection_TagFamily{{Name: "default", Tags: []string{"entity_id"}}},
+ }
+ want := &measurev1.QueryRequest{
+ Name: "tag_agg_metrics",
+ Groups: []string{"default"},
+ TagProjection: entityIDProjection,
+ Agg: &measurev1.QueryRequest_Aggregation{
+ Function: modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT_DISTINCT, TagName: "entity_id", TagFamily: "default",
+ },
+ GroupBy: &measurev1.QueryRequest_GroupBy{TagProjection: entityIDProjection},
+ }
+ Expect(cmp.Diff(want, req, diffOpts...)).To(BeEmpty())
+ })
+
+ It("resolves a non-distinct COUNT over a tag (general tag-agg gap, not just COUNT_DISTINCT)", func() {
+ req, err := transform("SELECT id, COUNT(entity_id) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY id")
+ Expect(err).To(BeNil())
+ Expect(req.GetAgg().GetFunction()).To(Equal(modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT))
+ Expect(req.GetAgg().GetTagName()).To(Equal("entity_id"))
+ Expect(req.GetAgg().GetTagFamily()).To(Equal("default"))
+ Expect(req.GetAgg().GetFieldName()).To(BeEmpty())
+ })
+
+ It("still resolves SUM over a field targeted by name", func() {
+ req, err := transform("SELECT SUM(value) FROM MEASURE tag_agg_metrics IN default TIME > '-15m'")
+ Expect(err).To(BeNil())
+ Expect(req.GetAgg().GetFunction()).To(Equal(modelv1.AggregationFunction_AGGREGATION_FUNCTION_SUM))
+ Expect(req.GetAgg().GetFieldName()).To(Equal("value"))
+ Expect(req.GetAgg().GetTagName()).To(BeEmpty())
+ })
+
+ It("accepts a tag-only GROUP BY combined with a field-targeted Agg (the deleted row-path constraint no longer applies)", func() {
+ req, err := transform("SELECT entity_id, SUM(value) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY entity_id")
+ Expect(err).To(BeNil())
+ Expect(req.GetGroupBy().GetFieldName()).To(BeEmpty())
+ Expect(req.GetGroupBy().GetTagProjection().GetTagFamilies()).NotTo(BeEmpty())
+ })
+
+ It("rejects an aggregation column that resolves to neither a tag nor a field", func() {
+ _, err := transform("SELECT COUNT(DISTINCT nonexistent) FROM MEASURE tag_agg_metrics IN default TIME > '-15m'")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("nonexistent"))
+ })
+
+ It("maps GROUP BY TIME_BUCKET() with no width to an empty Width", func() {
+ req, err := transform("SELECT SUM(value) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY TIME_BUCKET()")
+ Expect(err).To(BeNil())
+ want := &measurev1.QueryRequest{
+ Name: "tag_agg_metrics",
+ Groups: []string{"default"},
+ Agg: &measurev1.QueryRequest_Aggregation{Function: modelv1.AggregationFunction_AGGREGATION_FUNCTION_SUM, FieldName: "value"},
+ GroupBy: &measurev1.QueryRequest_GroupBy{TimeBucket: &measurev1.QueryRequest_GroupBy_TimeBucket{Width: ""}},
+ }
+ Expect(cmp.Diff(want, req, diffOpts...)).To(BeEmpty())
+ // TagProjection must be nil, not a present-but-empty message — a
+ // TIME_BUCKET-only GROUP BY has no tag key at all.
+ Expect(req.GetGroupBy().TagProjection).To(BeNil())
+ })
+
+ It("maps GROUP BY TIME_BUCKET('5m') with an explicit width", func() {
+ req, err := transform("SELECT SUM(value) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY TIME_BUCKET('5m')")
+ Expect(err).To(BeNil())
+ Expect(req.GetGroupBy().GetTimeBucket().GetWidth()).To(Equal("5m"))
+ })
+
+ It("maps GROUP BY TIME_BUCKET('5m'), tag combined", func() {
+ req, err := transform("SELECT id, SUM(value) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY TIME_BUCKET('5m'), id")
+ Expect(err).To(BeNil())
+ Expect(req.GetGroupBy().GetTimeBucket().GetWidth()).To(Equal("5m"))
+ Expect(req.GetGroupBy().GetTagProjection().GetTagFamilies()).To(HaveLen(1))
+ Expect(req.GetGroupBy().GetTagProjection().GetTagFamilies()[0].GetTags()).To(ConsistOf("id"))
+ })
+
+ It("ranks TOP N by a tag-targeted aggregation's own output column", func() {
+ req, err := transform("SELECT TOP 5 entity_id DESC, id, COUNT(DISTINCT entity_id) FROM MEASURE tag_agg_metrics IN default TIME > '-15m' GROUP BY id")
+ Expect(err).To(BeNil())
+ Expect(req.GetTop()).NotTo(BeNil())
+ Expect(req.GetTop().GetFieldName()).To(Equal("entity_id"))
+ Expect(req.GetTop().GetFieldValueSort()).To(Equal(modelv1.Sort_SORT_DESC))
+ })
+})
diff --git a/pkg/test/helpers/constant.go b/pkg/test/helpers/constant.go
index 65a780000..852763f1d 100644
--- a/pkg/test/helpers/constant.go
+++ b/pkg/test/helpers/constant.go
@@ -82,9 +82,8 @@ type Args struct {
IgnoreElementID bool
// SkipQL skips the BydbQL round-trip check (input/<Input>.ql) for this
// case. Temporary escape hatch for query shapes BydbQL cannot express
- // yet — e.g. GroupBy.time_bucket, which has no TIME_BUCKET(...) grammar
- // until apache/skywalking#14091 lands. Remove a case's SkipQL (and add
- // its .ql fixture) once BydbQL supports the shape.
+ // yet. Remove a case's SkipQL (and add its .ql fixture) once BydbQL
+ // supports the shape.
SkipQL bool
}
diff --git a/pkg/test/measure/testdata/measures/cardinality_metric.json b/pkg/test/measure/testdata/measures/cardinality_metric.json
new file mode 100644
index 000000000..658280c64
--- /dev/null
+++ b/pkg/test/measure/testdata/measures/cardinality_metric.json
@@ -0,0 +1,36 @@
+{
+ "metadata": {
+ "name": "cardinality_metric",
+ "group": "sw_metric"
+ },
+ "tag_families": [
+ {
+ "name": "default",
+ "tags": [
+ {
+ "name": "user_id",
+ "type": "TAG_TYPE_STRING"
+ },
+ {
+ "name": "api_key",
+ "type": "TAG_TYPE_STRING"
+ }
+ ]
+ }
+ ],
+ "fields": [
+ {
+ "name": "value",
+ "field_type": "FIELD_TYPE_INT",
+ "encoding_method": "ENCODING_METHOD_GORILLA",
+ "compression_method": "COMPRESSION_METHOD_ZSTD"
+ }
+ ],
+ "entity": {
+ "tag_names": [
+ "user_id"
+ ]
+ },
+ "interval": "20s",
+ "updated_at": "2021-04-15T01:30:15.01Z"
+}
diff --git a/test/cases/init.go b/test/cases/init.go
index ab713184f..5c146cad8 100644
--- a/test/cases/init.go
+++ b/test/cases/init.go
@@ -140,6 +140,32 @@ func Initialize(addr string, now time.Time) {
// cover that on regular time-series measures). See
// group_count_distinct_index_mode.yaml / group_count_index_mode.yaml.
casesmeasuredata.Write(conn, "index_mode_distinct_metric", "sw_metric", "index_mode_distinct_metric_data.json", now, 10*time.Second)
+ // cardinality_metric exercises COUNT_DISTINCT combined with
+ // GroupBy.time_bucket (design §7.2/§11 together). Its entity is
+ // [user_id], so a bucketed query must include user_id in GROUP BY (or
+ // target user_id itself) to satisfy §7.4's per-routing-tag pushdown
+ // check -- a pure `GROUP BY TIME_BUCKET(...)` with no tag component,
+ // counting DISTINCT on an unrelated tag (api_key), is correctly
+ // rejected the same way a GroupBy/Agg pair that covers neither the
+ // routing key nor the target always is. `cardinalityBase` is offset
+ // from `now` by a whole number of minutes so it stays minute-aligned,
+ // matching bucketStart's Unix-epoch-origin flooring
+ // (pkg/query/vectorized/measure/timebucket.go) -- every fixture here
+ // uses a bucket width of 1m or a divisor of it (30s). Each bucket
+ // belongs to exactly one user, so no fixture needs a tie-break rule for
+ // two users landing in the same bucket:
+ // bucket0 [+0s, +60s): user1 keyA,keyA,keyB (distinct 2)
+ // bucket1 [+60s, +120s): user2 keyX,keyY (distinct 2)
+ // bucket2 [+120s,+180s): user1 keyB,keyB,keyC (distinct 2)
+ // Across the whole window: user1 sees 3 distinct keys (keyA/keyB/keyC
+ // -- bucket0 ∪ bucket2), user2 sees 2 (keyX/keyY). See
+ // group_count_distinct_time_bucket.yaml,
+ // group_count_distinct_time_bucket_30s.yaml, and
+ // group_count_distinct_top_by_user.yaml.
+ cardinalityBase := now.Add(5 * time.Minute)
+ casesmeasuredata.Write(conn, "cardinality_metric", "sw_metric", "cardinality_metric_u1_b0_data.json", cardinalityBase.Add(30*time.Second), 10*time.Second)
+ casesmeasuredata.Write(conn, "cardinality_metric", "sw_metric", "cardinality_metric_u2_b1_data.json", cardinalityBase.Add(80*time.Second), 10*time.Second)
+ casesmeasuredata.Write(conn, "cardinality_metric", "sw_metric", "cardinality_metric_u1_b2_data.json", cardinalityBase.Add(150*time.Second), 10*time.Second)
casesmeasuredata.WriteMixed(conn, now.Add(30*time.Minute), interval,
casesmeasuredata.WriteSpec{
Metadata: &commonv1.Metadata{Name: "service_cpm_minute", Group: "sw_spec"},
diff --git a/test/cases/measure/cmd/generate/ql_renderer.go b/test/cases/measure/cmd/generate/ql_renderer.go
index c8dc26e76..582054d39 100644
--- a/test/cases/measure/cmd/generate/ql_renderer.go
+++ b/test/cases/measure/cmd/generate/ql_renderer.go
@@ -49,6 +49,15 @@ func RenderQL(req *measurev1.QueryRequest) (string, error) {
// GROUP BY
if req.GetGroupBy() != nil {
var groupCols []string
+ // TIME_BUCKET is the leading group key when present (matches the
+ // proto's own "leading group key" doc comment on GroupBy.time_bucket).
+ if tb := req.GetGroupBy().GetTimeBucket(); tb != nil {
+ if tb.GetWidth() != "" {
+ groupCols = append(groupCols, fmt.Sprintf("TIME_BUCKET('%s')", tb.GetWidth()))
+ } else {
+ groupCols = append(groupCols, "TIME_BUCKET()")
+ }
+ }
if tp := req.GetGroupBy().GetTagProjection(); tp != nil {
for _, family := range tp.GetTagFamilies() {
groupCols = append(groupCols, family.GetTags()...)
@@ -102,11 +111,23 @@ func renderProjection(req *measurev1.QueryRequest) string {
}
}
- // Aggregation in projection
+ // Aggregation in projection. The function and the target vary
+ // independently: COUNT_DISTINCT renders as COUNT(DISTINCT x) over either a
+ // tag or a numeric field (design §6), while every other function keeps the
+ // aggFunctionName(x) shape over either kind. Deriving the syntax from the
+ // target alone would rewrite a tag-targeted COUNT(id) into
+ // COUNT(DISTINCT id) and silently drop DISTINCT from a field-targeted
+ // COUNT_DISTINCT.
if agg := req.GetAgg(); agg != nil {
- aggFn := aggFunctionName(agg.GetFunction())
- fieldName := agg.GetFieldName()
- cols = append(cols, fmt.Sprintf("%s(%s)", aggFn, fieldName))
+ operand := agg.GetFieldName()
+ if tagName := agg.GetTagName(); tagName != "" {
+ operand = tagName
+ }
+ if agg.GetFunction() == modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT_DISTINCT {
+ cols = append(cols, fmt.Sprintf("COUNT(DISTINCT %s)", operand))
+ } else {
+ cols = append(cols, fmt.Sprintf("%s(%s)", aggFunctionName(agg.GetFunction()), operand))
+ }
}
// Field projection — all fields need the ::field suffix to disambiguate from tags
@@ -134,6 +155,12 @@ func aggFunctionName(fn modelv1.AggregationFunction) string {
return "COUNT"
case modelv1.AggregationFunction_AGGREGATION_FUNCTION_SUM:
return "SUM"
+ case modelv1.AggregationFunction_AGGREGATION_FUNCTION_COUNT_DISTINCT:
+ // renderProjection emits the COUNT(DISTINCT x) form directly, so this
+ // arm is unreachable from there. Kept explicit so the switch can't
+ // silently mis-map COUNT_DISTINCT to SUM via the default arm if a
+ // future caller reaches it another way.
+ return "COUNT"
default:
return "SUM"
}
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
index 977942dfd..817021338 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
@@ -15,4 +15,4 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+SELECT id, entity_id, COUNT(DISTINCT entity_id), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_by_entity.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_by_entity.ql
index 977942dfd..9a666c585 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_by_entity.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT entity_id, COUNT(id) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY entity_id
diff --git a/test/cases/measure/data/input/group_count_by_entity.yaml b/test/cases/measure/data/input/group_count_by_entity.yaml
index c81bc3177..3e11b5e4c 100644
--- a/test/cases/measure/data/input/group_count_by_entity.yaml
+++ b/test/cases/measure/data/input/group_count_by_entity.yaml
@@ -17,6 +17,10 @@
name: "time_bucket_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["entity_id"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_composite_entity.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_composite_entity.ql
index 977942dfd..0d52b9237 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_composite_entity.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT tag_b, COUNT(tag_a) FROM MEASURE composite_entity_metric IN sw_metric
+TIME > '-15m'
+GROUP BY tag_b
diff --git a/test/cases/measure/data/input/group_count_composite_entity.yaml b/test/cases/measure/data/input/group_count_composite_entity.yaml
index d2825eaa3..3f40918c6 100644
--- a/test/cases/measure/data/input/group_count_composite_entity.yaml
+++ b/test/cases/measure/data/input/group_count_composite_entity.yaml
@@ -17,6 +17,10 @@
name: "composite_entity_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["tag_b"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_by_entity.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_by_entity.ql
index 977942dfd..53d4269e2 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_by_entity.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT entity_id, COUNT(DISTINCT id) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY entity_id
diff --git a/test/cases/measure/data/input/group_count_distinct_by_entity.yaml b/test/cases/measure/data/input/group_count_distinct_by_entity.yaml
index 9c30022ca..3e1180999 100644
--- a/test/cases/measure/data/input/group_count_distinct_by_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_by_entity.yaml
@@ -17,6 +17,10 @@
name: "time_bucket_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["entity_id"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_composite_entity.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_composite_entity.ql
index 977942dfd..d06795017 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_composite_entity.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT tag_b, COUNT(DISTINCT tag_a) FROM MEASURE composite_entity_metric IN sw_metric
+TIME > '-15m'
+GROUP BY tag_b
diff --git a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml b/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
index ee0efaf03..60f265153 100644
--- a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
@@ -17,6 +17,10 @@
name: "composite_entity_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["tag_b"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_index_mode.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_index_mode.ql
index 977942dfd..d3925ec06 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_index_mode.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT tag_x, COUNT(DISTINCT entity_id) FROM MEASURE index_mode_distinct_metric IN sw_metric
+TIME > '-15m'
+GROUP BY tag_x
diff --git a/test/cases/measure/data/input/group_count_distinct_index_mode.yaml b/test/cases/measure/data/input/group_count_distinct_index_mode.yaml
index 0c1344da9..bb7ca5320 100644
--- a/test/cases/measure/data/input/group_count_distinct_index_mode.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_index_mode.yaml
@@ -17,6 +17,10 @@
name: "index_mode_distinct_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["tag_x"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_off_cadence.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_off_cadence.ql
index 977942dfd..3e33c2430 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_off_cadence.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT COUNT(DISTINCT entity_id) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m')
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_time_bucket.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_time_bucket.ql
index 977942dfd..c759bb2d6 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT user_id, COUNT(DISTINCT api_key) FROM MEASURE cardinality_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m'), user_id
diff --git a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml b/test/cases/measure/data/input/group_count_distinct_time_bucket.yaml
similarity index 84%
copy from test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
copy to test/cases/measure/data/input/group_count_distinct_time_bucket.yaml
index ee0efaf03..a7133a34a 100644
--- a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket.yaml
@@ -15,14 +15,20 @@
# specific language governing permissions and limitations
# under the License.
-name: "composite_entity_metric"
+name: "cardinality_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["user_id"]
groupBy:
tagProjection:
tagFamilies:
- name: "default"
- tags: ["tag_b"]
+ tags: ["user_id"]
+ timeBucket:
+ width: "1m"
agg:
function: "AGGREGATION_FUNCTION_COUNT_DISTINCT"
- tagName: "tag_a"
+ tagName: "api_key"
tagFamily: "default"
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_time_bucket_30s.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_time_bucket_30s.ql
index 977942dfd..08b694092 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket_30s.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT user_id, COUNT(DISTINCT api_key) FROM MEASURE cardinality_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('30s'), user_id
diff --git a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml b/test/cases/measure/data/input/group_count_distinct_time_bucket_30s.yaml
similarity index 84%
copy from test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
copy to test/cases/measure/data/input/group_count_distinct_time_bucket_30s.yaml
index ee0efaf03..6a6afa312 100644
--- a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket_30s.yaml
@@ -15,14 +15,20 @@
# specific language governing permissions and limitations
# under the License.
-name: "composite_entity_metric"
+name: "cardinality_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["user_id"]
groupBy:
tagProjection:
tagFamilies:
- name: "default"
- tags: ["tag_b"]
+ tags: ["user_id"]
+ timeBucket:
+ width: "30s"
agg:
function: "AGGREGATION_FUNCTION_COUNT_DISTINCT"
- tagName: "tag_a"
+ tagName: "api_key"
tagFamily: "default"
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.ql
index 977942dfd..24a0a2ad4 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT id, COUNT(DISTINCT entity_id) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m'), id
diff --git a/test/cases/measure/data/input/group_count_distinct_by_entity.yaml b/test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.yaml
similarity index 87%
copy from test/cases/measure/data/input/group_count_distinct_by_entity.yaml
copy to test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.yaml
index 9c30022ca..0899f51aa 100644
--- a/test/cases/measure/data/input/group_count_distinct_by_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_time_bucket_with_tag.yaml
@@ -17,12 +17,18 @@
name: "time_bucket_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["id"]
groupBy:
tagProjection:
tagFamilies:
- name: "default"
- tags: ["entity_id"]
+ tags: ["id"]
+ timeBucket:
+ width: "1m"
agg:
function: "AGGREGATION_FUNCTION_COUNT_DISTINCT"
- tagName: "id"
+ tagName: "entity_id"
tagFamily: "default"
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_distinct_top_by_user.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_distinct_top_by_user.ql
index 977942dfd..750595e55 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_distinct_top_by_user.ql
@@ -15,4 +15,9 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT TOP 2 api_key DESC, user_id, COUNT(DISTINCT api_key) FROM MEASURE cardinality_metric IN sw_metric
+TIME > '-15m'
+GROUP BY user_id
+LIMIT 1
+OFFSET 1
diff --git a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml b/test/cases/measure/data/input/group_count_distinct_top_by_user.yaml
similarity index 80%
copy from test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
copy to test/cases/measure/data/input/group_count_distinct_top_by_user.yaml
index ee0efaf03..0578fa906 100644
--- a/test/cases/measure/data/input/group_count_distinct_composite_entity.yaml
+++ b/test/cases/measure/data/input/group_count_distinct_top_by_user.yaml
@@ -15,14 +15,24 @@
# specific language governing permissions and limitations
# under the License.
-name: "composite_entity_metric"
+name: "cardinality_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["user_id"]
groupBy:
tagProjection:
tagFamilies:
- name: "default"
- tags: ["tag_b"]
+ tags: ["user_id"]
agg:
function: "AGGREGATION_FUNCTION_COUNT_DISTINCT"
- tagName: "tag_a"
+ tagName: "api_key"
tagFamily: "default"
+top:
+ number: 2
+ fieldName: "api_key"
+ fieldValueSort: "SORT_DESC"
+limit: 1
+offset: 1
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_index_mode.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_index_mode.ql
index 977942dfd..f5710697e 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_index_mode.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT tag_x, COUNT(entity_id) FROM MEASURE index_mode_distinct_metric IN sw_metric
+TIME > '-15m'
+GROUP BY tag_x
diff --git a/test/cases/measure/data/input/group_count_index_mode.yaml b/test/cases/measure/data/input/group_count_index_mode.yaml
index 729c5e01f..ebc809031 100644
--- a/test/cases/measure/data/input/group_count_index_mode.yaml
+++ b/test/cases/measure/data/input/group_count_index_mode.yaml
@@ -17,6 +17,10 @@
name: "index_mode_distinct_metric"
groups: ["sw_metric"]
+tagProjection:
+ tagFamilies:
+ - name: "default"
+ tags: ["tag_x"]
groupBy:
tagProjection:
tagFamilies:
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_count_off_cadence.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_count_off_cadence.ql
index 977942dfd..df3a58aa8 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_count_off_cadence.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT COUNT(entity_id) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m')
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_time_bucket.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_time_bucket.ql
index 977942dfd..9e68e114a 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_time_bucket.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT value::field, SUM(value) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m')
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/input/group_time_bucket_with_tag.ql
similarity index 83%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/input/group_time_bucket_with_tag.ql
index 977942dfd..1fd270b37 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/input/group_time_bucket_with_tag.ql
@@ -15,4 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+
+SELECT id, value::field, SUM(value) FROM MEASURE time_bucket_metric IN sw_metric
+TIME > '-15m'
+GROUP BY TIME_BUCKET('1m'), id
diff --git a/test/cases/measure/data/testdata/cardinality_metric_u1_b0_data.json b/test/cases/measure/data/testdata/cardinality_metric_u1_b0_data.json
new file mode 100644
index 000000000..05b544ee2
--- /dev/null
+++ b/test/cases/measure/data/testdata/cardinality_metric_u1_b0_data.json
@@ -0,0 +1,35 @@
+[
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyA" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 1 } } ]
+ },
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyA" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 2 } } ]
+ },
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyB" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 3 } } ]
+ }
+]
diff --git a/test/cases/measure/data/testdata/cardinality_metric_u1_b2_data.json b/test/cases/measure/data/testdata/cardinality_metric_u1_b2_data.json
new file mode 100644
index 000000000..fb819cabd
--- /dev/null
+++ b/test/cases/measure/data/testdata/cardinality_metric_u1_b2_data.json
@@ -0,0 +1,35 @@
+[
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyB" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 6 } } ]
+ },
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyB" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 7 } } ]
+ },
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user1" } },
+ { "str": { "value": "keyC" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 8 } } ]
+ }
+]
diff --git a/test/cases/measure/data/testdata/cardinality_metric_u2_b1_data.json b/test/cases/measure/data/testdata/cardinality_metric_u2_b1_data.json
new file mode 100644
index 000000000..958d707d3
--- /dev/null
+++ b/test/cases/measure/data/testdata/cardinality_metric_u2_b1_data.json
@@ -0,0 +1,24 @@
+[
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user2" } },
+ { "str": { "value": "keyX" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 4 } } ]
+ },
+ {
+ "tag_families": [
+ {
+ "tags": [
+ { "str": { "value": "user2" } },
+ { "str": { "value": "keyY" } }
+ ]
+ }
+ ],
+ "fields": [ { "int": { "value": 5 } } ]
+ }
+]
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/want/group_count_distinct_time_bucket.yaml
similarity index 59%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/want/group_count_distinct_time_bucket.yaml
index 977942dfd..a3ebef546 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/want/group_count_distinct_time_bucket.yaml
@@ -15,4 +15,40 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+dataPoints:
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user2
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
diff --git a/test/cases/measure/data/want/group_count_distinct_time_bucket_30s.yaml b/test/cases/measure/data/want/group_count_distinct_time_bucket_30s.yaml
new file mode 100644
index 000000000..8cd6e2d48
--- /dev/null
+++ b/test/cases/measure/data/want/group_count_distinct_time_bucket_30s.yaml
@@ -0,0 +1,78 @@
+# Licensed to Apache Software Foundation (ASF) under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Apache Software Foundation (ASF) licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+dataPoints:
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user2
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user1
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/want/group_count_distinct_time_bucket_with_tag.yaml
similarity index 52%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/want/group_count_distinct_time_bucket_with_tag.yaml
index 977942dfd..0c1684161 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/want/group_count_distinct_time_bucket_with_tag.yaml
@@ -15,4 +15,52 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+dataPoints:
+- fields:
+ - name: entity_id
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: id
+ value:
+ str:
+ value: svcA
+- fields:
+ - name: entity_id
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: id
+ value:
+ str:
+ value: svcA
+- fields:
+ - name: entity_id
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: id
+ value:
+ str:
+ value: svcB
+- fields:
+ - name: entity_id
+ value:
+ int:
+ value: "1"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: id
+ value:
+ str:
+ value: svcB
diff --git a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql b/test/cases/measure/data/want/group_count_distinct_top_by_user.yaml
similarity index 80%
copy from test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
copy to test/cases/measure/data/want/group_count_distinct_top_by_user.yaml
index 977942dfd..34bbbdeed 100644
--- a/test/cases/measure/data/input/gen_feat_count_distinct_group_order_desc_10.ql
+++ b/test/cases/measure/data/want/group_count_distinct_top_by_user.yaml
@@ -15,4 +15,16 @@
# specific language governing permissions and limitations
# under the License.
-SELECT id, entity_id, SUM(), total::field, value::field FROM MEASURE service_cpm_minute IN sw_metric TIME > '-15m' GROUP BY id, value::field ORDER BY DESC
+dataPoints:
+- fields:
+ - name: api_key
+ value:
+ int:
+ value: "2"
+ tagFamilies:
+ - name: default
+ tags:
+ - key: user_id
+ value:
+ str:
+ value: user2
diff --git a/test/cases/measure/measure.go b/test/cases/measure/measure.go
index 4e0afa197..d7fa3329d 100644
--- a/test/cases/measure/measure.go
+++ b/test/cases/measure/measure.go
@@ -116,10 +116,17 @@ var measureEntries = []any{
// time_bucket_metric is seeded at now-100s..now (20s apart); a 1-minute
// bucket deterministically splits them 2/3/1 across three buckets
// regardless of which wall-clock minute `now` lands on (see
- // test/cases/init.go). SkipQL: BydbQL has no TIME_BUCKET(...) grammar
- // yet — apache/skywalking#14091.
- g.Entry("group by time bucket", helpers.Args{Input: "group_time_bucket", Duration: 4 * time.Minute, Offset: -3 * time.Minute, SkipQL: true}),
- g.Entry("group by time bucket and tag", helpers.Args{Input: "group_time_bucket_with_tag", Duration: 4 * time.Minute, Offset: -3 * time.Minute, SkipQL: true}),
+ // test/cases/init.go).
+ g.Entry("group by time bucket", helpers.Args{Input: "group_time_bucket", Duration: 4 * time.Minute, Offset: -3 * time.Minute}),
+ g.Entry("group by time bucket and tag", helpers.Args{Input: "group_time_bucket_with_tag", Duration: 4 * time.Minute, Offset: -3 * time.Minute}),
+ // The three-way shape: TIME_BUCKET + a GroupBy tag that is NOT the
+ // routing key (id), with COUNT_DISTINCT targeting the routing key
+ // (entity_id) instead. validateCountDistinctPushdown never inspects
+ // GroupBy.time_bucket, so the target-covers-the-routing-key branch is
+ // what legalizes this -- the bucket is orthogonal. Same 4 groups as
+ // group_time_bucket_with_tag above, counted distinctly rather than summed.
+ g.Entry("group by time bucket and a non-routing tag, count distinct the entity tag",
+ helpers.Args{Input: "group_count_distinct_time_bucket_with_tag", Duration: 4 * time.Minute, Offset: -3 * time.Minute}),
// The off-cadence disagreement fixture (design §11): two points for the
// same entity, 34s apart, both inside the single 1-minute bucket
// [now+1m, now+2m) (see test/cases/init.go — offset a full minute past
@@ -127,41 +134,56 @@ var measureEntries = []any{
// `now` doesn't leak into this window). COUNT_DISTINCT(entity_id) must
// report 1 (one distinct entity) while COUNT(entity_id) reports 2 (two
// rows) — the exact case a "one row per (entity, bucket)" assumption
- // would get wrong. SkipQL: BydbQL has no DISTINCT grammar or tag-Agg
- // fallback yet — apache/skywalking#14091.
+ // would get wrong.
g.Entry("group by time bucket, count distinct off-cadence",
- helpers.Args{Input: "group_count_distinct_off_cadence", Duration: time.Minute, Offset: time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_distinct_off_cadence", Duration: time.Minute, Offset: time.Minute}),
g.Entry("group by time bucket, count off-cadence",
- helpers.Args{Input: "group_count_off_cadence", Duration: time.Minute, Offset: time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_off_cadence", Duration: time.Minute, Offset: time.Minute}),
// GROUP BY entity_id (the routing key), COUNT_DISTINCT over an unrelated
// normal tag -- decomposable via §7.4's "GroupBy covers the routing key"
// branch, not "target covers the routing key" (see test/cases/init.go).
- // SkipQL: BydbQL has no DISTINCT grammar or tag-Agg fallback yet --
- // apache/skywalking#14091.
g.Entry("group by entity, count distinct a normal tag",
- helpers.Args{Input: "group_count_distinct_by_entity", Duration: time.Minute, Offset: 2 * time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_distinct_by_entity", Duration: time.Minute, Offset: 2 * time.Minute}),
g.Entry("group by entity, count a normal tag",
- helpers.Args{Input: "group_count_by_entity", Duration: time.Minute, Offset: 2 * time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_by_entity", Duration: time.Minute, Offset: 2 * time.Minute}),
// composite_entity_metric's entity is [tag_b, tag_a]. GROUP BY tag_b,
// COUNT_DISTINCT(tag_a): tag_b is covered because it's a GroupBy key,
// tag_a is covered because it's the Agg target -- the two entity
// components covered by *different* branches of §7.4's per-routing-tag
- // check simultaneously (see test/cases/init.go). SkipQL: BydbQL has no
- // DISTINCT grammar or tag-Agg fallback yet -- apache/skywalking#14091.
+ // check simultaneously (see test/cases/init.go).
g.Entry("group by one entity tag, count distinct the other entity tag",
- helpers.Args{Input: "group_count_distinct_composite_entity", Duration: 2 * time.Minute, Offset: -time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_distinct_composite_entity", Duration: 2 * time.Minute, Offset: -time.Minute}),
g.Entry("group by one entity tag, count the other entity tag",
- helpers.Args{Input: "group_count_composite_entity", Duration: 2 * time.Minute, Offset: -time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_composite_entity", Duration: 2 * time.Minute, Offset: -time.Minute}),
// index_mode_distinct_metric carries a real IndexRule on tag_x (a
// non-entity tag) and is itself index_mode=true. GROUP BY the indexed
// tag_x, COUNT_DISTINCT(entity_id): the target covers the routing key on
// its own, so an indexed-but-unrelated GroupBy tag must not block
- // acceptance (see test/cases/init.go). SkipQL: BydbQL has no DISTINCT
- // grammar or tag-Agg fallback yet -- apache/skywalking#14091.
+ // acceptance (see test/cases/init.go).
g.Entry("group by an indexed tag, count distinct the entity tag",
- helpers.Args{Input: "group_count_distinct_index_mode", Duration: 2 * time.Minute, Offset: -time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_distinct_index_mode", Duration: 2 * time.Minute, Offset: -time.Minute}),
g.Entry("group by an indexed tag, count the entity tag",
- helpers.Args{Input: "group_count_index_mode", Duration: 2 * time.Minute, Offset: -time.Minute, SkipQL: true}),
+ helpers.Args{Input: "group_count_index_mode", Duration: 2 * time.Minute, Offset: -time.Minute}),
+ // cardinality_metric's entity is [user_id]; GROUP BY TIME_BUCKET('1m'),
+ // user_id combines the time-bucket and tag-group branches of §7.4's
+ // per-routing-tag pushdown check at once (design §7.2+§11 together).
+ // See test/cases/init.go's cardinalityBase comment for the exact
+ // per-bucket layout.
+ g.Entry("group by time bucket, count distinct api key",
+ helpers.Args{Input: "group_count_distinct_time_bucket", Duration: 3 * time.Minute, Offset: 5 * time.Minute}),
+ // Same query, narrower bucket width -- proves the width is actually
+ // read (5 rows spanning finer-grained buckets, some now empty), not
+ // silently ignored.
+ g.Entry("group by a narrower time bucket, count distinct api key",
+ helpers.Args{Input: "group_count_distinct_time_bucket_30s", Duration: 3 * time.Minute, Offset: 5 * time.Minute}),
+ // GROUP BY user_id (no time bucket), TOP 2 ranked by the COUNT_DISTINCT
+ // tag-Agg's own output column (api_key) DESC, then LIMIT/OFFSET paginate
+ // beneath TOP's truncation: user1 (3 distinct keys) ranks above user2
+ // (2), and OFFSET 1/LIMIT 1 skips user1 to return user2 alone --
+ // exercises convertTOP's widened tag-output resolution together with
+ // pagination.
+ g.Entry("top by count distinct api key, paged",
+ helpers.Args{Input: "group_count_distinct_top_by_user", Duration: 3 * time.Minute, Offset: 5 * time.Minute}),
g.Entry("top N with filter", helpers.Args{Input: "top_with_filter", Duration: 25 * time.Minute, Offset: -20 * time.Minute}),
g.Entry("index mode filter by NE", helpers.Args{Input: "index_mode_ne", Duration: 25 * time.Minute, Offset: -20 * time.Minute, DisOrder: true}),
g.Entry("index mode filter by LE on int", helpers.Args{Input: "index_mode_le", Duration: 25 * time.Minute, Offset: -20 * time.Minute, DisOrder: true}),
@@ -236,15 +258,13 @@ var measureEntries = []any{
helpers.Args{Input: "gen_feat_sum_group_order_desc_9", Want: "gen_feat_sum_group_order_desc_9", Duration: 25 * time.Minute, Offset: -20 * time.Minute}),
// COUNT_DISTINCT closes the design's own flagged gap (§11): the layer-3
// pairwise generator hard-coded {MEAN,MAX,MIN,COUNT,SUM} and would have
- // silently under-covered the sixth function. SkipQL: RenderQL has no
- // COUNT_DISTINCT/tag-Agg support yet, so the generated .ql would be
- // wrong (it renders a bogus SUM() call) -- deleted rather than shipped;
- // same BydbQL gap as every other COUNT_DISTINCT fixture here --
- // apache/skywalking#14091.
+ // silently under-covered the sixth function. BydbQL now supports
+ // COUNT_DISTINCT/tag-Agg (apache/skywalking#14091), so RenderQL's
+ // generated .ql renders correctly and this case verifies end to end.
g.Entry("gen: count distinct group order desc",
helpers.Args{
Input: "gen_feat_count_distinct_group_order_desc_10", Want: "gen_feat_count_distinct_group_order_desc_10",
- Duration: 25 * time.Minute, Offset: -20 * time.Minute, SkipQL: true,
+ Duration: 25 * time.Minute, Offset: -20 * time.Minute,
}),
}