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
refactor: move waterfall api to module structure with updated response (#10797)
Nikhil Soni156459e4145a
diff --git a/conf/example.yaml b/conf/example.yamlindex e01b8f8be3..c6e8ec99ab 100644--- a/conf/example.yaml+++ b/conf/example.yaml@@ -408,6 +408,16 @@ cloudintegration:# The version of the cloud integration agent.version: v0.0.8+##################### Trace Detail #####################+tracedetail:+ waterfall:+ # Number of spans returned per request when the trace is too large to show all at once.+ span_page_size: 500+ # Maximum depth of descendents to auto-expand for the selected span.+ max_depth_to_auto_expand: 5+ # Threshold below which all spans are returned without windowing.+ max_limit_to_select_all_spans: 10000+##################### Authz #################################authz:# Specifies the authz provider to use.diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 812cd6aa9d..d23bd98a6e 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -4581,6 +4581,140 @@ components:TimeDuration:format: int64type: integer+ TracedetailtypesEvent:+ properties:+ attributeMap:+ additionalProperties: {}+ type: object+ isError:+ type: boolean+ name:+ type: string+ timeUnixNano:+ minimum: 0+ type: integer+ type: object+ TracedetailtypesGettableWaterfallTrace:+ properties:+ endTimestampMillis:+ minimum: 0+ type: integer+ hasMissingSpans:+ type: boolean+ hasMore:+ type: boolean+ rootServiceEntryPoint:+ type: string+ rootServiceName:+ type: string+ serviceNameToTotalDurationMap:+ additionalProperties:+ minimum: 0+ type: integer+ nullable: true+ type: object+ spans:+ items:+ $ref: '#/components/schemas/TracedetailtypesWaterfallSpan'+ nullable: true+ type: array+ startTimestampMillis:+ minimum: 0+ type: integer+ totalErrorSpansCount:+ minimum: 0+ type: integer+ totalSpansCount:+ minimum: 0+ type: integer+ uncollapsedSpans:+ items:+ type: string+ nullable: true+ type: array+ type: object+ TracedetailtypesPostableWaterfall:+ properties:+ limit:+ minimum: 0+ type: integer+ selectedSpanId:+ type: string+ uncollapsedSpans:+ items:+ type: string+ nullable: true+ type: array+ type: object+ TracedetailtypesWaterfallSpan:+ properties:+ attributes:+ additionalProperties: {}+ nullable: true+ type: object+ db_name:+ type: string+ db_operation:+ type: string+ duration_nano:+ minimum: 0+ type: integer+ events:+ items:+ $ref: '#/components/schemas/TracedetailtypesEvent'+ nullable: true+ type: array+ external_http_method:+ type: string+ external_http_url:+ type: string+ flags:+ minimum: 0+ type: integer+ has_children:+ type: boolean+ has_error:+ type: boolean+ http_host:+ type: string+ http_method:+ type: string+ http_url:+ type: string+ is_remote:+ type: string+ kind_string:+ type: string+ level:+ minimum: 0+ type: integer+ name:+ type: string+ parent_span_id:+ type: string+ resource:+ additionalProperties:+ type: string+ nullable: true+ type: object+ response_status_code:+ type: string+ span_id:+ type: string+ status_code:+ type: integer+ status_code_string:+ type: string+ status_message:+ type: string+ sub_tree_node_count:+ minimum: 0+ type: integer+ trace_id:+ type: string+ trace_state:+ type: string+ type: objectTypesAlertStatus:properties:inhibitedBy:@@ -15995,6 +16129,76 @@ paths:summary: Put profile in Zeus for a deployment.tags:- zeus+ /api/v3/traces/{traceID}/waterfall:+ post:+ deprecated: false+ description: Returns the waterfall view of spans for a given trace ID with tree+ structure, metadata, and windowed pagination+ operationId: GetWaterfall+ parameters:+ - in: path+ name: traceID+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/TracedetailtypesPostableWaterfall'+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/TracedetailtypesGettableWaterfallTrace'+ 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 waterfall view for a trace+ tags:+ - tracedetail/api/v5/query_range:post:deprecated: falsediff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 69562e78e7..82e2abd76d 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -5559,6 +5559,237 @@ export interface TelemetrytypesTelemetryFieldValuesDTO {export type TimeDurationDTO = number;+export type TracedetailtypesEventDTOAttributeMap = { [key: string]: unknown };++export interface TracedetailtypesEventDTO {+ /**+ * @type object+ */+ attributeMap?: TracedetailtypesEventDTOAttributeMap;+ /**+ * @type boolean+ */+ isError?: boolean;+ /**+ * @type string+ */+ name?: string;+ /**+ * @type integer+ * @minimum 0+ */+ timeUnixNano?: number;+}++/**+ * @nullable+ */+export type TracedetailtypesGettableWaterfallTraceDTOServiceNameToTotalDurationMap =+ { [key: string]: number } | null;++export interface TracedetailtypesGettableWaterfallTraceDTO {+ /**+ * @type integer+ * @minimum 0+ */+ endTimestampMillis?: number;+ /**+ * @type boolean+ */+ hasMissingSpans?: boolean;+ /**+ * @type boolean+ */+ hasMore?: boolean;+ /**+ * @type string+ */+ rootServiceEntryPoint?: string;+ /**+ * @type string+ */+ rootServiceName?: string;+ /**+ * @type object+ * @nullable true+ */+ serviceNameToTotalDurationMap?: TracedetailtypesGettableWaterfallTraceDTOServiceNameToTotalDurationMap;+ /**+ * @type array+ * @nullable true+ */+ spans?: TracedetailtypesWaterfallSpanDTO[] | null;+ /**+ * @type integer+ * @minimum 0+ */+ startTimestampMillis?: number;+ /**+ * @type integer+ * @minimum 0+ */+ totalErrorSpansCount?: number;+ /**+ * @type integer+ * @minimum 0+ */+ totalSpansCount?: number;+ /**+ * @type array+ * @nullable true+ */+ uncollapsedSpans?: string[] | null;+}++export interface TracedetailtypesPostableWaterfallDTO {+ /**+ * @type integer+ * @minimum 0+ */+ limit?: number;+ /**+ * @type string+ */+ selectedSpanId?: string;+ /**+ * @type array+ * @nullable true+ */+ uncollapsedSpans?: string[] | null;+}++/**+ * @nullable+ */+export type TracedetailtypesWaterfallSpanDTOAttributes = {+ [key: string]: unknown;+} | null;++/**+ * @nullable+ */+export type TracedetailtypesWaterfallSpanDTOResource = {+ [key: string]: string;+} | null;++export interface TracedetailtypesWaterfallSpanDTO {+ /**+ * @type object+ * @nullable true+ */+ attributes?: TracedetailtypesWaterfallSpanDTOAttributes;+ /**+ * @type string+ */+ db_name?: string;+ /**+ * @type string+ */+ db_operation?: string;+ /**+ * @type integer+ * @minimum 0+ */+ duration_nano?: number;+ /**+ * @type array+ * @nullable true+ */+ events?: TracedetailtypesEventDTO[] | null;+ /**+ * @type string+ */+ external_http_method?: string;+ /**+ * @type string+ */+ external_http_url?: string;+ /**+ * @type integer+ * @minimum 0+ */+ flags?: number;+ /**+ * @type boolean+ */+ has_children?: boolean;+ /**+ * @type boolean+ */+ has_error?: boolean;+ /**+ * @type string+ */+ http_host?: string;+ /**+ * @type string+ */+ http_method?: string;+ /**+ * @type string+ */+ http_url?: string;+ /**+ * @type string+ */+ is_remote?: string;+ /**+ * @type string+ */+ kind_string?: string;+ /**+ * @type integer+ * @minimum 0+ */+ level?: number;+ /**+ * @type string+ */+ name?: string;+ /**+ * @type string+ */+ parent_span_id?: string;+ /**+ * @type object+ * @nullable true+ */+ resource?: TracedetailtypesWaterfallSpanDTOResource;+ /**+ * @type string+ */+ response_status_code?: string;+ /**+ * @type string+ */+ span_id?: string;+ /**+ * @type integer+ */+ status_code?: number;+ /**+ * @type string+ */+ status_code_string?: string;+ /**+ * @type string+ */+ status_message?: string;+ /**+ * @type integer+ * @minimum 0+ */+ sub_tree_node_count?: number;+ /**+ * @type string+ */+ trace_id?: string;+ /**+ * @type string+ */+ trace_state?: string;+}+export interface TypesAlertStatusDTO {/*** @type array@@ -7493,6 +7724,17 @@ export type GetHosts200 = {status: string;};+export type GetWaterfallPathParameters = {+ traceID: string;+};+export type GetWaterfall200 = {+ data: TracedetailtypesGettableWaterfallTraceDTO;+ /**+ * @type string+ */+ status: string;+};+export type QueryRangeV5200 = {data: Querybuildertypesv5QueryRangeResponseDTO;/**diff --git a/frontend/src/api/generated/services/tracedetail/index.ts b/frontend/src/api/generated/services/tracedetail/index.tsnew file mode 100644index 0000000000..e5701d1017--- /dev/null+++ b/frontend/src/api/generated/services/tracedetail/index.ts@@ -0,0 +1,123 @@+/**+ * ! Do not edit manually+ * * The file has been auto-generated using Orval for SigNoz+ * * regenerate with 'yarn generate:api'+ * SigNoz+ */+import { useMutation } from 'react-query';+import type {+ MutationFunction,+ UseMutationOptions,+ UseMutationResult,+} from 'react-query';++import type {+ GetWaterfall200,+ GetWaterfallPathParameters,+ RenderErrorResponseDTO,+ TracedetailtypesPostableWaterfallDTO,+} from '../sigNoz.schemas';++import { GeneratedAPIInstance } from '../../../generatedAPIInstance';+import type { ErrorType, BodyType } from '../../../generatedAPIInstance';++/**+ * Returns the waterfall view of spans for a given trace ID with tree structure, metadata, and windowed pagination+ * @summary Get waterfall view for a trace+ */+export const getWaterfall = (+ { traceID }: GetWaterfallPathParameters,+ tracedetailtypesPostableWaterfallDTO: BodyType<TracedetailtypesPostableWaterfallDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetWaterfall200>({+ url: `/api/v3/traces/${traceID}/waterfall`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: tracedetailtypesPostableWaterfallDTO,+ signal,+ });+};++export const getGetWaterfallMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof getWaterfall>>,+ TError,+ {+ pathParams: GetWaterfallPathParameters;+ data: BodyType<TracedetailtypesPostableWaterfallDTO>;+ },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof getWaterfall>>,+ TError,+ {+ pathParams: GetWaterfallPathParameters;+ data: BodyType<TracedetailtypesPostableWaterfallDTO>;+ },+ TContext+> => {+ const mutationKey = ['getWaterfall'];+ 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 getWaterfall>>,+ {+ pathParams: GetWaterfallPathParameters;+ data: BodyType<TracedetailtypesPostableWaterfallDTO>;+ }+ > = (props) => {+ const { pathParams, data } = props ?? {};++ return getWaterfall(pathParams, data);+ };++ return { mutationFn, ...mutationOptions };+};++export type GetWaterfallMutationResult = NonNullable<+ Awaited<ReturnType<typeof getWaterfall>>+>;+export type GetWaterfallMutationBody =+ BodyType<TracedetailtypesPostableWaterfallDTO>;+export type GetWaterfallMutationError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get waterfall view for a trace+ */+export const useGetWaterfall = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof getWaterfall>>,+ TError,+ {+ pathParams: GetWaterfallPathParameters;+ data: BodyType<TracedetailtypesPostableWaterfallDTO>;+ },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof getWaterfall>>,+ TError,+ {+ pathParams: GetWaterfallPathParameters;+ data: BodyType<TracedetailtypesPostableWaterfallDTO>;+ },+ TContext+> => {+ const mutationOptions = getGetWaterfallMutationOptions(options);++ return useMutation(mutationOptions);+};diff --git a/pkg/apiserver/signozapiserver/provider.go b/pkg/apiserver/signozapiserver/provider.goindex c50cf87da8..14d6039da9 100644--- a/pkg/apiserver/signozapiserver/provider.go+++ b/pkg/apiserver/signozapiserver/provider.go@@ -25,6 +25,7 @@ import ("github.com/SigNoz/signoz/pkg/modules/rulestatehistory""github.com/SigNoz/signoz/pkg/modules/serviceaccount""github.com/SigNoz/signoz/pkg/modules/session"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail""github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/ruler"@@ -62,6 +63,7 @@ type provider struct {cloudIntegrationHandler cloudintegration.HandlerruleStateHistoryHandler rulestatehistory.HandleralertmanagerHandler alertmanager.Handler+ traceDetailHandler tracedetail.HandlerrulerHandler ruler.Handler}@@ -91,6 +93,7 @@ func NewFactory(cloudIntegrationHandler cloudintegration.Handler,ruleStateHistoryHandler rulestatehistory.Handler,alertmanagerHandler alertmanager.Handler,+ traceDetailHandler tracedetail.Handler,rulerHandler ruler.Handler,) factory.ProviderFactory[apiserver.APIServer, apiserver.Config] {return factory.NewProviderFactory(factory.MustNewName("signoz"), func(ctx context.Context, providerSettings factory.ProviderSettings, config apiserver.Config) (apiserver.APIServer, error) {@@ -123,6 +126,7 @@ func NewFactory(cloudIntegrationHandler,ruleStateHistoryHandler,alertmanagerHandler,+ traceDetailHandler,rulerHandler,)})@@ -157,6 +161,7 @@ func newProvider(cloudIntegrationHandler cloudintegration.Handler,ruleStateHistoryHandler rulestatehistory.Handler,alertmanagerHandler alertmanager.Handler,+ traceDetailHandler tracedetail.Handler,rulerHandler ruler.Handler,) (apiserver.APIServer, error) {settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/apiserver/signozapiserver")@@ -189,6 +194,7 @@ func newProvider(cloudIntegrationHandler: cloudIntegrationHandler,ruleStateHistoryHandler: ruleStateHistoryHandler,alertmanagerHandler: alertmanagerHandler,+ traceDetailHandler: traceDetailHandler,rulerHandler: rulerHandler,}@@ -298,6 +304,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {return err}+ if err := provider.addTraceDetailRoutes(router); err != nil {+ return err+ }+if err := provider.addRulerRoutes(router); err != nil {return err}diff --git a/pkg/apiserver/signozapiserver/tracedetail.go b/pkg/apiserver/signozapiserver/tracedetail.gonew file mode 100644index 0000000000..1a59e6a68e--- /dev/null+++ b/pkg/apiserver/signozapiserver/tracedetail.go@@ -0,0 +1,33 @@+package signozapiserver++import (+ "net/http"++ "github.com/SigNoz/signoz/pkg/http/handler"+ "github.com/SigNoz/signoz/pkg/types"+ "github.com/SigNoz/signoz/pkg/types/tracedetailtypes"+ "github.com/gorilla/mux"+)++func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {+ if err := router.Handle("/api/v3/traces/{traceID}/waterfall", handler.New(+ provider.authZ.ViewAccess(provider.traceDetailHandler.GetWaterfall),+ handler.OpenAPIDef{+ ID: "GetWaterfall",+ Tags: []string{"tracedetail"},+ Summary: "Get waterfall view for a trace",+ Description: "Returns the waterfall view of spans for a given trace ID with tree structure, metadata, and windowed pagination",+ Request: new(tracedetailtypes.PostableWaterfall),+ RequestContentType: "application/json",+ Response: new(tracedetailtypes.GettableWaterfallTrace),+ 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/config.go b/pkg/modules/tracedetail/config.gonew file mode 100644index 0000000000..4c62234751--- /dev/null+++ b/pkg/modules/tracedetail/config.go@@ -0,0 +1,49 @@+package tracedetail++import (+ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/factory"+)++type Config struct {+ Waterfall WaterfallConfig `mapstructure:"waterfall"`+}++type WaterfallConfig struct {+ // SpanPageSize is the window size of spans returned per request.+ SpanPageSize float64 `mapstructure:"span_page_size"`+ // MaxDepthToAutoExpand is the depth of auto-expanded descendants below selectedSpanID.+ MaxDepthToAutoExpand int `mapstructure:"max_depth_to_auto_expand"`+ // MaxLimitToSelectAllSpans is the threshold below which all spans are returned without windowing.+ MaxLimitToSelectAllSpans uint `mapstructure:"max_limit_to_select_all_spans"`+}++func NewConfigFactory() factory.ConfigFactory {+ return factory.NewConfigFactory(factory.MustNewName("tracedetail"), newConfig)+}++func newConfig() factory.Config {+ return Config{+ Waterfall: WaterfallConfig{+ SpanPageSize: 500,+ MaxDepthToAutoExpand: 5,+ MaxLimitToSelectAllSpans: 10_000,+ },+ }+}++func (c Config) Validate() error {+ if c.Waterfall.SpanPageSize <= 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "tracedetail.waterfall.span_limit_per_request must be positive, got %v", c.Waterfall.SpanPageSize)+ }+ if c.Waterfall.MaxDepthToAutoExpand < 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "tracedetail.waterfall.max_depth_for_selected_children cannot be negative, got %d", c.Waterfall.MaxDepthToAutoExpand)+ }+ if c.Waterfall.MaxLimitToSelectAllSpans == 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "tracedetail.waterfall.max_limit_to_select_all_spans must be positive")+ }+ return nil+}diff --git a/pkg/modules/tracedetail/impltracedetail/handler.go b/pkg/modules/tracedetail/impltracedetail/handler.gonew file mode 100644index 0000000000..af328ad424--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/handler.go@@ -0,0 +1,35 @@+package impltracedetail++import (+ "net/http"++ "github.com/SigNoz/signoz/pkg/http/binding"+ "github.com/SigNoz/signoz/pkg/http/render"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail"+ "github.com/SigNoz/signoz/pkg/types/tracedetailtypes"+ "github.com/gorilla/mux"+)++type handler struct {+ module tracedetail.Module+}++func NewHandler(module tracedetail.Module) tracedetail.Handler {+ return &handler{module: module}+}++func (h *handler) GetWaterfall(rw http.ResponseWriter, r *http.Request) {+ req := new(tracedetailtypes.PostableWaterfall)+ if err := binding.JSON.BindBody(r.Body, req); err != nil {+ render.Error(rw, err)+ return+ }++ result, err := h.module.GetWaterfall(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.gonew file mode 100644index 0000000000..f74bbe913e--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/module.go@@ -0,0 +1,61 @@+package impltracedetail++import (+ "context"++ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail"+ "github.com/SigNoz/signoz/pkg/types/tracedetailtypes"+)++type module struct {+ store tracedetailtypes.TraceStore+ settings factory.ScopedProviderSettings+ config tracedetail.Config+}++func NewModule(traceStore tracedetailtypes.TraceStore, providerSettings factory.ProviderSettings, cfg tracedetail.Config) *module {+ scopedProviderSettings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/modules/tracedetail/impltracedetail")+ return &module{+ config: cfg,+ store: traceStore,+ settings: scopedProviderSettings,+ }+}++func (m *module) GetWaterfall(ctx context.Context, traceID string, req *tracedetailtypes.PostableWaterfall) (*tracedetailtypes.GettableWaterfallTrace, error) {+ waterfallTrace, err := m.getTraceData(ctx, traceID)+ if err != nil {+ return nil, err+ }++ selectedSpans, uncollapsedSpans, selectedAllSpans := waterfallTrace.GetWaterfallSpans(+ req.UncollapsedSpans,+ req.SelectedSpanID,+ min(req.Limit, m.config.Waterfall.MaxLimitToSelectAllSpans),+ m.config.Waterfall.SpanPageSize,+ m.config.Waterfall.MaxDepthToAutoExpand,+ )++ return tracedetailtypes.NewGettableWaterfallTrace(waterfallTrace, selectedSpans, uncollapsedSpans, selectedAllSpans), nil+}++// getTraceData returns the waterfall cache for the given traceID with fallback on DB.+func (m *module) getTraceData(ctx context.Context, traceID string) (*tracedetailtypes.WaterfallTrace, error) {+ summary, err := m.store.GetTraceSummary(ctx, traceID)+ if err != nil {+ return nil, err+ }++ spanItems, err := m.store.GetTraceSpans(ctx, traceID, summary)+ if err != nil {+ return nil, err+ }++ if len(spanItems) == 0 {+ return nil, tracedetailtypes.ErrTraceNotFound+ }++ traceData := tracedetailtypes.NewWaterfallTraceFromSpans(spanItems)+ return traceData, nil+}diff --git a/pkg/modules/tracedetail/impltracedetail/store.go b/pkg/modules/tracedetail/impltracedetail/store.gonew file mode 100644index 0000000000..4bb4b815b7--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/store.go@@ -0,0 +1,71 @@+package impltracedetail++import (+ "context"+ "database/sql"+ "fmt"++ sqlbuilder "github.com/huandu/go-sqlbuilder"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/telemetrystore"+ "github.com/SigNoz/signoz/pkg/types/tracedetailtypes"+)++type traceStore struct {+ telemetryStore telemetrystore.TelemetryStore+}++func NewTraceStore(ts telemetrystore.TelemetryStore) *traceStore {+ return &traceStore{telemetryStore: ts}+}++func (s *traceStore) GetTraceSummary(ctx context.Context, traceID string) (*tracedetailtypes.TraceSummary, error) {+ sb := sqlbuilder.NewSelectBuilder()+ sb.Select("trace_id", "min(start) AS start", "max(end) AS end", "sum(num_spans) AS num_spans")+ sb.From(fmt.Sprintf("%s.%s", tracedetailtypes.TraceDB, tracedetailtypes.TraceSummaryTable))+ sb.Where(sb.E("trace_id", traceID))+ sb.GroupBy("trace_id")+ query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)++ var summary tracedetailtypes.TraceSummary+ err := s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(+ &summary.TraceID, &summary.Start, &summary.End, &summary.NumSpans,+ )+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, tracedetailtypes.ErrTraceNotFound+ }+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace summary")+ }+ return &summary, nil+}++func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, summary *tracedetailtypes.TraceSummary) ([]tracedetailtypes.StorableSpan, error) {+ // DISTINCT ON (span_id) is ClickHouse-specific syntax not supported by sqlbuilder+ query := fmt.Sprintf(`+ SELECT DISTINCT ON (span_id)+ timestamp, duration_nano, span_id, trace_id, has_error, kind,+ resource_string_service$$name, name, links as references,+ attributes_string, attributes_number, attributes_bool, resources_string,+ events, status_message, status_code_string, kind_string, parent_span_id,+ flags, is_remote, trace_state, status_code,+ db_name, db_operation, http_method, http_url, http_host,+ external_http_method, external_http_url, response_status_code+ FROM %s.%s+ WHERE trace_id=? AND ts_bucket_start>=? AND ts_bucket_start<=?+ ORDER BY timestamp ASC, name ASC`,+ tracedetailtypes.TraceDB, tracedetailtypes.TraceTable,+ )+ var spanItems []tracedetailtypes.StorableSpan+ err := s.telemetryStore.ClickhouseDB().Select(+ ctx, &spanItems, query,+ traceID,+ summary.Start.Unix()-1800,+ summary.End.Unix(),+ )+ if err != nil {+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans")+ }+ return spanItems, nil+}diff --git a/pkg/modules/tracedetail/impltracedetail/waterfall_test.go b/pkg/modules/tracedetail/impltracedetail/waterfall_test.gonew file mode 100644index 0000000000..7ddd01171a--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/waterfall_test.go@@ -0,0 +1,574 @@+// Package impltracedetail tests — waterfall+//+// # Background+//+// The waterfall view renders a trace as a scrollable list of spans in+// pre-order (parent before children, siblings left-to-right). Because a trace+// can have thousands of spans, only a window of ~500 is returned per request.+// The window is centred on the selected span.+//+// # Key concepts+//+// uncollapsedSpans+//+// The set of span IDs the user has manually expanded in the UI.+// Only the direct children of an uncollapsed span are included in the+// output; grandchildren stay hidden until their parent is also uncollapsed.+// When multiple spans are uncollapsed their children are all visible at once.+//+// selectedSpanID+//+// The span currently focused — set when the user clicks a span in the+// waterfall or selects one from the flamegraph. The output window is always+// centred on this span. The path from the trace root down to the selected+// span is automatically uncollapsed so ancestors are visible even if they are+// not in uncollapsedSpans.+//+//+// traceRoots+//+// Root spans of the trace — spans with no parent in the current dataset.+// Normally one, but multiple roots are common when upstream services are+// not instrumented or their spans were not sampled/exported.++package impltracedetail++import (+ "fmt"+ "testing"++ "github.com/SigNoz/signoz/pkg/types/tracedetailtypes"+ "github.com/stretchr/testify/assert"+)++// ─────────────────────────────────────────────────────────────────────────────+// Helpers+// ─────────────────────────────────────────────────────────────────────────────++func mkSpan(id, service string, children ...*tracedetailtypes.WaterfallSpan) *tracedetailtypes.WaterfallSpan {+ return &tracedetailtypes.WaterfallSpan{+ SpanID: id,+ ServiceName: service,+ Name: id + "-op",+ Children: children,+ }+}++func spanIDs(spans []*tracedetailtypes.WaterfallSpan) []string {+ ids := make([]string, len(spans))+ for i, s := range spans {+ ids[i] = s.SpanID+ }+ return ids+}++func buildSpanMap(roots ...*tracedetailtypes.WaterfallSpan) map[string]*tracedetailtypes.WaterfallSpan {+ m := map[string]*tracedetailtypes.WaterfallSpan{}+ var walk func(*tracedetailtypes.WaterfallSpan)+ walk = func(s *tracedetailtypes.WaterfallSpan) {+ m[s.SpanID] = s+ for _, c := range s.Children {+ walk(c)+ }+ }+ for _, r := range roots {+ r.SortChildren()+ r.GetSubtreeNodeCount()+ walk(r)+ }+ return m+}++// makeChain builds a linear trace: span0 → span1 → … → span(n-1).+func makeChain(n int) (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan, []string) {+ spans := make([]*tracedetailtypes.WaterfallSpan, n)+ for i := n - 1; i >= 0; i-- {+ if i == n-1 {+ spans[i] = mkSpan(fmt.Sprintf("span%d", i), "svc")+ } else {+ spans[i] = mkSpan(fmt.Sprintf("span%d", i), "svc", spans[i+1])+ }+ }+ uncollapsed := make([]string, n)+ for i := range spans {+ uncollapsed[i] = fmt.Sprintf("span%d", i)+ }+ return spans[0], buildSpanMap(spans[0]), uncollapsed+}++func getWaterfallTrace(roots []*tracedetailtypes.WaterfallSpan, spanMap map[string]*tracedetailtypes.WaterfallSpan) *tracedetailtypes.WaterfallTrace {+ return tracedetailtypes.NewWaterfallTrace(0, 0, uint64(len(spanMap)), 0, spanMap, nil, roots, false)+}++// ─────────────────────────────────────────────────────────────────────────────+// GetSelectedSpans — span ordering and visibility+// ─────────────────────────────────────────────────────────────────────────────++func TestGetSelectedSpans_SpanOrdering(t *testing.T) {+ tests := []struct {+ name string+ buildRoots func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan)+ uncollapsedSpans []string+ selectedSpanID string+ wantSpanIDs []string+ }{+ {+ // Pre-order traversal is preserved: parent before children, siblings left-to-right.+ name: "pre_order_traversal",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("child1", "svc", mkSpan("grandchild", "svc")),+ mkSpan("child2", "svc"),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{"root", "child1"},+ selectedSpanID: "root",+ wantSpanIDs: []string{"root", "child1", "grandchild", "child2"},+ },+ {+ // Multiple spans uncollapsed simultaneously: children of all uncollapsed spans are visible at once.+ //+ // root+ // ├─ childA (uncollapsed) → grandchildA ✓+ // └─ childB (uncollapsed) → grandchildB ✓+ name: "multiple_uncollapsed",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("childA", "svc", mkSpan("grandchildA", "svc")),+ mkSpan("childB", "svc", mkSpan("grandchildB", "svc")),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{"root", "childA", "childB"},+ selectedSpanID: "root",+ wantSpanIDs: []string{"root", "childA", "grandchildA", "childB", "grandchildB"},+ },+ {+ // Collapsing a span with other uncollapsed spans.+ //+ // root+ // ├─ childA (previously expanded — in uncollapsedSpans)+ // │ ├─ grandchild1 ✓+ // │ │ └─ greatGrandchild ✗ (grandchild1 not in uncollapsedSpans)+ // │ └─ grandchild2 ✓+ // └─ childB ← selected (not expanded)+ name: "manual_uncollapse",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("childA", "svc",+ mkSpan("grandchild1", "svc", mkSpan("greatGrandchild", "svc")),+ mkSpan("grandchild2", "svc"),+ ),+ mkSpan("childB", "svc"),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{"childA"},+ selectedSpanID: "childB",+ wantSpanIDs: []string{"root", "childA", "grandchild1", "grandchild2", "childB"},+ },+ {+ // A collapsed span hides all children.+ name: "collapsed_span_hides_children",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("child1", "svc"),+ mkSpan("child2", "svc"),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "root",+ wantSpanIDs: []string{"root"},+ },+ {+ // Selecting a span auto-uncollpases the path from root to that span so it is visible.+ //+ // root → parent → selected+ name: "path_to_selected_is_uncollapsed",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("parent", "svc",+ mkSpan("selected", "svc"),+ ),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "selected",+ wantSpanIDs: []string{"root", "parent", "selected"},+ },+ {+ // Siblings of ancestors are rendered as collapsed nodes but their subtrees must NOT be expanded.+ //+ // root+ // ├─ unrelated → unrelated-child (✗)+ // └─ parent → selected+ name: "siblings_not_expanded",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("unrelated", "svc", mkSpan("unrelated-child", "svc")),+ mkSpan("parent", "svc",+ mkSpan("selected", "svc"),+ ),+ )+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "selected",+ // children of root sort alphabetically: parent < unrelated; unrelated-child stays hidden+ wantSpanIDs: []string{"root", "parent", "selected", "unrelated"},+ },+ {+ // An unknown selectedSpanID must not panic; returns a window from index 0.+ name: "unknown_selected_span",+ buildRoots: func() ([]*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc", mkSpan("child", "svc"))+ return []*tracedetailtypes.WaterfallSpan{root}, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "nonexistent",+ wantSpanIDs: []string{"root"},+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ roots, spanMap := tc.buildRoots()+ trace := getWaterfallTrace(roots, spanMap)+ spans, _ := trace.GetSelectedSpans(tc.uncollapsedSpans, tc.selectedSpanID, 500, 5)+ assert.Equal(t, tc.wantSpanIDs, spanIDs(spans))+ })+ }+}++// Multiple roots: both trees are flattened into a single pre-order list with+// root1's subtree before root2's. Service/entry-point come from the first root.+//+// root1 svc-a ← selected+// └─ child1+// root2 svc-b+// └─ child2+//+// Expected output order: root1 → child1 → root2 → child2.+func TestGetSelectedSpans_MultipleRoots(t *testing.T) {+ root1 := mkSpan("root1", "svc-a", mkSpan("child1", "svc-a"))+ root2 := mkSpan("root2", "svc-b", mkSpan("child2", "svc-b"))+ spanMap := buildSpanMap(root1, root2)++ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root1, root2}, spanMap)+ spans, _ := trace.GetSelectedSpans([]string{"root1", "root2"}, "root1", 500, 5)++ traceRespnose := tracedetailtypes.NewGettableWaterfallTrace(trace, spans, nil, false)++ assert.Equal(t, []string{"root1", "child1", "root2", "child2"}, spanIDs(spans), "root1 subtree must precede root2 subtree")+ assert.Equal(t, "svc-a", traceRespnose.RootServiceName, "metadata comes from first root")+ assert.Equal(t, "root1-op", traceRespnose.RootServiceEntryPoint, "metadata comes from first root")+}++// ─────────────────────────────────────────────────────────────────────────────+// GetSelectedSpans — uncollapsed span tracking+// ─────────────────────────────────────────────────────────────────────────────++func TestGetSelectedSpans_UncollapsedTracking(t *testing.T) {+ tests := []struct {+ name string+ buildRoot func() (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan)+ uncollapsedSpans []string+ selectedSpanID string+ wantSpanIDs []string+ checkUncollapsed func(t *testing.T, uncollapsed []string)+ }{+ {+ // The path-to-selected spans are returned in updatedUncollapsedSpans.+ name: "path_returned_in_uncollapsed",+ buildRoot: func() (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("parent", "svc",+ mkSpan("selected", "svc"),+ ),+ )+ return root, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "selected",+ wantSpanIDs: []string{"root", "parent", "selected"},+ checkUncollapsed: func(t *testing.T, uncollapsed []string) {+ assert.ElementsMatch(t, []string{"root", "parent"}, uncollapsed)+ },+ },+ {+ // Siblings of ancestors are not tracked as uncollapsed.+ name: "siblings_not_in_uncollapsed",+ buildRoot: func() (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("unrelated", "svc", mkSpan("unrelated-child", "svc")),+ mkSpan("parent", "svc",+ mkSpan("selected", "svc"),+ ),+ )+ return root, buildSpanMap(root)+ },+ uncollapsedSpans: []string{},+ selectedSpanID: "selected",+ wantSpanIDs: []string{"root", "parent", "selected", "unrelated"},+ checkUncollapsed: func(t *testing.T, uncollapsed []string) {+ assert.ElementsMatch(t, []string{"root", "parent"}, uncollapsed)+ },+ },+ {+ // Auto-expanded span IDs from ALL branches are returned in updatedUncollapsedSpans.+ // Only internal nodes (spans with children) are tracked — leaf spans are never added.+ // root is in uncollapsedSpans, so its children are auto-expanded.+ //+ // root (selected, expanded)+ // ├─ childA (internal ✓)+ // │ └─ grandchildA (internal ✓)+ // │ └─ leafA (leaf ✗)+ // └─ childB (internal ✓)+ // └─ grandchildB (internal ✓)+ // └─ leafB (leaf ✗)+ name: "auto_expanded_spans_returned",+ buildRoot: func() (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("childA", "svc",+ mkSpan("grandchildA", "svc",+ mkSpan("leafA", "svc"),+ ),+ ),+ mkSpan("childB", "svc",+ mkSpan("grandchildB", "svc",+ mkSpan("leafB", "svc"),+ ),+ ),+ )+ return root, buildSpanMap(root)+ },+ uncollapsedSpans: []string{"root"},+ selectedSpanID: "root",+ checkUncollapsed: func(t *testing.T, uncollapsed []string) {+ assert.Contains(t, uncollapsed, "root")+ assert.Contains(t, uncollapsed, "childA", "internal node depth 1, branch A")+ assert.Contains(t, uncollapsed, "childB", "internal node depth 1, branch B")+ assert.Contains(t, uncollapsed, "grandchildA", "internal node depth 2, branch A")+ assert.Contains(t, uncollapsed, "grandchildB", "internal node depth 2, branch B")+ assert.NotContains(t, uncollapsed, "leafA", "leaf spans are never added to uncollapsedSpans")+ assert.NotContains(t, uncollapsed, "leafB", "leaf spans are never added to uncollapsedSpans")+ },+ },+ {+ // If the selected span is already in uncollapsedSpans,+ // it should appear exactly once in the result.+ name: "duplicate_in_uncollapsed",+ buildRoot: func() (*tracedetailtypes.WaterfallSpan, map[string]*tracedetailtypes.WaterfallSpan) {+ root := mkSpan("root", "svc",+ mkSpan("selected", "svc", mkSpan("child", "svc")),+ )+ return root, buildSpanMap(root)+ },+ uncollapsedSpans: []string{"selected"}, // already present+ selectedSpanID: "selected",+ checkUncollapsed: func(t *testing.T, uncollapsed []string) {+ count := 0+ for _, id := range uncollapsed {+ if id == "selected" {+ count+++ }+ }+ assert.Equal(t, 1, count, "should appear once")+ },+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ root, spanMap := tc.buildRoot()+ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root}, spanMap)+ spans, uncollapsed := trace.GetSelectedSpans(tc.uncollapsedSpans, tc.selectedSpanID, 500, 5)+ if tc.wantSpanIDs != nil {+ assert.Equal(t, tc.wantSpanIDs, spanIDs(spans))+ }+ if tc.checkUncollapsed != nil {+ tc.checkUncollapsed(t, uncollapsed)+ }+ })+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// GetSelectedSpans — span metadata+// ─────────────────────────────────────────────────────────────────────────────++// Test to check if Level, HasChildren, and SubTreeNodeCount are populated correctly.+//+// root level=0, hasChildren=true, subTree=4+// child1 level=1, hasChildren=true, subTree=2+// grandchild level=2, hasChildren=false, subTree=1+// child2 level=1, hasChildren=false, subTree=1+func TestGetSelectedSpans_SpanMetadata(t *testing.T) {+ root := mkSpan("root", "svc",+ mkSpan("child1", "svc", mkSpan("grandchild", "svc")),+ mkSpan("child2", "svc"),+ )+ spanMap := buildSpanMap(root)+ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root}, spanMap)+ spans, _ := trace.GetSelectedSpans([]string{"root", "child1"}, "root", 500, 5)++ byID := map[string]*tracedetailtypes.WaterfallSpan{}+ for _, s := range spans {+ byID[s.SpanID] = s+ }++ tests := []struct {+ spanID string+ wantLevel uint64+ wantHasChildren bool+ wantSubTree uint64+ }{+ {"root", 0, true, 4},+ {"child1", 1, true, 2},+ {"child2", 1, false, 1},+ {"grandchild", 2, false, 1},+ }++ for _, tc := range tests {+ t.Run(tc.spanID, func(t *testing.T) {+ s := byID[tc.spanID]+ assert.Equal(t, tc.wantLevel, s.Level)+ assert.Equal(t, tc.wantHasChildren, s.HasChildren)+ assert.Equal(t, tc.wantSubTree, s.SubTreeNodeCount)+ })+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// GetSelectedSpans — windowing+// ─────────────────────────────────────────────────────────────────────────────++func TestGetSelectedSpans_Window(t *testing.T) {+ tests := []struct {+ name string+ selectedSpanID string+ wantLen int+ wantFirst string+ wantLast string+ wantSelectedPos int+ }{+ {+ // The selected span is centred: 200 spans before it, 300 after (0.4 / 0.6 split).+ name: "centred_on_selected",+ selectedSpanID: "span300",+ wantLen: 500,+ wantFirst: "span100",+ wantLast: "span599",+ wantSelectedPos: 200,+ },+ {+ // When the selected span is near the start, the window shifts right so no+ // negative index is used — the result is still 500 spans.+ name: "shifts_at_start",+ selectedSpanID: "span10",+ wantLen: 500,+ wantFirst: "span0",+ wantSelectedPos: 10,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ root, spanMap, uncollapsed := makeChain(600)+ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root}, spanMap)+ spans, _ := trace.GetSelectedSpans(uncollapsed, tc.selectedSpanID, 500, 5)++ assert.Equal(t, tc.wantLen, len(spans), "window size")+ assert.Equal(t, tc.wantFirst, spans[0].SpanID, "first span in window")+ if tc.wantLast != "" {+ assert.Equal(t, tc.wantLast, spans[len(spans)-1].SpanID, "last span in window")+ }+ assert.Equal(t, tc.selectedSpanID, spans[tc.wantSelectedPos].SpanID, "selected span position")+ })+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// GetSelectedSpans — depth limit+// ─────────────────────────────────────────────────────────────────────────────++// Depth is measured from the selected span, not the trace root.+// Ancestors appear via the path-to-root logic, not the depth limit.+// Each depth level has two children to confirm the limit is enforced on all+// branches, not just the first.+//+// root+// └─ A ancestor ✓ (path-to-root)+// └─ selected+// ├─ d1a depth 1 ✓+// │ ├─ d2a depth 2 ✓+// │ │ ├─ d3a depth 3 ✓+// │ │ │ ├─ d4a depth 4 ✓+// │ │ │ │ ├─ d5a depth 5 ✓+// │ │ │ │ │ └─ d6a depth 6 ✗+// │ │ │ │ └─ d5b depth 5 ✓+// │ │ │ └─ d4b depth 4 ✓+// │ │ └─ d3b depth 3 ✓+// │ └─ d2b depth 2 ✓+// └─ d1b depth 1 ✓+func TestGetSelectedSpans_DepthCountedFromSelectedSpan(t *testing.T) {+ selected := mkSpan("selected", "svc",+ mkSpan("d1a", "svc",+ mkSpan("d2a", "svc",+ mkSpan("d3a", "svc",+ mkSpan("d4a", "svc",+ mkSpan("d5a", "svc",+ mkSpan("d6a", "svc"), // depth 6 — excluded+ ),+ mkSpan("d5b", "svc"), // depth 5 — included+ ),+ mkSpan("d4b", "svc"), // depth 4 — included+ ),+ mkSpan("d3b", "svc"), // depth 3 — included+ ),+ mkSpan("d2b", "svc"), // depth 2 — included+ ),+ mkSpan("d1b", "svc"), // depth 1 — included+ )+ root := mkSpan("root", "svc", mkSpan("A", "svc", selected))++ spanMap := buildSpanMap(root)+ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root}, spanMap)+ spans, _ := trace.GetSelectedSpans([]string{"selected"}, "selected", 500, 5)+ ids := spanIDs(spans)++ assert.Contains(t, ids, "root", "ancestor shown via path-to-root")+ assert.Contains(t, ids, "A", "ancestor shown via path-to-root")+ for _, id := range []string{"d1a", "d1b", "d2a", "d2b", "d3a", "d3b", "d4a", "d4b", "d5a", "d5b"} {+ assert.Contains(t, ids, id, "depth ≤ 5 — must be included")+ }+ assert.NotContains(t, ids, "d6a", "depth 6 > limit — excluded")+}++// ─────────────────────────────────────────────────────────────────────────────+// GetAllSpans+// ─────────────────────────────────────────────────────────────────────────────++func TestGetAllSpans(t *testing.T) {+ root := mkSpan("root", "svc",+ mkSpan("childA", "svc",+ mkSpan("grandchildA", "svc",+ mkSpan("leafA", "svc2"),+ ),+ ),+ mkSpan("childB", "svc3",+ mkSpan("grandchildB", "svc",+ mkSpan("leafB", "svc2"),+ ),+ ),+ )+ trace := getWaterfallTrace([]*tracedetailtypes.WaterfallSpan{root}, nil)+ spans := trace.GetAllSpans()+ traceResponse := tracedetailtypes.NewGettableWaterfallTrace(trace, spans, nil, true)+ assert.ElementsMatch(t, spanIDs(spans), []string{"root", "childA", "grandchildA", "leafA", "childB", "grandchildB", "leafB"})+ assert.Equal(t, "svc", traceResponse.RootServiceName)+ assert.Equal(t, "root-op", traceResponse.RootServiceEntryPoint)+}diff --git a/pkg/modules/tracedetail/tracedetail.go b/pkg/modules/tracedetail/tracedetail.goindex c40ff0a70c..48768f2860 100644--- a/pkg/modules/tracedetail/tracedetail.go+++ b/pkg/modules/tracedetail/tracedetail.go@@ -5,7 +5,6 @@ import ("net/http""github.com/SigNoz/signoz/pkg/types/tracedetailtypes"- "github.com/SigNoz/signoz/pkg/valuer")// Handler exposes HTTP handlers for trace detail APIs.@@ -15,5 +14,5 @@ type Handler interface {// Module defines the business logic for trace detail operations.type Module interface {- GetWaterfall(ctx context.Context, orgID valuer.UUID, traceID string, req *tracedetailtypes.WaterfallRequest) (*tracedetailtypes.WaterfallResponse, error)+ GetWaterfall(ctx context.Context, traceID string, req *tracedetailtypes.PostableWaterfall) (*tracedetailtypes.GettableWaterfallTrace, error)}diff --git a/pkg/signoz/config.go b/pkg/signoz/config.goindex 69e3812c73..960bc0601b 100644--- a/pkg/signoz/config.go+++ b/pkg/signoz/config.go@@ -27,6 +27,7 @@ import ("github.com/SigNoz/signoz/pkg/modules/inframonitoring""github.com/SigNoz/signoz/pkg/modules/metricsexplorer""github.com/SigNoz/signoz/pkg/modules/serviceaccount"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail""github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/pprof""github.com/SigNoz/signoz/pkg/prometheus"@@ -137,6 +138,9 @@ type Config struct {// CloudIntegration configCloudIntegration cloudintegration.Config `mapstructure:"cloudintegration"`+ // TraceDetail config+ TraceDetail tracedetail.Config `mapstructure:"tracedetail"`+// Authz configAuthz authz.Config `mapstructure:"authz"`}@@ -172,6 +176,7 @@ func NewConfig(ctx context.Context, logger *slog.Logger, resolverConfig config.Rserviceaccount.NewConfigFactory(),auditor.NewConfigFactory(),cloudintegration.NewConfigFactory(),+ tracedetail.NewConfigFactory(),authz.NewConfigFactory(),}diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.goindex e9274c53dd..aa23b0f54e 100644--- a/pkg/signoz/handler.go+++ b/pkg/signoz/handler.go@@ -3,8 +3,6 @@ package signozimport ("github.com/SigNoz/signoz/pkg/alertmanager""github.com/SigNoz/signoz/pkg/alertmanager/signozalertmanager"- "github.com/SigNoz/signoz/pkg/ruler"- "github.com/SigNoz/signoz/pkg/ruler/signozruler""github.com/SigNoz/signoz/pkg/analytics""github.com/SigNoz/signoz/pkg/authz""github.com/SigNoz/signoz/pkg/authz/signozauthzapi"@@ -40,9 +38,13 @@ import ("github.com/SigNoz/signoz/pkg/modules/services/implservices""github.com/SigNoz/signoz/pkg/modules/spanpercentile""github.com/SigNoz/signoz/pkg/modules/spanpercentile/implspanpercentile"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail/impltracedetail""github.com/SigNoz/signoz/pkg/modules/tracefunnel""github.com/SigNoz/signoz/pkg/modules/tracefunnel/impltracefunnel""github.com/SigNoz/signoz/pkg/querier"+ "github.com/SigNoz/signoz/pkg/ruler"+ "github.com/SigNoz/signoz/pkg/ruler/signozruler""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/zeus")@@ -70,6 +72,7 @@ type Handlers struct {CloudIntegrationHandler cloudintegration.HandlerRuleStateHistory rulestatehistory.HandlerAlertmanagerHandler alertmanager.Handler+ TraceDetail tracedetail.HandlerRulerHandler ruler.Handler}@@ -112,6 +115,7 @@ func NewHandlers(RuleStateHistory: implrulestatehistory.NewHandler(modules.RuleStateHistory),CloudIntegrationHandler: implcloudintegration.NewHandler(modules.CloudIntegration),AlertmanagerHandler: signozalertmanager.NewHandler(alertmanagerService),+ TraceDetail: impltracedetail.NewHandler(modules.TraceDetail),RulerHandler: signozruler.NewHandler(rulerService),}}diff --git a/pkg/signoz/module.go b/pkg/signoz/module.goindex ce3b602e4f..85aabd8926 100644--- a/pkg/signoz/module.go+++ b/pkg/signoz/module.go@@ -39,6 +39,8 @@ import ("github.com/SigNoz/signoz/pkg/modules/session/implsession""github.com/SigNoz/signoz/pkg/modules/spanpercentile""github.com/SigNoz/signoz/pkg/modules/spanpercentile/implspanpercentile"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail/impltracedetail""github.com/SigNoz/signoz/pkg/modules/tracefunnel""github.com/SigNoz/signoz/pkg/modules/tracefunnel/impltracefunnel""github.com/SigNoz/signoz/pkg/modules/user"@@ -76,6 +78,7 @@ type Modules struct {ServiceAccount serviceaccount.ModuleCloudIntegration cloudintegration.ModuleRuleStateHistory rulestatehistory.Module+ TraceDetail tracedetail.Module}func NewModules(@@ -127,5 +130,6 @@ func NewModules(ServiceAccount: serviceAccount,RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger)),CloudIntegration: cloudIntegrationModule,+ TraceDetail: impltracedetail.NewModule(impltracedetail.NewTraceStore(telemetryStore), providerSettings, config.TraceDetail),}}diff --git a/pkg/signoz/openapi.go b/pkg/signoz/openapi.goindex 00004a3c69..33ee136886 100644--- a/pkg/signoz/openapi.go+++ b/pkg/signoz/openapi.go@@ -30,6 +30,7 @@ import ("github.com/SigNoz/signoz/pkg/modules/rulestatehistory""github.com/SigNoz/signoz/pkg/modules/serviceaccount""github.com/SigNoz/signoz/pkg/modules/session"+ "github.com/SigNoz/signoz/pkg/modules/tracedetail""github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/ruler"@@ -74,6 +75,7 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumentastruct{ cloudintegration.Handler }{},struct{ rulestatehistory.Handler }{},struct{ alertmanager.Handler }{},+ struct{ tracedetail.Handler }{},struct{ ruler.Handler }{},).New(ctx, instrumentation.ToProviderSettings(), apiserver.Config{})if err != nil {diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex 5f367e8ca9..bed4a43331 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -3,8 +3,6 @@ package signozimport ("github.com/SigNoz/signoz/pkg/alertmanager""github.com/SigNoz/signoz/pkg/alertmanager/nfmanager"- "github.com/SigNoz/signoz/pkg/auditor"- "github.com/SigNoz/signoz/pkg/auditor/noopauditor""github.com/SigNoz/signoz/pkg/alertmanager/nfmanager/rulebasednotification""github.com/SigNoz/signoz/pkg/alertmanager/signozalertmanager""github.com/SigNoz/signoz/pkg/analytics"@@ -12,6 +10,8 @@ import ("github.com/SigNoz/signoz/pkg/analytics/segmentanalytics""github.com/SigNoz/signoz/pkg/apiserver""github.com/SigNoz/signoz/pkg/apiserver/signozapiserver"+ "github.com/SigNoz/signoz/pkg/auditor"+ "github.com/SigNoz/signoz/pkg/auditor/noopauditor""github.com/SigNoz/signoz/pkg/authz""github.com/SigNoz/signoz/pkg/cache""github.com/SigNoz/signoz/pkg/cache/memorycache"@@ -227,8 +227,6 @@ func NewAlertmanagerProviderFactories(sqlstore sqlstore.SQLStore, orgGetter orga)}--func NewEmailingProviderFactories() factory.NamedMap[factory.ProviderFactory[emailing.Emailing, emailing.Config]] {return factory.MustNewNamedMap(noopemailing.NewFactory(),@@ -284,6 +282,7 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Auhandlers.CloudIntegrationHandler,handlers.RuleStateHistory,handlers.AlertmanagerHandler,+ handlers.TraceDetail,handlers.RulerHandler,),)diff --git a/pkg/types/tracedetailtypes/store.go b/pkg/types/tracedetailtypes/store.gonew file mode 100644index 0000000000..967bd11a69--- /dev/null+++ b/pkg/types/tracedetailtypes/store.go@@ -0,0 +1,9 @@+package tracedetailtypes++import "context"++// TraceStore defines the data access interface for trace detail queries.+type TraceStore interface {+ GetTraceSummary(ctx context.Context, traceID string) (*TraceSummary, error)+ GetTraceSpans(ctx context.Context, traceID string, summary *TraceSummary) ([]StorableSpan, error)+}diff --git a/pkg/types/tracedetailtypes/waterfall.go b/pkg/types/tracedetailtypes/waterfall.godeleted file mode 100644index 2aeabe77d8..0000000000--- a/pkg/types/tracedetailtypes/waterfall.go+++ /dev/null@@ -1,247 +0,0 @@-package tracedetailtypes--import (- "encoding/json"- "maps"- "time"-- "github.com/SigNoz/signoz/pkg/types/cachetypes"-)--// WaterfallRequest is the request body for the v3 waterfall API.-type WaterfallRequest struct {- SelectedSpanID string `json:"selectedSpanId"`- UncollapsedSpans []string `json:"uncollapsedSpans"`- Limit uint `json:"limit"`-}--// WaterfallResponse is the response for the v3 waterfall API.-type WaterfallResponse struct {- StartTimestampMillis uint64 `json:"startTimestampMillis"`- EndTimestampMillis uint64 `json:"endTimestampMillis"`- DurationNano uint64 `json:"durationNano"`- RootServiceName string `json:"rootServiceName"`- RootServiceEntryPoint string `json:"rootServiceEntryPoint"`- TotalSpansCount uint64 `json:"totalSpansCount"`- TotalErrorSpansCount uint64 `json:"totalErrorSpansCount"`- ServiceNameToTotalDurationMap map[string]uint64 `json:"serviceNameToTotalDurationMap"`- Spans []*WaterfallSpan `json:"spans"`- HasMissingSpans bool `json:"hasMissingSpans"`- UncollapsedSpans []string `json:"uncollapsedSpans"`-}--// Event represents a span event.-type Event struct {- Name string `json:"name,omitempty"`- TimeUnixNano uint64 `json:"timeUnixNano,omitempty"`- AttributeMap map[string]any `json:"attributeMap,omitempty"`- IsError bool `json:"isError,omitempty"`-}--// WaterfallSpan represents the span in waterfall response,-// this uses snake_case keys for response as a special case since these-// keys can be directly used to query spans and client need to know the actual fields.-// This pattern should not be copied elsewhere.-type WaterfallSpan struct {- Attributes map[string]any `json:"attributes"`- DBName string `json:"db_name"`- DBOperation string `json:"db_operation"`- DurationNano uint64 `json:"duration_nano"`- Events []Event `json:"events"`- ExternalHTTPMethod string `json:"external_http_method"`- ExternalHTTPURL string `json:"external_http_url"`- Flags uint32 `json:"flags"`- HasError bool `json:"has_error"`- HTTPHost string `json:"http_host"`- HTTPMethod string `json:"http_method"`- HTTPURL string `json:"http_url"`- IsRemote string `json:"is_remote"`- Kind int32 `json:"kind"`- KindString string `json:"kind_string"`- Links string `json:"links"`- Name string `json:"name"`- ParentSpanID string `json:"parent_span_id"`- Resource map[string]string `json:"resource"`- ResponseStatusCode string `json:"response_status_code"`- SpanID string `json:"span_id"`- StatusCode int32 `json:"status_code"`- StatusCodeString string `json:"status_code_string"`- StatusMessage string `json:"status_message"`- Timestamp string `json:"timestamp"`- TraceID string `json:"trace_id"`- TraceState string `json:"trace_state"`-- // Tree structure fields- Children []*WaterfallSpan `json:"-"`- SubTreeNodeCount uint64 `json:"sub_tree_node_count"`- HasChildren bool `json:"has_children"`- Level uint64 `json:"level"`-- // timeUnixNano is an internal field used for tree building and sorting.- // It is not serialized in the JSON response.- TimeUnixNano uint64 `json:"-"`- // serviceName is an internal field used for service time calculation.- ServiceName string `json:"-"`-}--// CopyWithoutChildren creates a shallow copy and reset computed tree fields.-func (s *WaterfallSpan) CopyWithoutChildren(level uint64) *WaterfallSpan {- cp := *s- cp.Level = level- cp.HasChildren = len(s.Children) > 0- cp.Children = make([]*WaterfallSpan, 0)- cp.SubTreeNodeCount = 0- return &cp-}--// SpanModel is the ClickHouse scan struct for the v3 waterfall query.-type SpanModel struct {- TimeUnixNano time.Time `ch:"timestamp"`- DurationNano uint64 `ch:"duration_nano"`- SpanID string `ch:"span_id"`- TraceID string `ch:"trace_id"`- HasError bool `ch:"has_error"`- Kind int8 `ch:"kind"`- ServiceName string `ch:"resource_string_service$$name"`- Name string `ch:"name"`- References string `ch:"references"`- AttributesString map[string]string `ch:"attributes_string"`- AttributesNumber map[string]float64 `ch:"attributes_number"`- AttributesBool map[string]bool `ch:"attributes_bool"`- ResourcesString map[string]string `ch:"resources_string"`- Events []string `ch:"events"`- StatusMessage string `ch:"status_message"`- StatusCodeString string `ch:"status_code_string"`- SpanKind string `ch:"kind_string"`- ParentSpanID string `ch:"parent_span_id"`- Flags uint32 `ch:"flags"`- IsRemote string `ch:"is_remote"`- TraceState string `ch:"trace_state"`- StatusCode int32 `ch:"status_code"`- DBName string `ch:"db_name"`- DBOperation string `ch:"db_operation"`- HTTPMethod string `ch:"http_method"`- HTTPURL string `ch:"http_url"`- HTTPHost string `ch:"http_host"`- ExternalHTTPMethod string `ch:"external_http_method"`- ExternalHTTPURL string `ch:"external_http_url"`- ResponseStatusCode string `ch:"response_status_code"`-}--// ToSpan converts a SpanModel (ClickHouse scan result) into a Span for the waterfall response.-func (item *SpanModel) ToSpan() *WaterfallSpan {- // Merge attributes_string, attributes_number, attributes_bool preserving native types- attributes := make(map[string]any, len(item.AttributesString)+len(item.AttributesNumber)+len(item.AttributesBool))- for k, v := range item.AttributesString {- attributes[k] = v- }- for k, v := range item.AttributesNumber {- attributes[k] = v- }- for k, v := range item.AttributesBool {- attributes[k] = v- }-- resources := make(map[string]string)- maps.Copy(resources, item.ResourcesString)-- events := make([]Event, 0, len(item.Events))- for _, eventStr := range item.Events {- var event Event- if err := json.Unmarshal([]byte(eventStr), &event); err != nil {- continue- }- events = append(events, event)- }-- return &WaterfallSpan{- Attributes: attributes,- DBName: item.DBName,- DBOperation: item.DBOperation,- DurationNano: item.DurationNano,- Events: events,- ExternalHTTPMethod: item.ExternalHTTPMethod,- ExternalHTTPURL: item.ExternalHTTPURL,- Flags: item.Flags,- HasError: item.HasError,- HTTPHost: item.HTTPHost,- HTTPMethod: item.HTTPMethod,- HTTPURL: item.HTTPURL,- IsRemote: item.IsRemote,- Kind: int32(item.Kind),- KindString: item.SpanKind,- Links: item.References,- Name: item.Name,- ParentSpanID: item.ParentSpanID,- Resource: resources,- ResponseStatusCode: item.ResponseStatusCode,- SpanID: item.SpanID,- StatusCode: item.StatusCode,- StatusCodeString: item.StatusCodeString,- StatusMessage: item.StatusMessage,- Timestamp: item.TimeUnixNano.Format(time.RFC3339Nano),- TraceID: item.TraceID,- TraceState: item.TraceState,- Children: make([]*WaterfallSpan, 0),- TimeUnixNano: uint64(item.TimeUnixNano.UnixNano()),- ServiceName: item.ServiceName,- }-}--// TraceSummary is the ClickHouse scan struct for the trace_summary query.-type TraceSummary struct {- TraceID string `ch:"trace_id"`- Start time.Time `ch:"start"`- End time.Time `ch:"end"`- NumSpans uint64 `ch:"num_spans"`-}--// OtelSpanRef is used for parsing the references/links JSON from ClickHouse.-type OtelSpanRef struct {- TraceId string `json:"traceId,omitempty"`- SpanId string `json:"spanId,omitempty"`- RefType string `json:"refType,omitempty"`-}--// WaterfallCache holds pre-processed trace data for caching.-type WaterfallCache struct {- StartTime uint64 `json:"startTime"`- EndTime uint64 `json:"endTime"`- DurationNano uint64 `json:"durationNano"`- TotalSpans uint64 `json:"totalSpans"`- TotalErrorSpans uint64 `json:"totalErrorSpans"`- ServiceNameToTotalDurationMap map[string]uint64 `json:"serviceNameToTotalDurationMap"`- SpanIDToSpanNodeMap map[string]*WaterfallSpan `json:"spanIdToSpanNodeMap"`- TraceRoots []*WaterfallSpan `json:"traceRoots"`- HasMissingSpans bool `json:"hasMissingSpans"`-}--func (c *WaterfallCache) Clone() cachetypes.Cacheable {- copyOfServiceNameToTotalDurationMap := make(map[string]uint64)- maps.Copy(copyOfServiceNameToTotalDurationMap, c.ServiceNameToTotalDurationMap)-- copyOfSpanIDToSpanNodeMap := make(map[string]*WaterfallSpan)- maps.Copy(copyOfSpanIDToSpanNodeMap, c.SpanIDToSpanNodeMap)-- copyOfTraceRoots := make([]*WaterfallSpan, len(c.TraceRoots))- copy(copyOfTraceRoots, c.TraceRoots)- return &WaterfallCache{- StartTime: c.StartTime,- EndTime: c.EndTime,- DurationNano: c.DurationNano,- TotalSpans: c.TotalSpans,- TotalErrorSpans: c.TotalErrorSpans,- ServiceNameToTotalDurationMap: copyOfServiceNameToTotalDurationMap,- SpanIDToSpanNodeMap: copyOfSpanIDToSpanNodeMap,- TraceRoots: copyOfTraceRoots,- HasMissingSpans: c.HasMissingSpans,- }-}--func (c *WaterfallCache) MarshalBinary() (data []byte, err error) {- return json.Marshal(c)-}--func (c *WaterfallCache) UnmarshalBinary(data []byte) error {- return json.Unmarshal(data, c)-}diff --git a/pkg/types/tracedetailtypes/waterfall_span.go b/pkg/types/tracedetailtypes/waterfall_span.gonew file mode 100644index 0000000000..28ca5fa4a6--- /dev/null+++ b/pkg/types/tracedetailtypes/waterfall_span.go@@ -0,0 +1,272 @@+package tracedetailtypes++import (+ "encoding/json"+ "maps"+ "sort"+ "time"++ "github.com/SigNoz/signoz/pkg/errors"+)++const (+ // ClickHouse database and table names for trace queries.+ TraceDB = "signoz_traces"+ TraceTable = "distributed_signoz_index_v3"+ TraceSummaryTable = "distributed_trace_summary"+)++// ErrTraceNotFound is returned when a trace ID has no matching spans in ClickHouse.+var ErrTraceNotFound = errors.NewNotFoundf(errors.CodeNotFound, "trace not found")++// PostableWaterfall is the request body for the v3 waterfall API.+type PostableWaterfall struct {+ SelectedSpanID string `json:"selectedSpanId"`+ UncollapsedSpans []string `json:"uncollapsedSpans"`+ Limit uint `json:"limit"`+}++// Event represents a span event.+type Event struct {+ Name string `json:"name,omitempty"`+ TimeUnixNano uint64 `json:"timeUnixNano,omitempty"`+ AttributeMap map[string]any `json:"attributeMap,omitempty"`+ IsError bool `json:"isError,omitempty"`+}++// WaterfallSpan represents the span in waterfall response,+// this uses snake_case keys for response as a special case since these+// keys can be directly used to query spans and client need to know the actual fields.+// This pattern should not be copied elsewhere.+type WaterfallSpan struct {+ Attributes map[string]any `json:"attributes"`+ DurationNano uint64 `json:"duration_nano"`+ Events []Event `json:"events"`+ Flags uint32 `json:"flags"`+ HasError bool `json:"has_error"`+ IsRemote string `json:"is_remote"`+ Kind int32 `json:"-"`+ KindString string `json:"kind_string"`+ Name string `json:"name"`+ ParentSpanID string `json:"parent_span_id"`+ Resource map[string]string `json:"resource"`+ SpanID string `json:"span_id"`+ TimeUnixNano uint64 `json:"-"`+ TraceID string `json:"trace_id"`+ TraceState string `json:"trace_state"`++ // Calculated fields https://signoz.io/docs/traces-management/guides/derived-fields-spans+ DBName string `json:"db_name,omitempty"`+ DBOperation string `json:"db_operation,omitempty"`+ ExternalHTTPMethod string `json:"external_http_method,omitempty"`+ ExternalHTTPURL string `json:"external_http_url,omitempty"`+ HTTPHost string `json:"http_host,omitempty"`+ HTTPMethod string `json:"http_method,omitempty"`+ HTTPURL string `json:"http_url,omitempty"`+ ResponseStatusCode string `json:"response_status_code,omitempty"`+ StatusCode int16 `json:"status_code,omitempty"`+ StatusCodeString string `json:"status_code_string,omitempty"`+ StatusMessage string `json:"status_message,omitempty"`++ // Internal tree structure fields+ Children []*WaterfallSpan `json:"-"`+ SubTreeNodeCount uint64 `json:"sub_tree_node_count"`+ HasChildren bool `json:"has_children"`+ Level uint64 `json:"level"`++ // used only for service time calculation+ ServiceName string `json:"-"`+}++// StorableSpan is the ClickHouse scan struct for the v3 waterfall query.+type StorableSpan struct {+ StartTime time.Time `ch:"timestamp"`+ DurationNano uint64 `ch:"duration_nano"`+ SpanID string `ch:"span_id"`+ TraceID string `ch:"trace_id"`+ HasError bool `ch:"has_error"`+ Kind int8 `ch:"kind"`+ ServiceName string `ch:"resource_string_service$$name"`+ Name string `ch:"name"`+ References string `ch:"references"`+ AttributesString map[string]string `ch:"attributes_string"`+ AttributesNumber map[string]float64 `ch:"attributes_number"`+ AttributesBool map[string]bool `ch:"attributes_bool"`+ ResourcesString map[string]string `ch:"resources_string"`+ Events []string `ch:"events"`+ StatusMessage string `ch:"status_message"`+ StatusCodeString string `ch:"status_code_string"`+ SpanKind string `ch:"kind_string"`+ ParentSpanID string `ch:"parent_span_id"`+ Flags uint32 `ch:"flags"`+ IsRemote string `ch:"is_remote"`+ TraceState string `ch:"trace_state"`+ StatusCode int16 `ch:"status_code"`+ DBName string `ch:"db_name"`+ DBOperation string `ch:"db_operation"`+ HTTPMethod string `ch:"http_method"`+ HTTPURL string `ch:"http_url"`+ HTTPHost string `ch:"http_host"`+ ExternalHTTPMethod string `ch:"external_http_method"`+ ExternalHTTPURL string `ch:"external_http_url"`+ ResponseStatusCode string `ch:"response_status_code"`+}++// NewMissingWaterfallSpan creates a synthetic placeholder span for a parent that has no recorded data.+func NewMissingWaterfallSpan(spanID, traceID string, timeUnixNano, durationNano uint64) *WaterfallSpan {+ return &WaterfallSpan{+ SpanID: spanID,+ TraceID: traceID,+ Name: "Missing Span",+ TimeUnixNano: timeUnixNano,+ DurationNano: durationNano,+ Events: make([]Event, 0),+ Children: make([]*WaterfallSpan, 0),+ Attributes: make(map[string]any),+ Resource: make(map[string]string),+ }+}++// SortChildren recursively sorts children of each span by TimeUnixNano then Name.+func (ws *WaterfallSpan) SortChildren() {+ sort.Slice(ws.Children, func(i, j int) bool {+ if ws.Children[i].TimeUnixNano == ws.Children[j].TimeUnixNano {+ return ws.Children[i].Name < ws.Children[j].Name+ }+ return ws.Children[i].TimeUnixNano < ws.Children[j].TimeUnixNano+ })+ for _, child := range ws.Children {+ child.SortChildren()+ }+}++// GetWithoutChildren creates a shallow copy and resets tree-structure fields.+// SubTreeNodeCount is preserved (must be pre-computed via computeSubTreeNodeCount).+func (ws *WaterfallSpan) GetWithoutChildren(level uint64) *WaterfallSpan {+ cp := *ws+ cp.Level = level+ cp.HasChildren = len(ws.Children) > 0+ cp.Children = make([]*WaterfallSpan, 0)+ return &cp+}++// GetSubtreeNodeCount recursively sets SubTreeNodeCount on every span in the subtree.+func (ws *WaterfallSpan) GetSubtreeNodeCount() uint64 {+ count := uint64(1)+ for _, child := range ws.Children {+ count += child.GetSubtreeNodeCount()+ }+ ws.SubTreeNodeCount = count+ return count+}++// getPreOrderedSpans returns spans in pre-order, uncollapsedSpanIDs must be pre-computed.+func (ws *WaterfallSpan) getPreOrderedSpans(uncollapsedSpanIDs map[string]struct{}, selectAll bool, level uint64) []*WaterfallSpan {+ result := []*WaterfallSpan{ws.GetWithoutChildren(level)}+ _, isUncollapsed := uncollapsedSpanIDs[ws.SpanID]+ if selectAll || isUncollapsed {+ for _, child := range ws.Children {+ result = append(result, child.getPreOrderedSpans(uncollapsedSpanIDs, selectAll, level+1)...)+ }+ }+ return result+}++// autoExpandDescendants marks spans within depth levels below span as uncollapsed.+func (ws *WaterfallSpan) autoExpandDescendants(remainingDepth int, uncollapsedMap map[string]struct{}) {+ if remainingDepth <= 0 || len(ws.Children) == 0 { // leaves have nothing to expand+ return+ }+ uncollapsedMap[ws.SpanID] = struct{}{}+ for _, child := range ws.Children {+ child.autoExpandDescendants(remainingDepth-1, uncollapsedMap)+ }+}++func (ws *WaterfallSpan) getPathToSelectedSpanID(selectedSpanID string) ([]string, bool) {+ path := []string{ws.SpanID}+ if ws.SpanID == selectedSpanID {+ return path, true+ }++ for _, child := range ws.Children {+ childPath, found := child.getPathToSelectedSpanID(selectedSpanID)+ if found {+ path = append(path, childPath...)+ return path, true+ }+ }+ return nil, false+}++func (item *StorableSpan) Attributes() map[string]any {+ attributes := make(map[string]any, len(item.AttributesString)+len(item.AttributesNumber)+len(item.AttributesBool))+ for k, v := range item.AttributesString {+ attributes[k] = v+ }+ for k, v := range item.AttributesNumber {+ attributes[k] = v+ }+ for k, v := range item.AttributesBool {+ attributes[k] = v+ }+ return attributes+}++func (item *StorableSpan) UnmarshalledEvents() []Event {+ events := make([]Event, 0, len(item.Events))+ for _, eventStr := range item.Events {+ var event Event+ if err := json.Unmarshal([]byte(eventStr), &event); err != nil {+ continue // skipping malformed events+ }+ events = append(events, event)+ }+ return events+}++func (item *StorableSpan) ToWaterfallSpan() *WaterfallSpan {+ resources := make(map[string]string)+ maps.Copy(resources, item.ResourcesString)++ return &WaterfallSpan{+ Attributes: item.Attributes(),+ DBName: item.DBName,+ DBOperation: item.DBOperation,+ DurationNano: item.DurationNano,+ Events: item.UnmarshalledEvents(),+ ExternalHTTPMethod: item.ExternalHTTPMethod,+ ExternalHTTPURL: item.ExternalHTTPURL,+ Flags: item.Flags,+ HasError: item.HasError,+ HTTPHost: item.HTTPHost,+ HTTPMethod: item.HTTPMethod,+ HTTPURL: item.HTTPURL,+ IsRemote: item.IsRemote,+ Kind: int32(item.Kind),+ KindString: item.SpanKind,+ Name: item.Name,+ ParentSpanID: item.ParentSpanID,+ Resource: resources,+ ResponseStatusCode: item.ResponseStatusCode,+ SpanID: item.SpanID,+ StatusCode: item.StatusCode,+ StatusCodeString: item.StatusCodeString,+ StatusMessage: item.StatusMessage,+ TraceID: item.TraceID,+ TraceState: item.TraceState,+ Children: make([]*WaterfallSpan, 0),+ TimeUnixNano: uint64(item.StartTime.UnixNano()),+ ServiceName: item.ServiceName,+ }+}++// getSpanIndex returns the index of matched span and -1 for no match.+func getSpanIndex(spans []*WaterfallSpan, targetSpanID string) int {+ for i, s := range spans {+ if s != nil && s.SpanID == targetSpanID {+ return i+ }+ }+ return -1+}diff --git a/pkg/types/tracedetailtypes/waterfall_trace.go b/pkg/types/tracedetailtypes/waterfall_trace.gonew file mode 100644index 0000000000..7e808a0441--- /dev/null+++ b/pkg/types/tracedetailtypes/waterfall_trace.go@@ -0,0 +1,335 @@+package tracedetailtypes++import (+ "encoding/json"+ "maps"+ "slices"+ "sort"+ "time"++ "github.com/SigNoz/signoz/pkg/types/cachetypes"+)++type TraceSummary struct {+ TraceID string `ch:"trace_id"`+ Start time.Time `ch:"start"`+ End time.Time `ch:"end"`+ NumSpans uint64 `ch:"num_spans"`+}++// WaterfallTrace holds processed trace data with childern populated in spans.+type WaterfallTrace struct {+ StartTime uint64 `json:"startTime"`+ EndTime uint64 `json:"endTime"`+ TotalSpans uint64 `json:"totalSpans"`+ TotalErrorSpans uint64 `json:"totalErrorSpans"`+ ServiceNameToTotalDurationMap map[string]uint64 `json:"serviceNameToTotalDurationMap"`+ SpanIDToSpanNodeMap map[string]*WaterfallSpan `json:"spanIdToSpanNodeMap"`+ TraceRoots []*WaterfallSpan `json:"traceRoots"`+ HasMissingSpans bool `json:"hasMissingSpans"`+}++// GettableWaterfallTrace is the response for the v3 waterfall API.+type GettableWaterfallTrace struct {+ StartTimestampMillis uint64 `json:"startTimestampMillis"`+ EndTimestampMillis uint64 `json:"endTimestampMillis"`+ RootServiceName string `json:"rootServiceName"`+ RootServiceEntryPoint string `json:"rootServiceEntryPoint"`+ TotalSpansCount uint64 `json:"totalSpansCount"`+ TotalErrorSpansCount uint64 `json:"totalErrorSpansCount"`+ ServiceNameToTotalDurationMap map[string]uint64 `json:"serviceNameToTotalDurationMap"`+ Spans []*WaterfallSpan `json:"spans"`+ HasMissingSpans bool `json:"hasMissingSpans"`+ UncollapsedSpans []string `json:"uncollapsedSpans"`+ HasMore bool `json:"hasMore"`+}++// NewWaterfallTrace constructs a WaterfallTrace from processed span data.+func NewWaterfallTrace(+ startTime, endTime, totalSpans, totalErrorSpans uint64,+ spanIDToSpanNodeMap map[string]*WaterfallSpan,+ serviceNameToTotalDurationMap map[string]uint64,+ traceRoots []*WaterfallSpan,+ hasMissingSpans bool,+) *WaterfallTrace {+ return &WaterfallTrace{+ StartTime: startTime,+ EndTime: endTime,+ TotalSpans: totalSpans,+ TotalErrorSpans: totalErrorSpans,+ SpanIDToSpanNodeMap: spanIDToSpanNodeMap,+ ServiceNameToTotalDurationMap: serviceNameToTotalDurationMap,+ TraceRoots: traceRoots,+ HasMissingSpans: hasMissingSpans,+ }+}++func NewWaterfallTraceFromSpans(spans []StorableSpan) *WaterfallTrace {+ var (+ startTime, endTime, totalErrorSpans uint64+ spanIDToSpanNodeMap = make(map[string]*WaterfallSpan, len(spans))+ traceRoots []*WaterfallSpan+ hasMissingSpans bool+ )++ for _, item := range spans {+ span := item.ToWaterfallSpan()+ startTimeUnixNano := uint64(item.StartTime.UnixNano())+ if startTime == 0 || startTimeUnixNano < startTime {+ startTime = startTimeUnixNano+ }+ endTime = max(endTime, startTimeUnixNano+span.DurationNano)++ if span.HasError {+ totalErrorSpans+++ }++ spanIDToSpanNodeMap[span.SpanID] = span+ }++ for _, spanNode := range spanIDToSpanNodeMap {+ if spanNode.ParentSpanID != "" {+ if parentNode, exists := spanIDToSpanNodeMap[spanNode.ParentSpanID]; exists {+ parentNode.Children = append(parentNode.Children, spanNode)+ } else {+ missingSpan := NewMissingWaterfallSpan(spanNode.ParentSpanID, spanNode.TraceID, spanNode.TimeUnixNano, spanNode.DurationNano)+ missingSpan.Children = append(missingSpan.Children, spanNode)+ spanIDToSpanNodeMap[missingSpan.SpanID] = missingSpan+ traceRoots = append(traceRoots, missingSpan)+ hasMissingSpans = true+ }+ } else if getSpanIndex(traceRoots, spanNode.SpanID) == -1 {+ traceRoots = append(traceRoots, spanNode)+ }+ }++ for _, root := range traceRoots {+ root.SortChildren()+ root.GetSubtreeNodeCount()+ }++ sort.Slice(traceRoots, func(i, j int) bool {+ if traceRoots[i].TimeUnixNano == traceRoots[j].TimeUnixNano {+ return traceRoots[i].Name < traceRoots[j].Name+ }+ return traceRoots[i].TimeUnixNano < traceRoots[j].TimeUnixNano+ })++ return NewWaterfallTrace(+ startTime,+ endTime,+ uint64(len(spans)),+ totalErrorSpans,+ spanIDToSpanNodeMap,+ calculateServiceTime(spanIDToSpanNodeMap),+ traceRoots,+ hasMissingSpans,+ )+}++func (wt *WaterfallTrace) GetWaterfallSpans(uncollapsedSpanIDs []string, selectedSpanID string, limit uint, spanPageSize float64, maxDepthToAutoExpand int) ([]*WaterfallSpan, []string, bool) {+ // Span selection decision: all spans or windowed+ selectAllSpans := wt.TotalSpans <= uint64(limit)++ var (+ selectedSpans []*WaterfallSpan+ uncollapsedSpans []string+ )++ if selectAllSpans {+ selectedSpans = wt.GetAllSpans()+ } else {+ selectedSpans, uncollapsedSpans = wt.GetSelectedSpans(uncollapsedSpanIDs, selectedSpanID, spanPageSize, maxDepthToAutoExpand)+ }+ return selectedSpans, uncollapsedSpans, selectAllSpans+}++// GetAllSpans returns all spans with pre order traversal.+func (wt *WaterfallTrace) GetAllSpans() []*WaterfallSpan {+ var preOrderedSpans []*WaterfallSpan+ for _, root := range wt.TraceRoots {+ preOrderedSpans = append(preOrderedSpans, root.getPreOrderedSpans(nil, true, 0)...)+ }+ return preOrderedSpans+}++// GetSelectedSpans returns a window of spans around selectedSpanID with pre order traversal.+func (wt *WaterfallTrace) GetSelectedSpans(uncollapsedSpanIDs []string, selectedSpanID string, spanLimitPerRequest float64, maxDepthForSelectedChildren int) ([]*WaterfallSpan, []string) {+ uncollapsedSpanIDsMap := wt.CalculateUncollapsedSpanIDs(uncollapsedSpanIDs, selectedSpanID, maxDepthForSelectedChildren)++ var (+ preOrderedSpans []*WaterfallSpan+ selectedSpanIndex = -1+ )+ for _, root := range wt.TraceRoots {+ preOrderedSpansForRoot := root.getPreOrderedSpans(uncollapsedSpanIDsMap, false, 0)+ if idx := getSpanIndex(preOrderedSpansForRoot, selectedSpanID); idx != -1 {+ selectedSpanIndex = idx + len(preOrderedSpans)+ }+ preOrderedSpans = append(preOrderedSpans, preOrderedSpansForRoot...)+ }+ startIndex, endIndex := windowAroundIndex(selectedSpanIndex, len(preOrderedSpans), spanLimitPerRequest)+ return preOrderedSpans[startIndex:endIndex], slices.Collect(maps.Keys(uncollapsedSpanIDsMap))+}++// CalculateUncollapsedSpanIDs returns the full set of span IDs that should be uncollapsed,+// merging three sources:+// 1. Caller-supplied uncollapsedSpanIDs (explicit user state)+// 2. Every ancestor of selectedSpanID (so the selected span is always visible)+// 3. Up to maxDepthForSelectedChildren levels of descendants below selectedSpanID,+// when selectedSpanID is itself already uncollapsed (auto-expansion).+func (wt *WaterfallTrace) CalculateUncollapsedSpanIDs(uncollapsedSpanIDs []string, selectedSpanID string, maxDepthForSelectedChildren int) map[string]struct{} {+ uncollapsedSpanMap := make(map[string]struct{}, len(uncollapsedSpanIDs))+ for _, spanID := range uncollapsedSpanIDs {+ uncollapsedSpanMap[spanID] = struct{}{}+ }++ // Uncollapse every ancestor so the selected span is reachable in the tree.+ path, _ := wt.getPathFromRoot(selectedSpanID)+ for _, spanID := range path {+ if spanID != selectedSpanID {+ uncollapsedSpanMap[spanID] = struct{}{}+ }+ }++ // Auto-expand children of the selected span when it is already uncollapsed.+ if _, isUncollapsed := uncollapsedSpanMap[selectedSpanID]; isUncollapsed {+ if selectedSpan, exists := wt.SpanIDToSpanNodeMap[selectedSpanID]; exists {+ selectedSpan.autoExpandDescendants(maxDepthForSelectedChildren, uncollapsedSpanMap)+ }+ }++ return uncollapsedSpanMap+}++func (wt *WaterfallTrace) Clone() cachetypes.Cacheable {+ copyOfServiceNameToTotalDurationMap := make(map[string]uint64)+ maps.Copy(copyOfServiceNameToTotalDurationMap, wt.ServiceNameToTotalDurationMap)++ copyOfSpanIDToSpanNodeMap := make(map[string]*WaterfallSpan)+ maps.Copy(copyOfSpanIDToSpanNodeMap, wt.SpanIDToSpanNodeMap)++ copyOfTraceRoots := make([]*WaterfallSpan, len(wt.TraceRoots))+ copy(copyOfTraceRoots, wt.TraceRoots)+ return &WaterfallTrace{+ StartTime: wt.StartTime,+ EndTime: wt.EndTime,+ TotalSpans: wt.TotalSpans,+ TotalErrorSpans: wt.TotalErrorSpans,+ ServiceNameToTotalDurationMap: copyOfServiceNameToTotalDurationMap,+ SpanIDToSpanNodeMap: copyOfSpanIDToSpanNodeMap,+ TraceRoots: copyOfTraceRoots,+ HasMissingSpans: wt.HasMissingSpans,+ }+}++func (wt *WaterfallTrace) getPathFromRoot(selectedSpanID string) ([]string, bool) {+ for _, root := range wt.TraceRoots {+ if path, found := root.getPathToSelectedSpanID(selectedSpanID); found {+ return path, found+ }+ }+ return nil, false+}++func (wt *WaterfallTrace) MarshalBinary() (data []byte, err error) {+ return json.Marshal(wt)+}++func (wt *WaterfallTrace) UnmarshalBinary(data []byte) error {+ return json.Unmarshal(data, wt)+}++// NewGettableWaterfallTrace constructs a WaterfallResponse from processed trace data and selected spans.+func NewGettableWaterfallTrace(+ traceData *WaterfallTrace,+ selectedSpans []*WaterfallSpan,+ uncollapsedSpans []string,+ selectAllSpans bool,+) *GettableWaterfallTrace {+ var rootServiceName, rootServiceEntryPoint string+ if len(traceData.TraceRoots) > 0 {+ rootServiceName = traceData.TraceRoots[0].ServiceName+ rootServiceEntryPoint = traceData.TraceRoots[0].Name+ }++ serviceDurationsMillis := make(map[string]uint64, len(traceData.ServiceNameToTotalDurationMap))+ for svc, dur := range traceData.ServiceNameToTotalDurationMap {+ serviceDurationsMillis[svc] = dur / 1_000_000+ }++ // convert start timestamp to millis because client is expecting it in millis+ for _, span := range selectedSpans {+ span.TimeUnixNano = span.TimeUnixNano / 1_000_000+ }++ return &GettableWaterfallTrace{+ Spans: selectedSpans,+ UncollapsedSpans: uncollapsedSpans,+ StartTimestampMillis: traceData.StartTime / 1_000_000,+ EndTimestampMillis: traceData.EndTime / 1_000_000,+ TotalSpansCount: traceData.TotalSpans,+ TotalErrorSpansCount: traceData.TotalErrorSpans,+ RootServiceName: rootServiceName,+ RootServiceEntryPoint: rootServiceEntryPoint,+ ServiceNameToTotalDurationMap: serviceDurationsMillis,+ HasMissingSpans: traceData.HasMissingSpans,+ HasMore: !selectAllSpans,+ }+}++// windowAroundIndex returns start/end indices for a window of spanLimitPerRequest spans.+func windowAroundIndex(selectedIndex, total int, spanLimitPerRequest float64) (start, end int) {+ selectedIndex = max(selectedIndex, 0)++ start = selectedIndex - int(spanLimitPerRequest*0.4)+ end = selectedIndex + int(spanLimitPerRequest*0.6)++ if start < 0 {+ end = end - start+ start = 0+ }+ if end > total {+ start = start - (end - total)+ end = total+ }+ start = max(start, 0)+ return+}++func calculateServiceTime(spanIDToSpanNodeMap map[string]*WaterfallSpan) map[string]uint64 {+ serviceSpans := make(map[string][]*WaterfallSpan)+ for _, span := range spanIDToSpanNodeMap {+ if span.ServiceName != "" {+ serviceSpans[span.ServiceName] = append(serviceSpans[span.ServiceName], span)+ }+ }++ totalTimes := make(map[string]uint64)+ for service, spans := range serviceSpans {+ sort.Slice(spans, func(i, j int) bool {+ return spans[i].TimeUnixNano < spans[j].TimeUnixNano+ })++ currentStart := spans[0].TimeUnixNano+ currentEnd := currentStart + spans[0].DurationNano+ total := uint64(0)++ for _, span := range spans[1:] {+ startNano := span.TimeUnixNano+ endNano := startNano + span.DurationNano+ if currentEnd >= startNano {+ if endNano > currentEnd {+ currentEnd = endNano+ }+ } else {+ total += currentEnd - currentStart+ currentStart = startNano+ currentEnd = endNano+ }+ }+ total += currentEnd - currentStart+ totalTimes[service] = total+ }+ return totalTimes+}