SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(trace-details): Add API endpoint & module for trace aggregations (#11452)
Nikhil Soni5e94f7ac6e15
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex aaa9c13d6f..6f7fc074a8 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -6525,6 +6525,15 @@ components:required:- itemstype: object+ SpantypesGettableTraceAggregations:+ properties:+ aggregations:+ items:+ $ref: '#/components/schemas/SpantypesSpanAggregationResult'+ type: array+ required:+ - aggregations+ type: objectSpantypesGettableWaterfallTrace:properties:aggregations:@@ -6590,6 +6599,15 @@ components:- name- conditiontype: object+ SpantypesPostableTraceAggregations:+ properties:+ aggregations:+ items:+ $ref: '#/components/schemas/SpantypesSpanAggregation'+ type: array+ required:+ - aggregations+ type: objectSpantypesPostableWaterfall:properties:aggregations:@@ -6614,6 +6632,9 @@ components:$ref: '#/components/schemas/SpantypesSpanAggregationType'field:$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'+ required:+ - field+ - aggregationtype: objectSpantypesSpanAggregationResult:properties:@@ -6627,6 +6648,10 @@ components:type: integernullable: truetype: object+ required:+ - field+ - aggregation+ - valuetype: objectSpantypesSpanAggregationType:enum:@@ -12265,6 +12290,75 @@ paths:summary: Test notification channel (deprecated)tags:- channels+ /api/v1/traces/{traceID}/aggregations:+ post:+ deprecated: false+ description: Computes span aggregations grouped by requested field.+ operationId: GetTraceAggregations+ parameters:+ - in: path+ name: traceID+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SpantypesPostableTraceAggregations'+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/SpantypesGettableTraceAggregations'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "404":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Not Found+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - VIEWER+ - tokenizer:+ - VIEWER+ summary: Get aggregations for a trace+ tags:+ - tracedetail/api/v1/user:get:deprecated: falsediff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex d89034f629..f8a8d49063 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -7753,12 +7753,19 @@ export type SpantypesSpanAggregationResultDTOValue =SpantypesSpanAggregationResultDTOValueAnyOf | null;export interface SpantypesSpanAggregationResultDTO {- aggregation?: SpantypesSpanAggregationTypeDTO;- field?: TelemetrytypesTelemetryFieldKeyDTO;+ aggregation: SpantypesSpanAggregationTypeDTO;+ field: TelemetrytypesTelemetryFieldKeyDTO;/*** @type object,null*/- value?: SpantypesSpanAggregationResultDTOValue;+ value: SpantypesSpanAggregationResultDTOValue;+}++export interface SpantypesGettableTraceAggregationsDTO {+ /**+ * @type array+ */+ aggregations: SpantypesSpanAggregationResultDTO[];}export type SpantypesWaterfallSpanDTOAttributesAnyOf = {@@ -8000,8 +8007,15 @@ export interface SpantypesPostableSpanMapperGroupDTO {}export interface SpantypesSpanAggregationDTO {- aggregation?: SpantypesSpanAggregationTypeDTO;- field?: TelemetrytypesTelemetryFieldKeyDTO;+ aggregation: SpantypesSpanAggregationTypeDTO;+ field: TelemetrytypesTelemetryFieldKeyDTO;+}++export interface SpantypesPostableTraceAggregationsDTO {+ /**+ * @type array+ */+ aggregations: SpantypesSpanAggregationDTO[];}export interface SpantypesPostableWaterfallDTO {@@ -9344,6 +9358,17 @@ export type UpdateSpanMapperPathParameters = {groupId: string;mapperId: string;};+export type GetTraceAggregationsPathParameters = {+ traceID: string;+};+export type GetTraceAggregations200 = {+ data: SpantypesGettableTraceAggregationsDTO;+ /**+ * @type string+ */+ status: string;+};+export type ListUsersDeprecated200 = {/*** @type arraydiff --git a/frontend/src/api/generated/services/tracedetail/index.ts b/frontend/src/api/generated/services/tracedetail/index.tsindex 2bad04de15..79c1c107e5 100644--- a/frontend/src/api/generated/services/tracedetail/index.ts+++ b/frontend/src/api/generated/services/tracedetail/index.ts@@ -12,17 +12,120 @@ import type {} from 'react-query';import type {+ GetTraceAggregations200,+ GetTraceAggregationsPathParameters,GetWaterfall200,GetWaterfallPathParameters,GetWaterfallV4200,GetWaterfallV4PathParameters,RenderErrorResponseDTO,+ SpantypesPostableTraceAggregationsDTO,SpantypesPostableWaterfallDTO,} from '../sigNoz.schemas';import { GeneratedAPIInstance } from '../../../generatedAPIInstance';import type { ErrorType, BodyType } from '../../../generatedAPIInstance';+/**+ * Computes span aggregations grouped by requested field.+ * @summary Get aggregations for a trace+ */+export const getTraceAggregations = (+ { traceID }: GetTraceAggregationsPathParameters,+ spantypesPostableTraceAggregationsDTO?: BodyType<SpantypesPostableTraceAggregationsDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetTraceAggregations200>({+ url: `/api/v1/traces/${traceID}/aggregations`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: spantypesPostableTraceAggregationsDTO,+ signal,+ });+};++export const getGetTraceAggregationsMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof getTraceAggregations>>,+ TError,+ {+ pathParams: GetTraceAggregationsPathParameters;+ data?: BodyType<SpantypesPostableTraceAggregationsDTO>;+ },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof getTraceAggregations>>,+ TError,+ {+ pathParams: GetTraceAggregationsPathParameters;+ data?: BodyType<SpantypesPostableTraceAggregationsDTO>;+ },+ TContext+> => {+ const mutationKey = ['getTraceAggregations'];+ const { mutation: mutationOptions } = options+ ? options.mutation &&+ 'mutationKey' in options.mutation &&+ options.mutation.mutationKey+ ? options+ : { ...options, mutation: { ...options.mutation, mutationKey } }+ : { mutation: { mutationKey } };++ const mutationFn: MutationFunction<+ Awaited<ReturnType<typeof getTraceAggregations>>,+ {+ pathParams: GetTraceAggregationsPathParameters;+ data?: BodyType<SpantypesPostableTraceAggregationsDTO>;+ }+ > = (props) => {+ const { pathParams, data } = props ?? {};++ return getTraceAggregations(pathParams, data);+ };++ return { mutationFn, ...mutationOptions };+};++export type GetTraceAggregationsMutationResult = NonNullable<+ Awaited<ReturnType<typeof getTraceAggregations>>+>;+export type GetTraceAggregationsMutationBody =+ | BodyType<SpantypesPostableTraceAggregationsDTO>+ | undefined;+export type GetTraceAggregationsMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get aggregations for a trace+ */+export const useGetTraceAggregations = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof getTraceAggregations>>,+ TError,+ {+ pathParams: GetTraceAggregationsPathParameters;+ data?: BodyType<SpantypesPostableTraceAggregationsDTO>;+ },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof getTraceAggregations>>,+ TError,+ {+ pathParams: GetTraceAggregationsPathParameters;+ data?: BodyType<SpantypesPostableTraceAggregationsDTO>;+ },+ TContext+> => {+ return useMutation(getGetTraceAggregationsMutationOptions(options));+};/*** Returns the waterfall view of spans for a given trace ID with tree structure, metadata, and windowed pagination* @summary Get waterfall view for a tracediff --git a/pkg/apiserver/signozapiserver/tracedetail.go b/pkg/apiserver/signozapiserver/tracedetail.goindex 3f3dad7f99..b5facb5a54 100644--- a/pkg/apiserver/signozapiserver/tracedetail.go+++ b/pkg/apiserver/signozapiserver/tracedetail.go@@ -48,5 +48,24 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {return err}+ if err := router.Handle("/api/v1/traces/{traceID}/aggregations", handler.New(+ provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetTraceAggregations),+ handler.OpenAPIDef{+ ID: "GetTraceAggregations",+ Tags: []string{"tracedetail"},+ Summary: "Get aggregations for a trace",+ Description: "Computes span aggregations grouped by requested field.",+ Request: new(spantypes.PostableTraceAggregations),+ RequestContentType: "application/json",+ Response: new(spantypes.GettableTraceAggregations),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),+ },+ )).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }+return nil}diff --git a/pkg/modules/tracedetail/impltracedetail/handler.go b/pkg/modules/tracedetail/impltracedetail/handler.goindex 788de6e0a4..c01cfde9b4 100644--- a/pkg/modules/tracedetail/impltracedetail/handler.go+++ b/pkg/modules/tracedetail/impltracedetail/handler.go@@ -59,3 +59,24 @@ func (h *handler) GetWaterfallV4(rw http.ResponseWriter, r *http.Request) {render.Success(rw, http.StatusOK, result)}++func (h *handler) GetTraceAggregations(rw http.ResponseWriter, r *http.Request) {+ req := new(spantypes.PostableTraceAggregations)+ if err := binding.JSON.BindBody(r.Body, req); err != nil {+ render.Error(rw, err)+ return+ }++ if err := req.Validate(); err != nil {+ render.Error(rw, err)+ return+ }++ result, err := h.module.GetTraceAggregations(r.Context(), mux.Vars(r)["traceID"], req)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, result)+}diff --git a/pkg/modules/tracedetail/impltracedetail/module.go b/pkg/modules/tracedetail/impltracedetail/module.goindex 87c57ceca3..435e170939 100644--- a/pkg/modules/tracedetail/impltracedetail/module.go+++ b/pkg/modules/tracedetail/impltracedetail/module.go@@ -105,6 +105,49 @@ func (m *module) getFullWaterfall(ctx context.Context, traceID string, summary *return spantypes.NewGettableWaterfallTrace(waterfallTrace, selectedSpans, nil, true, nil), nil}+func (m *module) GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error) {+ summary, err := m.store.GetTraceSummary(ctx, traceID)+ if err != nil {+ return nil, err+ }++ traceDurationNs := uint64(summary.End.UnixNano()) - uint64(summary.Start.UnixNano())++ results := make([]spantypes.SpanAggregationResult, 0, len(req.Aggregations))+ for _, agg := range req.Aggregations {+ result := spantypes.SpanAggregationResult{Field: agg.Field, Aggregation: agg.Aggregation}+ switch agg.Aggregation {+ case spantypes.SpanAggregationSpanCount:+ result.Value, err = m.store.GetSpanCountByField(ctx, traceID, summary, agg.Field)+ if err != nil {+ return nil, err+ }+ case spantypes.SpanAggregationDuration:+ durationNs, err2 := m.store.GetSpanDurationByField(ctx, traceID, summary, agg.Field)+ if err2 != nil {+ return nil, err2+ }+ result.Value = make(map[string]uint64, len(durationNs))+ for k, ns := range durationNs {+ result.Value[k] = ns / 1_000_000+ }+ case spantypes.SpanAggregationExecutionTimePercentage:+ durationNs, err2 := m.store.GetSpanDurationByField(ctx, traceID, summary, agg.Field)+ if err2 != nil {+ return nil, err2+ }+ result.Value = make(map[string]uint64, len(durationNs))+ if traceDurationNs > 0 {+ for k, ns := range durationNs {+ result.Value[k] = ns * 100 / traceDurationNs+ }+ }+ }+ results = append(results, result)+ }+ return &spantypes.GettableTraceAggregations{Aggregations: results}, nil+}+// getWindowedWaterfall builds the waterfall tree with minimal data and then returns only a window of full spans.func (m *module) getWindowedWaterfall(ctx context.Context, traceID, selectedSpanID string, uncollapsedSpans []string, start, end time.Time) (*spantypes.GettableWaterfallTrace, error) {// Step 1: minimal fetch → build full tree → select visible windowdiff --git a/pkg/modules/tracedetail/impltracedetail/store.go b/pkg/modules/tracedetail/impltracedetail/store.goindex de95644c2a..0470f684e7 100644--- a/pkg/modules/tracedetail/impltracedetail/store.go+++ b/pkg/modules/tracedetail/impltracedetail/store.go@@ -11,10 +11,30 @@ import ("github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/telemetrystore""github.com/SigNoz/signoz/pkg/types/spantypes"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes")const colServiceName = `resource_string_service$$$$name` // $ gets escaped so $$$$ converts to $$.+func buildFieldExpr(fieldKey telemetrytypes.TelemetryFieldKey) (string, error) {+ switch fieldKey.FieldContext {+ case telemetrytypes.FieldContextResource:+ // String cast required — Variant/Dynamic is rejected by GROUP BY.+ return fmt.Sprintf("resource.`%s`::String", fieldKey.Name), nil+ }+ return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "unsupported field context: %v", fieldKey.FieldContext)+}++type spanCountRow struct {+ FieldValue string `ch:"field_value"`+ Count uint64 `ch:"count"`+}++type spanDurationRow struct {+ FieldValue string `ch:"field_value"`+ TotalNs uint64 `ch:"total_ns"`+}+type traceStore struct {telemetryStore telemetrystore.TelemetryStore}@@ -133,3 +153,85 @@ func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, sta}return spans, nil}++func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, summary *spantypes.TraceSummary, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {+ fieldExpr, err := buildFieldExpr(fieldKey)+ if err != nil {+ return nil, err+ }+ sb := sqlbuilder.NewSelectBuilder()+ sb.Select(fieldExpr+" AS field_value", "count(DISTINCT span_id) AS count")+ sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))+ sb.Where(+ sb.E("trace_id", traceID),+ sb.GE("ts_bucket_start", summary.Start.Unix()-1800),+ sb.LE("ts_bucket_start", summary.End.Unix()),+ "notEmpty("+fieldExpr+")",+ )+ sb.GroupBy("field_value")+ query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)++ var rows []spanCountRow+ if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying span count by field")+ }+ result := make(map[string]uint64, len(rows))+ for _, r := range rows {+ result[r.FieldValue] = r.Count+ }+ return result, nil+}++func (s *traceStore) GetSpanDurationByField(ctx context.Context, traceID string, summary *spantypes.TraceSummary, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {+ fieldExpr, err := buildFieldExpr(fieldKey)+ if err != nil {+ return nil, err+ }++ // CTE 1: all span with start and end timestamps.+ allSpansSB := sqlbuilder.NewSelectBuilder()+ allSpansSB.Select(+ "DISTINCT ON (span_id) "+fieldExpr+" AS field_value",+ "toUnixTimestamp64Nano(timestamp) AS start_ns",+ "start_ns + duration_nano AS end_ns",+ )+ allSpansSB.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))+ allSpansSB.Where(+ allSpansSB.E("trace_id", traceID),+ allSpansSB.GE("ts_bucket_start", summary.Start.Unix()-1800),+ allSpansSB.LE("ts_bucket_start", summary.End.Unix()),+ "notEmpty(field_value)",+ )+ allSpansSB.OrderByAsc("timestamp")+ allSpansSB.OrderByAsc("name")++ // CTE 2: find max end time of all preceding spans.+ effectiveStartSB := sqlbuilder.NewSelectBuilder()+ effectiveStartSB.Select(+ "field_value", "end_ns",+ "greatest(start_ns, ifNull(max(end_ns) OVER (PARTITION BY field_value ORDER BY start_ns ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), toUInt64(0))) AS effective_start_ns",+ )+ effectiveStartSB.From("all_spans")++ // Final SELECT: each span contributes only the tail past its effective start.+ sb := sqlbuilder.With(+ sqlbuilder.CTEQuery("all_spans").As(allSpansSB),+ sqlbuilder.CTEQuery("effective_start").As(effectiveStartSB),+ ).Select(+ "field_value",+ "sum(toUInt64(greatest(end_ns - effective_start_ns, 0))) AS total_ns",+ )+ sb.From("effective_start")+ sb.GroupBy("field_value")++ query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)+ var rows []spanDurationRow+ if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying span duration by field")+ }+ result := make(map[string]uint64, len(rows))+ for _, r := range rows {+ result[r.FieldValue] = r.TotalNs+ }+ return result, nil+}diff --git a/pkg/modules/tracedetail/impltracedetail/store_test.go b/pkg/modules/tracedetail/impltracedetail/store_test.gonew file mode 100644index 0000000000..a0f3ea4f0b--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/store_test.go@@ -0,0 +1,118 @@+package impltracedetail_test++import (+ "context"+ "regexp"+ "testing"+ "time"++ "github.com/DATA-DOG/go-sqlmock"+ cmock "github.com/SigNoz/clickhouse-go-mock"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail/impltracedetail"+ "github.com/SigNoz/signoz/pkg/telemetrystore"+ "github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"+ "github.com/SigNoz/signoz/pkg/types/spantypes"+ "github.com/SigNoz/signoz/pkg/types/spantypes/spantypestest"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/stretchr/testify/assert"+)++var (+ testTraceID = "trace-abc123"+ testStart = time.Unix(1000, 0).UTC()+ testEnd = time.Unix(2000, 0).UTC()+ testSummary = &spantypes.TraceSummary{+ TraceID: testTraceID,+ Start: testStart,+ End: testEnd,+ NumSpans: 10,+ }+ svcNameField = telemetrytypes.TelemetryFieldKey{+ Name: "service.name",+ FieldContext: telemetrytypes.FieldContextResource,+ }+ unsupportedField = telemetrytypes.TelemetryFieldKey{+ Name: "http.method",+ FieldContext: telemetrytypes.FieldContextSpan,+ }+)++func newTestStore(matcher sqlmock.QueryMatcher) *spantypestest.TraceStoreTest {+ ts := telemetrystoretest.New(telemetrystore.Config{}, matcher)+ return spantypestest.New(impltracedetail.NewTraceStore(ts), ts.Mock())+}++func TestGetTraceSummary(t *testing.T) {+ expectedSQL := "SELECT trace_id, min(start) AS start, max(end) AS end, sum(num_spans) AS num_spans FROM signoz_traces.distributed_trace_summary WHERE trace_id = ? GROUP BY trace_id"++ t.Run("ValidTraceID_GeneratesExpectedSQL", func(t *testing.T) {+ s := newTestStore(sqlmock.QueryMatcherRegexp)+ s.Mock().ExpectQueryRow(regexp.QuoteMeta(expectedSQL)).+ WillReturnRow(cmock.NewRow(nil, nil))+ _, _ = s.Store().GetTraceSummary(context.Background(), testTraceID)+ assert.NoError(t, s.Mock().ExpectationsWereMet())+ })+}++func TestGetMinimalSpans(t *testing.T) {+ expectedSQL := "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, resource_string_service$$name FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC"++ t.Run("ValidRange_GeneratesExpectedSQL", func(t *testing.T) {+ s := newTestStore(sqlmock.QueryMatcherRegexp)+ s.Mock().ExpectSelect(regexp.QuoteMeta(expectedSQL)).+ WillReturnRows(cmock.NewRows(nil, nil))+ _, _ = s.Store().GetMinimalSpans(context.Background(), testTraceID, testStart, testEnd)+ assert.NoError(t, s.Mock().ExpectationsWereMet())+ })+}++func TestGetSpanCountByField(t *testing.T) {+ expectedSQL := "SELECT resource.`service.name`::String AS field_value, count(DISTINCT span_id) AS count FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND notEmpty(resource.`service.name`::String) GROUP BY field_value"++ tests := []struct {+ name string+ field telemetrytypes.TelemetryFieldKey+ wantQuery bool+ }{+ {name: "ResourceField_GeneratesExpectedSQL", field: svcNameField, wantQuery: true},+ {name: "NonResourceField_NoSQLGenerated", field: unsupportedField},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ s := newTestStore(sqlmock.QueryMatcherRegexp)+ if tc.wantQuery {+ s.Mock().ExpectSelect(regexp.QuoteMeta(expectedSQL)).+ WillReturnRows(cmock.NewRows(nil, nil))+ }+ _, _ = s.Store().GetSpanCountByField(context.Background(), testTraceID, testSummary, tc.field)+ assert.NoError(t, s.Mock().ExpectationsWereMet())+ })+ }+}++func TestGetSpanDurationByField(t *testing.T) {++ expectedSQL := "WITH all_spans AS (SELECT DISTINCT ON (span_id) resource.`service.name`::String AS field_value, toUnixTimestamp64Nano(timestamp) AS start_ns, start_ns + duration_nano AS end_ns FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND notEmpty(field_value) ORDER BY timestamp ASC, name ASC), effective_start AS (SELECT field_value, end_ns, greatest(start_ns, ifNull(max(end_ns) OVER (PARTITION BY field_value ORDER BY start_ns ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), toUInt64(0))) AS effective_start_ns FROM all_spans) SELECT field_value, sum(toUInt64(greatest(end_ns - effective_start_ns, 0))) AS total_ns FROM effective_start GROUP BY field_value"++ tests := []struct {+ name string+ field telemetrytypes.TelemetryFieldKey+ wantQuery bool+ }{+ {name: "ResourceField_GeneratesExpectedSQL", field: svcNameField, wantQuery: true},+ {name: "NonResourceField_NoSQLGenerated", field: unsupportedField},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ s := newTestStore(sqlmock.QueryMatcherRegexp)+ if tc.wantQuery {+ s.Mock().ExpectSelect(regexp.QuoteMeta(expectedSQL)).+ WillReturnRows(cmock.NewRows(nil, nil))+ }+ _, _ = s.Store().GetSpanDurationByField(context.Background(), testTraceID, testSummary, tc.field)+ assert.NoError(t, s.Mock().ExpectationsWereMet())+ })+ }+}diff --git a/pkg/modules/tracedetail/tracedetail.go b/pkg/modules/tracedetail/tracedetail.goindex 0e729274f8..49efc6caec 100644--- a/pkg/modules/tracedetail/tracedetail.go+++ b/pkg/modules/tracedetail/tracedetail.go@@ -11,10 +11,12 @@ import (type Handler interface {GetWaterfall(http.ResponseWriter, *http.Request)GetWaterfallV4(http.ResponseWriter, *http.Request)+ GetTraceAggregations(http.ResponseWriter, *http.Request)}// Module defines the business logic for trace detail operations.type Module interface {GetWaterfall(ctx context.Context, traceID string, req *spantypes.PostableWaterfall) (*spantypes.GettableWaterfallTrace, error)GetWaterfallV4(ctx context.Context, traceID string, selectedSpanID string, uncollapsedSpans []string, selectAllLimit uint) (*spantypes.GettableWaterfallTrace, error)+ GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)}diff --git a/pkg/types/spantypes/aggregation.go b/pkg/types/spantypes/aggregation.goindex 5f980796eb..ff190b4d4c 100644--- a/pkg/types/spantypes/aggregation.go+++ b/pkg/types/spantypes/aggregation.go@@ -1,6 +1,7 @@package spantypesimport (+ "regexp""slices""github.com/SigNoz/signoz/pkg/errors"@@ -8,6 +9,8 @@ import ("github.com/SigNoz/signoz/pkg/valuer")+var validAggregationFieldName = regexp.MustCompile(`^[a-zA-Z0-9._\-]+$`)+const maxAggregationItems = 10var ErrTooManyAggregationItems = errors.NewInvalidInputf(errors.CodeInvalidInput, "aggregations request exceeds maximum of %d items", maxAggregationItems)@@ -25,16 +28,16 @@ var (// SpanAggregation is a single aggregation request item: which field to group by and how.type SpanAggregation struct {- Field telemetrytypes.TelemetryFieldKey `json:"field"`- Aggregation SpanAggregationType `json:"aggregation"`+ Field telemetrytypes.TelemetryFieldKey `json:"field" required:"true" nullable:"false"`+ Aggregation SpanAggregationType `json:"aggregation" required:"true" nullable:"false"`}// SpanAggregationResult is the computed result for one aggregation request item.// Duration values are in milliseconds.type SpanAggregationResult struct {- Field telemetrytypes.TelemetryFieldKey `json:"field"`- Aggregation SpanAggregationType `json:"aggregation"`- Value map[string]uint64 `json:"value" nullable:"true"`+ Field telemetrytypes.TelemetryFieldKey `json:"field" required:"true" nullable:"false"`+ Aggregation SpanAggregationType `json:"aggregation" required:"true" nullable:"false"`+ Value map[string]uint64 `json:"value" required:"true" nullable:"true"`}func (SpanAggregationType) Enum() []any {@@ -48,3 +51,35 @@ func (SpanAggregationType) Enum() []any {func (s SpanAggregationType) isValid() bool {return slices.ContainsFunc(s.Enum(), func(v any) bool { return v == s })}++// PostableTraceAggregations is the request body for the V4 aggregations endpoint.+type PostableTraceAggregations struct {+ Aggregations []SpanAggregation `json:"aggregations" required:"true" nullable:"false"`+}++func (p *PostableTraceAggregations) Validate() error {+ if len(p.Aggregations) == 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "aggregations is required and must not be empty")+ }+ if len(p.Aggregations) > maxAggregationItems {+ return ErrTooManyAggregationItems+ }+ for _, a := range p.Aggregations {+ if !a.Aggregation.isValid() {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown aggregation type: %q", a.Aggregation)+ }+ if a.Field.FieldContext != telemetrytypes.FieldContextResource {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "aggregation field context must be %q, got %q",+ telemetrytypes.FieldContextResource, a.Field.FieldContext)+ }+ if !validAggregationFieldName.MatchString(a.Field.Name) {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid field name: %q", a.Field.Name)+ }+ }+ return nil+}++// GettableTraceAggregations is the response for the V4 aggregations endpoint.+type GettableTraceAggregations struct {+ Aggregations []SpanAggregationResult `json:"aggregations" required:"true" nullable:"false"`+}diff --git a/pkg/types/spantypes/spantypestest/store.go b/pkg/types/spantypes/spantypestest/store.gonew file mode 100644index 0000000000..02e7ffb54a--- /dev/null+++ b/pkg/types/spantypes/spantypestest/store.go@@ -0,0 +1,22 @@+package spantypestest++import (+ cmock "github.com/SigNoz/clickhouse-go-mock"+ "github.com/SigNoz/signoz/pkg/types/spantypes"+)++// TraceStoreTest pairs a TraceStore with the ClickHouse mock.+type TraceStoreTest struct {+ store spantypes.TraceStore+ mock cmock.ClickConnMockCommon+}++func New(store spantypes.TraceStore, mock cmock.ClickConnMockCommon) *TraceStoreTest {+ return &TraceStoreTest{store: store, mock: mock}+}++// Store returns the TraceStore for calling methods under test.+func (t *TraceStoreTest) Store() spantypes.TraceStore { return t.store }++// Mock returns the ClickHouse mock for setting query expectations.+func (t *TraceStoreTest) Mock() cmock.ClickConnMockCommon { return t.mock }diff --git a/pkg/types/spantypes/store.go b/pkg/types/spantypes/store.goindex 7b03d9ecef..888ddb0259 100644--- a/pkg/types/spantypes/store.go+++ b/pkg/types/spantypes/store.go@@ -4,6 +4,7 @@ import ("context""time"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer")@@ -29,4 +30,7 @@ type TraceStore interface {GetTraceSpans(ctx context.Context, traceID string, summary *TraceSummary) ([]StorableSpan, error)GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]MinimalSpan, error)GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]StorableSpan, error)++ GetSpanCountByField(ctx context.Context, traceID string, summary *TraceSummary, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)+ GetSpanDurationByField(ctx context.Context, traceID string, summary *TraceSummary, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)}