mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 05:30:41 +00:00
Compare commits
75 Commits
chore/dead
...
issue_nerv
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a64e85459 | ||
|
|
c5b98e86c1 | ||
|
|
82617fac20 | ||
|
|
8f12a9c99d | ||
|
|
133ac48aaf | ||
|
|
a676fd3fca | ||
|
|
2ad6292730 | ||
|
|
22739f406b | ||
|
|
d38d9c10a3 | ||
|
|
7e6eba82bd | ||
|
|
b41341a87d | ||
|
|
14f8a813c4 | ||
|
|
142b98a31e | ||
|
|
687ce8c5d6 | ||
|
|
31644c65ba | ||
|
|
3593339907 | ||
|
|
88ed8d6e2a | ||
|
|
a8d30be82e | ||
|
|
4171a5835a | ||
|
|
736d108485 | ||
|
|
b339f056e2 | ||
|
|
98c709e362 | ||
|
|
dd81355d60 | ||
|
|
536fe6c065 | ||
|
|
0e000f6a00 | ||
|
|
a527841297 | ||
|
|
dc57e60a73 | ||
|
|
080291be69 | ||
|
|
935ad00c12 | ||
|
|
8fc0d1e775 | ||
|
|
0bac4990ef | ||
|
|
f028897749 | ||
|
|
f4023c9f6f | ||
|
|
791d150554 | ||
|
|
56a3148a77 | ||
|
|
af7d1d31fd | ||
|
|
eed2c7d177 | ||
|
|
ff3bff481a | ||
|
|
5902ba86c4 | ||
|
|
5870d1f2b5 | ||
|
|
d63c6fb344 | ||
|
|
9341922a83 | ||
|
|
015e0ab502 | ||
|
|
af8e036412 | ||
|
|
94ead23432 | ||
|
|
9ed59f872b | ||
|
|
63caf73fdb | ||
|
|
9ef7def96c | ||
|
|
d2ca350b51 | ||
|
|
478a7645e4 | ||
|
|
1d0b83cb6d | ||
|
|
6f5d3af7f7 | ||
|
|
b0386a0850 | ||
|
|
ca4f2f5236 | ||
|
|
9777092344 | ||
|
|
de7a4c084c | ||
|
|
eaf4cb9a81 | ||
|
|
0acf668098 | ||
|
|
f0868980ac | ||
|
|
4d3edfc60f | ||
|
|
d79b50e6fc | ||
|
|
122a28eecc | ||
|
|
319149f3f9 | ||
|
|
3ad9300dd3 | ||
|
|
de2f960771 | ||
|
|
9e5e145b46 | ||
|
|
e892107960 | ||
|
|
273ec41fb3 | ||
|
|
b81bbea9f1 | ||
|
|
8954823bf9 | ||
|
|
08cca0f59b | ||
|
|
690a2af781 | ||
|
|
82c8c1c43d | ||
|
|
75686f4004 | ||
|
|
2df97d39e2 |
@@ -13065,6 +13065,12 @@ components:
|
||||
additionalProperties: {}
|
||||
description: All of them for a span read by ID; the selected ones in a list.
|
||||
type: object
|
||||
db_name:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
db_operation:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
duration_nano:
|
||||
minimum: 0
|
||||
type: integer
|
||||
@@ -13073,8 +13079,26 @@ components:
|
||||
items:
|
||||
$ref: '#/components/schemas/SpantypesEvent'
|
||||
type: array
|
||||
external_http_method:
|
||||
description: Method of an outgoing HTTP call. Omitted when empty, and in
|
||||
a list unless selected.
|
||||
type: string
|
||||
external_http_url:
|
||||
description: Host of an outgoing HTTP call. Omitted when empty, and in a
|
||||
list unless selected.
|
||||
type: string
|
||||
has_error:
|
||||
type: boolean
|
||||
http_host:
|
||||
description: Host or server address. Omitted when empty, and in a list unless
|
||||
selected.
|
||||
type: string
|
||||
http_method:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
http_url:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
kind_string:
|
||||
description: For example Server, Client or Internal.
|
||||
type: string
|
||||
@@ -13097,6 +13121,11 @@ components:
|
||||
response_status_code:
|
||||
description: HTTP or gRPC status code, for example 404.
|
||||
type: string
|
||||
scope:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SpantypesScope'
|
||||
description: Instrumentation scope. Omitted when empty, and in a list unless
|
||||
selected.
|
||||
span_id:
|
||||
type: string
|
||||
status_code_string:
|
||||
@@ -13110,6 +13139,9 @@ components:
|
||||
type: integer
|
||||
trace_id:
|
||||
type: string
|
||||
trace_state:
|
||||
description: W3C trace state. Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
required:
|
||||
- span_id
|
||||
- trace_id
|
||||
@@ -13163,8 +13195,8 @@ components:
|
||||
SpantypesSpanItem:
|
||||
properties:
|
||||
matches:
|
||||
description: Where the query's words were found, up to three places. Omitted
|
||||
when the query has no words.
|
||||
description: Where the query's search() text was found, up to three places.
|
||||
Omitted when the query has no search().
|
||||
items:
|
||||
$ref: '#/components/schemas/SpantypesSpanTextMatch'
|
||||
type: array
|
||||
@@ -19767,15 +19799,17 @@ paths:
|
||||
span per same-name sibling group, by the group''s own time. ai_usage:
|
||||
spans with gen_ai token or cost usage, with those attributes, by cost,
|
||||
else tokens. links: spans that link to other spans.'
|
||||
- description: 'Words, a filter expression, or both, for example: worldpay AND
|
||||
has_error = true. Words match the name, status message, attributes, resource
|
||||
attributes and events, ignoring case. Applied before view.'
|
||||
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
|
||||
= true. search() matches text, ignoring case, in the name, status message,
|
||||
attributes, resource attributes and events; a second argument limits it
|
||||
to span, attribute, resource or event. Applied before view.'
|
||||
in: query
|
||||
name: query
|
||||
schema:
|
||||
description: 'Words, a filter expression, or both, for example: worldpay
|
||||
AND has_error = true. Words match the name, status message, attributes,
|
||||
resource attributes and events, ignoring case. Applied before view.'
|
||||
description: 'A filter expression, for example: search(''worldpay'') AND
|
||||
has_error = true. search() matches text, ignoring case, in the name, status
|
||||
message, attributes, resource attributes and events; a second argument
|
||||
limits it to span, attribute, resource or event. Applied before view.'
|
||||
type: string
|
||||
- description: 'Attributes or resource attributes to add to each span, for example
|
||||
http.route or resource.k8s.pod.name. Default: service.name only.'
|
||||
@@ -19953,15 +19987,17 @@ paths:
|
||||
span per same-name sibling group, by the group''s own time. ai_usage:
|
||||
spans with gen_ai token or cost usage, with those attributes, by cost,
|
||||
else tokens. links: spans that link to other spans.'
|
||||
- description: 'Words, a filter expression, or both, for example: worldpay AND
|
||||
has_error = true. Words match the name, status message, attributes, resource
|
||||
attributes and events, ignoring case. Applied before view.'
|
||||
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
|
||||
= true. search() matches text, ignoring case, in the name, status message,
|
||||
attributes, resource attributes and events; a second argument limits it
|
||||
to span, attribute, resource or event. Applied before view.'
|
||||
in: query
|
||||
name: query
|
||||
schema:
|
||||
description: 'Words, a filter expression, or both, for example: worldpay
|
||||
AND has_error = true. Words match the name, status message, attributes,
|
||||
resource attributes and events, ignoring case. Applied before view.'
|
||||
description: 'A filter expression, for example: search(''worldpay'') AND
|
||||
has_error = true. search() matches text, ignoring case, in the name, status
|
||||
message, attributes, resource attributes and events; a second argument
|
||||
limits it to span, attribute, resource or event. Applied before view.'
|
||||
type: string
|
||||
- description: 'Attributes or resource attributes to add to each span, for example
|
||||
http.route or resource.k8s.pod.name. Default: service.name only.'
|
||||
@@ -20076,15 +20112,17 @@ paths:
|
||||
span per same-name sibling group, by the group''s own time. ai_usage:
|
||||
spans with gen_ai token or cost usage, with those attributes, by cost,
|
||||
else tokens. links: spans that link to other spans.'
|
||||
- description: 'Words, a filter expression, or both, for example: worldpay AND
|
||||
has_error = true. Words match the name, status message, attributes, resource
|
||||
attributes and events, ignoring case. Applied before view.'
|
||||
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
|
||||
= true. search() matches text, ignoring case, in the name, status message,
|
||||
attributes, resource attributes and events; a second argument limits it
|
||||
to span, attribute, resource or event. Applied before view.'
|
||||
in: query
|
||||
name: query
|
||||
schema:
|
||||
description: 'Words, a filter expression, or both, for example: worldpay
|
||||
AND has_error = true. Words match the name, status message, attributes,
|
||||
resource attributes and events, ignoring case. Applied before view.'
|
||||
description: 'A filter expression, for example: search(''worldpay'') AND
|
||||
has_error = true. search() matches text, ignoring case, in the name, status
|
||||
message, attributes, resource attributes and events; a second argument
|
||||
limits it to span, attribute, resource or event. Applied before view.'
|
||||
type: string
|
||||
- description: 'Attributes or resource attributes to add to each span, for example
|
||||
http.route or resource.k8s.pod.name. Default: service.name only.'
|
||||
@@ -20199,15 +20237,17 @@ paths:
|
||||
span per same-name sibling group, by the group''s own time. ai_usage:
|
||||
spans with gen_ai token or cost usage, with those attributes, by cost,
|
||||
else tokens. links: spans that link to other spans.'
|
||||
- description: 'Words, a filter expression, or both, for example: worldpay AND
|
||||
has_error = true. Words match the name, status message, attributes, resource
|
||||
attributes and events, ignoring case. Applied before view.'
|
||||
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
|
||||
= true. search() matches text, ignoring case, in the name, status message,
|
||||
attributes, resource attributes and events; a second argument limits it
|
||||
to span, attribute, resource or event. Applied before view.'
|
||||
in: query
|
||||
name: query
|
||||
schema:
|
||||
description: 'Words, a filter expression, or both, for example: worldpay
|
||||
AND has_error = true. Words match the name, status message, attributes,
|
||||
resource attributes and events, ignoring case. Applied before view.'
|
||||
description: 'A filter expression, for example: search(''worldpay'') AND
|
||||
has_error = true. search() matches text, ignoring case, in the name, status
|
||||
message, attributes, resource attributes and events; a second argument
|
||||
limits it to span, attribute, resource or event. Applied before view.'
|
||||
type: string
|
||||
- description: 'Attributes or resource attributes to add to each span, for example
|
||||
http.route or resource.k8s.pod.name. Default: service.name only.'
|
||||
|
||||
@@ -14681,6 +14681,16 @@ export interface SpantypesSpanDTO {
|
||||
* @description All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
attributes: SpantypesSpanDTOAttributes;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
db_name?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
db_operation?: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
@@ -14691,10 +14701,35 @@ export interface SpantypesSpanDTO {
|
||||
* @description All of them for a span read by ID; none in a list.
|
||||
*/
|
||||
events: SpantypesEventDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @description Method of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
external_http_method?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Host of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
external_http_url?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
has_error: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description Host or server address. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_host?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_method?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_url?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description For example Server, Client or Internal.
|
||||
@@ -14724,6 +14759,10 @@ export interface SpantypesSpanDTO {
|
||||
* @description HTTP or gRPC status code, for example 404.
|
||||
*/
|
||||
response_status_code: string;
|
||||
/**
|
||||
* @description Instrumentation scope. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
scope?: SpantypesScopeDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -14747,6 +14786,11 @@ export interface SpantypesSpanDTO {
|
||||
* @type string
|
||||
*/
|
||||
trace_id: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description W3C trace state. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
trace_state?: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTextMatchDTO {
|
||||
@@ -14807,7 +14851,7 @@ export enum SpantypesUnmarkedFailureKindDTO {
|
||||
export interface SpantypesSpanItemDTO {
|
||||
/**
|
||||
* @type array
|
||||
* @description Where the query's words were found, up to three places. Omitted when the query has no words.
|
||||
* @description Where the query's search() text was found, up to three places. Omitted when the query has no search().
|
||||
*/
|
||||
matches?: SpantypesSpanTextMatchDTO[];
|
||||
span: SpantypesSpanDTO;
|
||||
@@ -16393,7 +16437,7 @@ export type ListTraceSpansParams = {
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
@@ -16444,7 +16488,7 @@ export type ListTraceSpanAncestorsParams = {
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
@@ -16483,7 +16527,7 @@ export type ListTraceSpanChildrenParams = {
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
@@ -16522,7 +16566,7 @@ export type ListTraceSpanDescendantsParams = {
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,6 @@ package impltracedetail
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/http/binding"
|
||||
"github.com/SigNoz/signoz/pkg/http/render"
|
||||
"github.com/SigNoz/signoz/pkg/modules/tracedetail"
|
||||
@@ -129,27 +128,84 @@ func (h *handler) GetThread(rw http.ResponseWriter, r *http.Request) {
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// These routes are registered for their place in the API spec; the implementation follows.
|
||||
func (h *handler) GetTraceHighlights(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace highlights is not implemented yet"))
|
||||
func (h *handler) GetTraceHighlights(rw http.ResponseWriter, r *http.Request) {
|
||||
claims, err := authtypes.ClaimsFromContext(r.Context())
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
params := new(spantypes.GetTraceHighlightsParams)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
query, err := spantypes.NewTraceHighlightsQuery(params)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.module.GetTraceHighlights(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], query)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpans(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span list is not implemented yet"))
|
||||
func (h *handler) GetTraceSpan(rw http.ResponseWriter, r *http.Request) {
|
||||
result, err := h.module.GetTraceSpan(r.Context(), mux.Vars(r)["traceID"], mux.Vars(r)["spanID"])
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (h *handler) GetTraceSpan(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span is not implemented yet"))
|
||||
func (h *handler) ListTraceSpans(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeTrace)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanChildren(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span children is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanChildren(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeChildren)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanDescendants(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span descendants is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanDescendants(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeDescendants)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanAncestors(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span ancestors is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanAncestors(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeAncestors)
|
||||
}
|
||||
|
||||
func (h *handler) listTraceSpans(rw http.ResponseWriter, r *http.Request, scope spantypes.SpanScope) {
|
||||
claims, err := authtypes.ClaimsFromContext(r.Context())
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
params := new(spantypes.ListTraceSpansParams)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
query, err := spantypes.NewSpanListQuery(params, scope, mux.Vars(r)["spanID"])
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.module.ListTraceSpans(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], query)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/modules/tracedetail"
|
||||
"github.com/SigNoz/signoz/pkg/types/spantypes"
|
||||
@@ -292,3 +293,63 @@ func (m *module) getWindowedFlamegraph(ctx context.Context, traceID, selectedSpa
|
||||
enrichedSpans := flamegraphTrace.EnrichSelectedSpans(selectedSpans, fullSpans, selectFields)
|
||||
return spantypes.NewGettableFlamegraphTrace(enrichedSpans, start, end, true), nil
|
||||
}
|
||||
|
||||
func (m *module) GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return spantypes.NewTraceHighlights(skeleton, query), nil
|
||||
}
|
||||
|
||||
func (m *module) GetTraceSpan(ctx context.Context, traceID string, spanID string) (*spantypes.Span, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, []string{spanID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, errors.NewNotFoundf(spantypes.ErrCodeTraceSpanNotFound, "span %s not found in trace %s", spanID, traceID)
|
||||
}
|
||||
return spantypes.NewSpan(traceID, &rows[0]), nil
|
||||
}
|
||||
|
||||
func (m *module) ListTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.SpanListQuery) (*spantypes.SpanList, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The search runs before the tree is loaded, so that a query that cannot be parsed fails early.
|
||||
var search *spantypes.SpanSearch
|
||||
if query.Query != "" {
|
||||
search, err = m.store.SearchTraceSpans(ctx, orgID, traceID, bounds, query.Query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, err := spantypes.NewSpanListPage(skeleton, query, search)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The full rows of the page's spans are read only for selected fields and for search() snippets.
|
||||
var rows []spantypes.StorableSpan
|
||||
if page.ReadsAttributes() {
|
||||
rows, err = m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, page.SpanIDs())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return spantypes.NewSpanList(page, rows), nil
|
||||
}
|
||||
|
||||
@@ -24,11 +24,26 @@ import (
|
||||
|
||||
const colServiceName = `resource_string_service$$$$name` // $ gets escaped so $$$$ converts to $$.
|
||||
|
||||
// The collector marks an exception event with isError when it writes the span.
|
||||
const colHasExceptionEvent = `(NOT has_error AND arrayExists(e -> position(e, '"isError":true') > 0, events)) AS has_exception_event`
|
||||
|
||||
// The collector writes a span link as a FOLLOWS_FROM reference; the parent is a CHILD_OF one.
|
||||
const colHasLink = `(position(links, '"refType":"FOLLOWS_FROM"') > 0) AS has_link`
|
||||
|
||||
var genAIUsageValues = []struct{ key, alias string }{
|
||||
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
|
||||
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
|
||||
}
|
||||
|
||||
// storableSpanColumns are the columns a waterfall span scans. A row's legacy maps are blanked when its
|
||||
// JSON holds the attributes.
|
||||
var storableSpanColumns = []string{
|
||||
"DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "has_error", "kind",
|
||||
colServiceName, "name", "attributes", "resources_string", "scope",
|
||||
colServiceName, "name", "attributes", "resource", "scope",
|
||||
"if(notEmpty(attributes), map(), attributes_string) AS attributes_string",
|
||||
"if(notEmpty(attributes), map(), attributes_number) AS attributes_number",
|
||||
"if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool",
|
||||
@@ -57,6 +72,10 @@ type spanDurationRow struct {
|
||||
TotalNs uint64 `ch:"total_ns"`
|
||||
}
|
||||
|
||||
type spanIDRow struct {
|
||||
SpanID string `ch:"span_id"`
|
||||
}
|
||||
|
||||
type traceStore struct {
|
||||
telemetryStore telemetrystore.TelemetryStore
|
||||
metadataStore telemetrytypes.MetadataStore
|
||||
@@ -73,7 +92,7 @@ func NewTraceStore(ts telemetrystore.TelemetryStore, metadataStore telemetrytype
|
||||
}
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spantypes.TraceBounds, error) {
|
||||
func (store *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spantypes.TraceBounds, 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", spantypes.TraceDB, spantypes.TraceSummaryTable))
|
||||
@@ -82,7 +101,7 @@ func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spant
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var bounds spantypes.TraceBounds
|
||||
err := s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
|
||||
err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
|
||||
&bounds.TraceID, &bounds.Start, &bounds.End, &bounds.NumSpans,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -94,11 +113,11 @@ func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spant
|
||||
return &bounds, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceStats, error) {
|
||||
func (store *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceStats, error) {
|
||||
table := fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable)
|
||||
spans := sqlbuilder.NewSelectBuilder()
|
||||
|
||||
genAIColumns, err := s.genAISpanColumns(ctx, orgID, bounds, spans)
|
||||
genAIColumns, err := store.genAISpanColumns(ctx, orgID, bounds, spans)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -160,7 +179,7 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var stats spantypes.TraceStats
|
||||
err = s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
|
||||
err = store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
|
||||
&stats.StartNs, &stats.EndNs, &stats.TotalSpans, &stats.TotalErrorSpans, &stats.HasMissingSpans,
|
||||
&stats.RootServiceName, &stats.RootEntryPoint, &stats.RootSpanStatusCode, &stats.GenAISpanCount, &stats.LLMCallCount, &stats.ToolCallCount,
|
||||
&stats.Tokens.Input, &stats.Tokens.Output, &stats.Tokens.CacheRead, &stats.Tokens.CacheWrite, &stats.Tokens.Reasoning,
|
||||
@@ -173,44 +192,43 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
|
||||
}
|
||||
|
||||
// genAISpanColumns returns the gen_ai columns aggregated per span, resolved across attribute evolutions.
|
||||
func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
|
||||
values := []struct{ key, alias string }{
|
||||
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
|
||||
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
|
||||
}
|
||||
|
||||
func (store *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
|
||||
names := slices.Clone(aiobservabilitytypes.GenAISpanGateKeys)
|
||||
for _, value := range values {
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, names)
|
||||
keys, err := store.genAIFieldKeys(ctx, orgID, names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
isGenAI, err := s.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
isGenAI, err := store.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
isLLMCall, err := s.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIRequestModel}, keys, sb)
|
||||
isLLMCall, err := store.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIRequestModel}, keys, sb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
isToolCall, err := s.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIToolName}, keys, sb)
|
||||
isToolCall, err := store.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIToolName}, keys, sb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := []string{isGenAI + " AS is_gen_ai", isLLMCall + " AS is_llm_call", isToolCall + " AS is_tool_call"}
|
||||
usageColumns, err := store.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append([]string{isGenAI + " AS is_gen_ai", isLLMCall + " AS is_llm_call", isToolCall + " AS is_tool_call"}, usageColumns...), nil
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
// genAIUsageColumns returns the token and cost columns of a span, resolved across attribute evolutions.
|
||||
func (store *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
|
||||
columns := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
// lookup by number, the type metadata stores numeric attributes under; float64 is only the output cast
|
||||
// fixed gen_ai keys that many traces lack, so a not-found warning means nothing here
|
||||
expr, _, err := querybuilder.ResolveColumn(ctx, q, s.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
|
||||
expr, _, err := querybuilder.ResolveColumn(ctx, q, store.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -220,7 +238,7 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
|
||||
return columns, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
|
||||
func (store *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
|
||||
sb := selectStorableSpans()
|
||||
sb.Where(
|
||||
sb.E("trace_id", traceID),
|
||||
@@ -232,13 +250,13 @@ func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var spans []spantypes.StorableSpan
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans")
|
||||
}
|
||||
return spans, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]spantypes.MinimalSpan, error) {
|
||||
func (store *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]spantypes.MinimalSpan, error) {
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) span_id",
|
||||
@@ -256,13 +274,13 @@ func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start,
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var spans []spantypes.MinimalSpan
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying minimal spans")
|
||||
}
|
||||
return spans, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
|
||||
func (store *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
|
||||
if len(spanIDs) == 0 {
|
||||
return []spantypes.StorableSpan{}, nil
|
||||
}
|
||||
@@ -282,7 +300,7 @@ func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, sta
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var spans []spantypes.StorableSpan
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans by IDs")
|
||||
}
|
||||
return spans, nil
|
||||
@@ -296,21 +314,21 @@ func selectStorableSpans() *sqlbuilder.SelectBuilder {
|
||||
return sb
|
||||
}
|
||||
|
||||
func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, page spantypes.ThreadPage) ([]spantypes.StorableSpan, error) {
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
func (store *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, page spantypes.ThreadPage) ([]spantypes.StorableSpan, error) {
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "parent_span_id", "has_error", "name", "kind_string",
|
||||
"status_code_string", "status_message", "resources_string",
|
||||
"status_code_string", "status_message", "resource",
|
||||
"attributes", "attributes_string", "attributes_number", "attributes_bool",
|
||||
"events", "links as references",
|
||||
)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, aiobservabilitytypes.GenAISpanGateKeys)
|
||||
keys, err := store.genAIFieldKeys(ctx, orgID, aiobservabilitytypes.GenAISpanGateKeys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
isThreadSpan, err := s.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
|
||||
isThreadSpan, err := store.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -349,13 +367,13 @@ func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, trac
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var spans []spantypes.StorableSpan
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying thread spans")
|
||||
}
|
||||
return spans, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, spanID string) (*spantypes.ThreadCursor, error) {
|
||||
func (store *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, spanID string) (*spantypes.ThreadCursor, error) {
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select("toUnixTimestamp64Nano(timestamp)")
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
@@ -369,7 +387,7 @@ func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var timeUnixNano int64
|
||||
if err := s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(&timeUnixNano); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(&timeUnixNano); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, errors.NewNotFoundf(spantypes.ErrCodeThreadSpanNotFound, "span %s not found in trace %s", spanID, traceID)
|
||||
}
|
||||
@@ -378,7 +396,7 @@ func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds
|
||||
return &spantypes.ThreadCursor{TimeUnixNano: uint64(timeUnixNano), SpanID: spanID}, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
|
||||
func (store *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select(
|
||||
"span_id",
|
||||
@@ -392,7 +410,7 @@ func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, sta
|
||||
"if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string", // `attributes` below resolves to the aggregated alias
|
||||
"if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number",
|
||||
"if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool",
|
||||
"any(resources_string) AS resources_string",
|
||||
"any(resource) AS resource",
|
||||
"any(scope) AS scope",
|
||||
)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
@@ -415,13 +433,13 @@ func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, sta
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var spans []spantypes.StorableSpan
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying flamegraph spans")
|
||||
}
|
||||
return spans, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
|
||||
func (store *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
|
||||
fieldExpr, err := buildFieldExpr(fieldKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -439,7 +457,7 @@ func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bo
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var rows []spanCountRow
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
|
||||
if err := store.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))
|
||||
@@ -449,7 +467,7 @@ func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bo
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetSpanDurationByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
|
||||
func (store *traceStore) GetSpanDurationByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
|
||||
fieldExpr, err := buildFieldExpr(fieldKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -493,7 +511,7 @@ func (s *traceStore) GetSpanDurationByField(ctx context.Context, traceID string,
|
||||
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
var rows []spanDurationRow
|
||||
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
|
||||
if err := store.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))
|
||||
@@ -508,12 +526,12 @@ func attributeKey(name string, dataType telemetrytypes.FieldDataType) *telemetry
|
||||
}
|
||||
|
||||
// genAIFieldKeys fetches the metadata keys for the attribute names, expanded across semconv families.
|
||||
func (s *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, names []string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
|
||||
func (store *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, names []string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
|
||||
selectors := make([]*telemetrytypes.FieldKeySelector, 0, len(names))
|
||||
for _, name := range names {
|
||||
selectors = append(selectors, &telemetrytypes.FieldKeySelector{Name: name, Signal: telemetrytypes.SignalTraces, FieldContext: telemetrytypes.FieldContextAttribute, SelectorMatchType: telemetrytypes.FieldSelectorMatchTypeExact})
|
||||
}
|
||||
keys, _, err := s.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, s.flagger, selectors))
|
||||
keys, _, err := store.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, store.flagger, selectors))
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error fetching gen_ai field keys")
|
||||
}
|
||||
@@ -522,10 +540,10 @@ func (s *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, name
|
||||
|
||||
// anyExistsCondition ORs an EXISTS test per attribute name, resolved across attribute evolutions
|
||||
// and the use_trace_attributes_json flag so the filter reads the same columns the query builder does.
|
||||
func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo, names []string, keys map[string][]*telemetrytypes.TelemetryFieldKey, sb *sqlbuilder.SelectBuilder) (string, error) {
|
||||
func (store *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo, names []string, keys map[string][]*telemetrytypes.TelemetryFieldKey, sb *sqlbuilder.SelectBuilder) (string, error) {
|
||||
conds := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
keyConds, _, err := querybuilder.Conditions(ctx, q, s.storage, attributeKey(name, telemetrytypes.FieldDataTypeString), qbtypes.FilterOperatorExists, nil, keys, false, sb)
|
||||
keyConds, _, err := querybuilder.Conditions(ctx, q, store.storage, attributeKey(name, telemetrytypes.FieldDataTypeString), qbtypes.FilterOperatorExists, nil, keys, false, sb)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -533,3 +551,124 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
|
||||
}
|
||||
return sb.Or(conds...), nil
|
||||
}
|
||||
|
||||
func (store *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
|
||||
names := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := store.genAIFieldKeys(ctx, orgID, names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
usageColumns, err := store.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
// Empty for the usual value, one reference to the parent, which the tree rebuilds from the two ids.
|
||||
otherReferences := fmt.Sprintf("multiIf(links = concat(%s, trace_id, %s, parent_span_id, %s), '', links = '', '[]', links) AS other_references",
|
||||
sb.Var(`[{"traceId":"`), sb.Var(`","spanId":"`), sb.Var(`","refType":"CHILD_OF"}]`))
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) span_id", "parent_span_id", "timestamp", "duration_nano", "has_error",
|
||||
"name", colServiceName, "kind_string", "response_status_code", "status_code_string", "status_message",
|
||||
colHasExceptionEvent, colHasLink, otherReferences,
|
||||
)
|
||||
sb.SelectMore(usageColumns...)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
sb.Where(
|
||||
sb.E("trace_id", traceID),
|
||||
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
|
||||
sb.LE("ts_bucket_start", bounds.End.Unix()),
|
||||
)
|
||||
sb.OrderByAsc("timestamp")
|
||||
sb.OrderByAsc("name")
|
||||
sb.OrderByAsc("span_id")
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
rows, err := store.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace skeleton")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
builder := spantypes.NewTraceSkeletonBuilder(traceID, int(bounds.NumSpans))
|
||||
var span spantypes.SkeletonSpan
|
||||
// ScanStruct builds a new list of fields for every row; reusing one halves the time on a large trace.
|
||||
fields := []any{
|
||||
&span.SpanID, &span.ParentSpanID, &span.StartTime, &span.DurationNano, &span.HasError,
|
||||
&span.Name, &span.ServiceName, &span.KindString, &span.ResponseStatusCode, &span.StatusCodeString, &span.StatusMessage,
|
||||
&span.HasExceptionEvent, &span.HasLink, &span.OtherReferences,
|
||||
&span.AIUsage.InputTokens, &span.AIUsage.OutputTokens, &span.AIUsage.CacheReadTokens,
|
||||
&span.AIUsage.CacheWriteTokens, &span.AIUsage.ReasoningTokens, &span.AIUsage.Cost,
|
||||
}
|
||||
spanCount := 0
|
||||
for rows.Next() {
|
||||
// The builder keeps the usage values of a row, so every row gets its own.
|
||||
span.AIUsage = spantypes.AISpanUsage{}
|
||||
if err := rows.Scan(fields...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error scanning trace skeleton")
|
||||
}
|
||||
builder.Add(&span)
|
||||
spanCount++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error reading trace skeleton")
|
||||
}
|
||||
if spanCount == 0 {
|
||||
return nil, spantypes.ErrTraceNotFound
|
||||
}
|
||||
return builder.Build(), nil
|
||||
}
|
||||
|
||||
func (store *traceStore) SearchTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, query string) (*spantypes.SpanSearch, error) {
|
||||
selectors := querybuilder.QueryStringToKeysSelectors(query)
|
||||
for _, selector := range selectors {
|
||||
selector.Signal = telemetrytypes.SignalTraces
|
||||
selector.SelectorMatchType = telemetrytypes.FieldSelectorMatchTypeExact
|
||||
}
|
||||
keys, _, err := store.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, store.flagger, selectors))
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error fetching query field keys")
|
||||
}
|
||||
|
||||
search := &spantypes.SpanSearch{}
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select("DISTINCT span_id")
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
sb.Where(
|
||||
sb.E("trace_id", traceID),
|
||||
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
|
||||
sb.LE("ts_bucket_start", bounds.End.Unix()),
|
||||
)
|
||||
prepared, err := querybuilder.PrepareWhereClause(query, querybuilder.FilterExprVisitorOpts{
|
||||
Context: ctx,
|
||||
Query: querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano())),
|
||||
Storage: store.storage,
|
||||
FieldKeys: keys,
|
||||
Builder: sb,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !prepared.IsEmpty() {
|
||||
sb.AddWhereClause(prepared.WhereClause)
|
||||
}
|
||||
for _, term := range prepared.SearchTerms {
|
||||
search.Words = append(search.Words, spantypes.SearchWord{Text: term.Text, Contexts: term.Contexts})
|
||||
}
|
||||
search.Warnings = prepared.Warnings
|
||||
stmt, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
var rows []spanIDRow
|
||||
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &rows, stmt, args...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error searching trace spans")
|
||||
}
|
||||
search.SpanIDs = make([]string, len(rows))
|
||||
for i, row := range rows {
|
||||
search.SpanIDs[i] = row.SpanID
|
||||
}
|
||||
return search, nil
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ func TestGetSpanCountByField(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetTraceSpans(t *testing.T) {
|
||||
expectedSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, has_error, kind, resource_string_service$$name, name, attributes, resources_string, scope, if(notEmpty(attributes), map(), attributes_string) AS attributes_string, if(notEmpty(attributes), map(), attributes_number) AS attributes_number, if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool, 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, links as references FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC"
|
||||
expectedSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, has_error, kind, resource_string_service$$name, name, attributes, resource, scope, if(notEmpty(attributes), map(), attributes_string) AS attributes_string, if(notEmpty(attributes), map(), attributes_number) AS attributes_number, if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool, 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, links as references FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC"
|
||||
|
||||
s := newTestStore(sqlmock.QueryMatcherEqual)
|
||||
s.Mock().ExpectSelect(expectedSQL).
|
||||
@@ -171,12 +171,12 @@ func TestGetFlamegraphSpans(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
name: "NoSpanIDs_GeneratesBaseSQL",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resources_string) AS resources_string, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resource) AS resource, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
},
|
||||
{
|
||||
name: "WithSpanIDs_GeneratesInClauseSQL",
|
||||
spanIDs: []string{"span-1", "span-2"},
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resources_string) AS resources_string, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND span_id IN (?, ?) GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resource) AS resource, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND span_id IN (?, ?) GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ func TestGetSpanDurationByField(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetThreadSpans(t *testing.T) {
|
||||
selectSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, parent_span_id, has_error, name, kind_string, status_code_string, status_message, resources_string, attributes, attributes_string, attributes_number, attributes_bool, events, links as references"
|
||||
selectSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, parent_span_id, has_error, name, kind_string, status_code_string, status_message, resource, attributes, attributes_string, attributes_number, attributes_bool, events, links as references"
|
||||
fromSQL := " FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND "
|
||||
orderSQL := " ORDER BY timestamp ASC, span_id ASC LIMIT ?"
|
||||
jsonInsideTrace := testStart.Add(500 * time.Second)
|
||||
@@ -253,3 +253,39 @@ func TestGetThreadSpans(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTraceSkeleton(t *testing.T) {
|
||||
jsonInsideTrace := testStart.Add(500 * time.Second)
|
||||
jsonBeforeTrace := testStart.Add(-500 * time.Second)
|
||||
fl := flaggertest.WithBooleanFlags(t, map[string]bool{flagger.FeatureUseTraceAttributesJSON.String(): true})
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
jsonRelease *time.Time
|
||||
expectedSQL string
|
||||
}{
|
||||
{
|
||||
name: "LegacyMaps",
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, multiIf(mapContains(attributes_number, 'gen_ai.usage.input_tokens'), toFloat64(attributes_number['gen_ai.usage.input_tokens']), NULL) AS input_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.output_tokens'), toFloat64(attributes_number['gen_ai.usage.output_tokens']), NULL) AS output_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_read.input_tokens']), NULL) AS cache_read_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_creation.input_tokens']), NULL) AS cache_write_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), toFloat64(attributes_number['gen_ai.usage.reasoning.output_tokens']), NULL) AS reasoning_tokens_value, multiIf(mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), toFloat64(attributes_number['signoz.gen_ai.usage.tokens.cost']), NULL) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionInsideTrace_ReadsBothColumns",
|
||||
jsonRelease: &jsonInsideTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.input_tokens'), attributes_number['gen_ai.usage.input_tokens'], NULL)) AS input_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.output_tokens'), attributes_number['gen_ai.usage.output_tokens'], NULL)) AS output_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), attributes_number['gen_ai.usage.cache_read.input_tokens'], NULL)) AS cache_read_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), attributes_number['gen_ai.usage.cache_creation.input_tokens'], NULL)) AS cache_write_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), attributes_number['gen_ai.usage.reasoning.output_tokens'], NULL)) AS reasoning_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) IS NOT NULL, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String), mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), attributes_number['signoz.gen_ai.usage.tokens.cost'], NULL)) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionBeforeTrace_ReadsJSONOnly",
|
||||
jsonRelease: &jsonBeforeTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
s := newTestStoreWithMetadata(sqlmock.QueryMatcherEqual, genAIMetadataStore(testCase.jsonRelease), fl)
|
||||
s.Mock().ExpectQuery(testCase.expectedSQL).WithArgs(`[{"traceId":"`, `","spanId":"`, `","refType":"CHILD_OF"}]`, testTraceID, testStart.Unix()-1800, testEnd.Unix()).WillReturnRows(cmock.NewRows(nil, nil))
|
||||
_, _ = s.Store().GetTraceSkeleton(context.Background(), valuer.GenerateUUID(), testTraceID, testBounds)
|
||||
assert.NoError(t, s.Mock().ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,4 +31,7 @@ type Module interface {
|
||||
GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)
|
||||
GetFlamegraph(ctx context.Context, traceID string, selectedSpanID string, selectFields []telemetrytypes.TelemetryFieldKey) (*spantypes.GettableFlamegraphTrace, error)
|
||||
GetThread(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.ThreadQuery) (*spantypes.GettableTraceThread, error)
|
||||
GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error)
|
||||
GetTraceSpan(ctx context.Context, traceID string, spanID string) (*spantypes.Span, error)
|
||||
ListTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.SpanListQuery) (*spantypes.SpanList, error)
|
||||
}
|
||||
|
||||
@@ -76,14 +76,18 @@ func Condition(
|
||||
return conds, warnings, nil
|
||||
}
|
||||
|
||||
// RejectsBodyFunction reports the error a storage without body functions
|
||||
// returns for one, before resolution. The fingerprint side of a split skips
|
||||
// RejectsBodyFunction reports the error a storage returns for a body function
|
||||
// or search() it does not support, before resolution. The fingerprint side of a split skips
|
||||
// the term instead, because the main query evaluates it.
|
||||
func RejectsBodyFunction(traits qbtypes.Traits, operator qbtypes.FilterOperator) (skip bool, err error) {
|
||||
if !operator.IsFunctionOperator() && operator != qbtypes.FilterOperatorSearch {
|
||||
switch {
|
||||
case operator == qbtypes.FilterOperatorSearch:
|
||||
if traits.SupportsSearchFunction {
|
||||
return false, nil
|
||||
}
|
||||
case !operator.IsFunctionOperator():
|
||||
return false, nil
|
||||
}
|
||||
if traits.SupportsBodyFunctions {
|
||||
case traits.SupportsBodyFunctions:
|
||||
return false, nil
|
||||
}
|
||||
if traits.Split == qbtypes.FingerprintOfSplit {
|
||||
|
||||
@@ -213,7 +213,7 @@ func NewFunctionUnsupportedError(operator qbtypes.FilterOperator) error {
|
||||
case qbtypes.FilterOperatorHas, qbtypes.FilterOperatorHasAny, qbtypes.FilterOperatorHasAll:
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "function `%s` supports only body JSON search", operator.FunctionName()).WithUrl(functionBodyJSONSearchDocURL)
|
||||
case qbtypes.FilterOperatorSearch:
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "function `search` is only supported for logs")
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "function `search` is only supported for logs and traces")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ type filterExpressionVisitor struct {
|
||||
keysWithWarnings map[string]bool
|
||||
|
||||
requiresCostGuard bool
|
||||
searchTerms []SearchTerm
|
||||
}
|
||||
|
||||
type FilterExprVisitorOpts struct {
|
||||
@@ -83,6 +84,14 @@ type PreparedWhereClause struct {
|
||||
Warnings []string
|
||||
WarningsDocURL string
|
||||
RequiresCostGuard bool
|
||||
// SearchTerms holds every search() call, in the order they appear.
|
||||
SearchTerms []SearchTerm
|
||||
}
|
||||
|
||||
// SearchTerm is the text of a search() call and the contexts it names; none means every part.
|
||||
type SearchTerm struct {
|
||||
Text string
|
||||
Contexts []telemetrytypes.FieldContext
|
||||
}
|
||||
|
||||
func (p PreparedWhereClause) IsEmpty() bool {
|
||||
@@ -164,12 +173,12 @@ func PrepareWhereClause(query string, opts FilterExprVisitorOpts) (PreparedWhere
|
||||
|
||||
// Return empty where clause so callers can skip the WHERE clause
|
||||
if cond == "" || cond == SkipConditionLiteral {
|
||||
return PreparedWhereClause{WhereClause: nil, Warnings: visitor.warnings, WarningsDocURL: visitor.mainWarnURL, RequiresCostGuard: visitor.requiresCostGuard}, nil
|
||||
return PreparedWhereClause{WhereClause: nil, Warnings: visitor.warnings, WarningsDocURL: visitor.mainWarnURL, RequiresCostGuard: visitor.requiresCostGuard, SearchTerms: visitor.searchTerms}, nil
|
||||
}
|
||||
|
||||
whereClause := sqlbuilder.NewWhereClause().AddWhereExpr(visitor.builder.Args, cond)
|
||||
|
||||
return PreparedWhereClause{WhereClause: whereClause, Expr: cond, Warnings: visitor.warnings, WarningsDocURL: visitor.mainWarnURL, RequiresCostGuard: visitor.requiresCostGuard}, nil
|
||||
return PreparedWhereClause{WhereClause: whereClause, Expr: cond, Warnings: visitor.warnings, WarningsDocURL: visitor.mainWarnURL, RequiresCostGuard: visitor.requiresCostGuard, SearchTerms: visitor.searchTerms}, nil
|
||||
}
|
||||
|
||||
// Visit dispatches to the specific visit method based on node type.
|
||||
@@ -816,12 +825,17 @@ func (v *filterExpressionVisitor) VisitSearchCall(ctx *grammar.SearchCallContext
|
||||
}
|
||||
fc, fok := telemetrytypes.FieldContextFromText(scopeText)
|
||||
if !fok {
|
||||
v.errors = append(v.errors, fmt.Sprintf("invalid search scope %q; expected a field context: body, attribute, resource, or log", scopeText))
|
||||
v.errors = append(v.errors, fmt.Sprintf("invalid search scope %q; expected a field context such as attribute or resource", scopeText))
|
||||
return ErrorConditionLiteral
|
||||
}
|
||||
fieldContexts = append(fieldContexts, fc)
|
||||
}
|
||||
}
|
||||
term := SearchTerm{Text: searchText}
|
||||
if len(params) > 1 {
|
||||
term.Contexts = fieldContexts
|
||||
}
|
||||
v.searchTerms = append(v.searchTerms, term)
|
||||
|
||||
var conds []string
|
||||
for _, fieldContext := range fieldContexts {
|
||||
|
||||
@@ -131,3 +131,29 @@ func TestBuild_SpanList_TraceFilter_Variables(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, stmt.Query, "__trace_scope")
|
||||
}
|
||||
|
||||
// A span list runs through the traces builder, which guards search() with the scan budget; a trace
|
||||
// aggregation builds its own statement, so it rejects search().
|
||||
func TestBuild_Search(t *testing.T) {
|
||||
t.Run("SpanList_Guarded", func(t *testing.T) {
|
||||
stmt, err := newTestBuilder(t).Build(context.Background(), valuer.UUID{}, testStartMs, testEndMs, qbtypes.RequestTypeRaw,
|
||||
qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
|
||||
Signal: telemetrytypes.SignalTraces,
|
||||
Filter: &qbtypes.Filter{Expression: "search('worldpay') AND trace.output_tokens > 1000"},
|
||||
Limit: 10,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, stmt.CostGuard)
|
||||
})
|
||||
|
||||
t.Run("Aggregation_Rejected", func(t *testing.T) {
|
||||
_, err := newTestBuilder(t).Build(context.Background(), valuer.UUID{}, testStartMs, testEndMs, qbtypes.RequestTypeScalar,
|
||||
qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
|
||||
Signal: telemetrytypes.SignalTraces,
|
||||
Aggregations: []qbtypes.TraceAggregation{{Expression: "avg(trace.output_tokens)"}},
|
||||
Filter: &qbtypes.Filter{Expression: "search('worldpay')"},
|
||||
}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "function `search` is not supported in trace-scoped queries")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -500,6 +500,10 @@ func (b *scopedTraceStatementBuilder) resolveSpanPredicate(ctx context.Context,
|
||||
if err != nil {
|
||||
return "", nil, "", err
|
||||
}
|
||||
// The scoped query has no scan budget to guard search() with.
|
||||
if prepared.RequiresCostGuard {
|
||||
return "", nil, "", errors.NewInvalidInputf(errors.CodeInvalidInput, "function `search` is not supported in trace-scoped queries").WithSuggestions("use `search` in a regular traces query")
|
||||
}
|
||||
if prepared.IsEmpty() {
|
||||
return "", nil, "", nil
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ type traceQueryStatementBuilder struct {
|
||||
aggExprRewriter qbtypes.AggExprRewriter
|
||||
fl flagger.Flagger
|
||||
skipResourceFingerprintEnabled bool
|
||||
searchMaxScanRows int64
|
||||
// traceScope, set only on the per-call copy made by BuildTraceScoped, constrains
|
||||
// queries to spans whose trace_id is in the __trace_scope CTE.
|
||||
traceScope *qbtypes.Statement
|
||||
@@ -57,10 +58,12 @@ func NewFactory(
|
||||
func(_ context.Context, settings factory.ProviderSettings, cfg statementbuilder.Config) (qbtypes.StatementBuilder[qbtypes.TraceAggregation], error) {
|
||||
storage := tracestelemetryschema.NewStorage(schemaMetadataStore)
|
||||
aggExprRewriter := querybuilder.NewAggExprRewriter(settings, nil, storage, fl, telemetrytypes.SignalTraces)
|
||||
return NewTraceQueryStatementBuilder(
|
||||
builder := NewTraceQueryStatementBuilder(
|
||||
settings, metadataStore, storage, aggExprRewriter, telemetryStore, fl,
|
||||
cfg.SkipResourceFingerprint.Enabled, cfg.SkipResourceFingerprint.Threshold,
|
||||
), nil
|
||||
)
|
||||
builder.searchMaxScanRows = cfg.SearchMaxScanRows
|
||||
return builder, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -441,7 +444,7 @@ func (b *traceQueryStatementBuilder) buildListQuery(
|
||||
WarningsDocURL: preparedWhereClause.WarningsDocURL,
|
||||
}
|
||||
|
||||
return stmt, nil
|
||||
return b.withCostGuard(stmt, preparedWhereClause.RequiresCostGuard), nil
|
||||
}
|
||||
|
||||
func (b *traceQueryStatementBuilder) buildTraceQuery(
|
||||
@@ -560,7 +563,7 @@ func (b *traceQueryStatementBuilder) buildTraceQuery(
|
||||
WarningsDocURL: preparedWhereClause.WarningsDocURL,
|
||||
}
|
||||
|
||||
return stmt, nil
|
||||
return b.withCostGuard(stmt, preparedWhereClause.RequiresCostGuard), nil
|
||||
}
|
||||
|
||||
func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(
|
||||
@@ -783,7 +786,7 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesOrHeatmapQuery(
|
||||
WarningsDocURL: preparedWhereClause.WarningsDocURL,
|
||||
}
|
||||
|
||||
return stmt, nil
|
||||
return b.withCostGuard(stmt, preparedWhereClause.RequiresCostGuard), nil
|
||||
}
|
||||
|
||||
// buildScalarQuery builds a query for scalar panel type.
|
||||
@@ -921,7 +924,7 @@ func (b *traceQueryStatementBuilder) buildScalarQuery(
|
||||
WarningsDocURL: preparedWhereClause.WarningsDocURL,
|
||||
}
|
||||
|
||||
return stmt, nil
|
||||
return b.withCostGuard(stmt, preparedWhereClause.RequiresCostGuard), nil
|
||||
}
|
||||
|
||||
// buildFilterCondition builds SQL condition from filter expression.
|
||||
@@ -1064,3 +1067,13 @@ func (b *traceQueryStatementBuilder) expandRawSelectFields(query qbtypes.QueryBu
|
||||
query.SelectFields = selectFields
|
||||
return query
|
||||
}
|
||||
|
||||
// withCostGuard attaches the search() scan budget and its advisory when the filter runs search().
|
||||
func (b *traceQueryStatementBuilder) withCostGuard(stmt *qbtypes.Statement, required bool) *qbtypes.Statement {
|
||||
if !required {
|
||||
return stmt
|
||||
}
|
||||
stmt.CostGuard = &qbtypes.CostGuard{Warning: querybuilder.SearchWarning, MaxScanRows: b.searchMaxScanRows}
|
||||
stmt.Warnings = append(stmt.Warnings, querybuilder.SearchWarning)
|
||||
return stmt
|
||||
}
|
||||
|
||||
@@ -1962,6 +1962,47 @@ func TestStatementBuilderGroupByUnseenKey(t *testing.T) {
|
||||
assert.Contains(t, q.Query, "attributes_bool['error.type']")
|
||||
}
|
||||
|
||||
func TestStatementBuilderSearchCostGuard(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
requestType qbtypes.RequestType
|
||||
filter string
|
||||
guarded bool
|
||||
}{
|
||||
{name: "List_Search_Guarded", requestType: qbtypes.RequestTypeRaw, filter: "search('worldpay')", guarded: true},
|
||||
{name: "TimeSeries_Search_Guarded", requestType: qbtypes.RequestTypeTimeSeries, filter: "search('worldpay') AND has_error = true", guarded: true},
|
||||
{name: "Scalar_Search_Guarded", requestType: qbtypes.RequestTypeScalar, filter: "search('worldpay', attribute)", guarded: true},
|
||||
{name: "List_NoSearch_NotGuarded", requestType: qbtypes.RequestTypeRaw, filter: "has_error = true", guarded: false},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
statementBuilder := newSkipResourceFingerprintBuilder(t, nil, false, 100000)
|
||||
statementBuilder.searchMaxScanRows = 5000
|
||||
query := qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
|
||||
Signal: telemetrytypes.SignalTraces,
|
||||
StepInterval: qbtypes.Step{Duration: 30 * time.Second},
|
||||
Aggregations: []qbtypes.TraceAggregation{{Expression: "count()"}},
|
||||
Filter: &qbtypes.Filter{Expression: testCase.filter},
|
||||
Limit: 10,
|
||||
}
|
||||
|
||||
stmt, err := statementBuilder.Build(context.Background(), valuer.UUID{}, 1747947419000, 1747983448000, testCase.requestType, query, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
if !testCase.guarded {
|
||||
assert.Nil(t, stmt.CostGuard)
|
||||
assert.NotContains(t, stmt.Warnings, querybuilder.SearchWarning)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, stmt.CostGuard)
|
||||
assert.Equal(t, int64(5000), stmt.CostGuard.MaxScanRows)
|
||||
assert.Contains(t, stmt.Warnings, querybuilder.SearchWarning)
|
||||
assert.Contains(t, stmt.Query, "positionCaseInsensitiveUTF8(")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatementBuilderAggregationUnseenKey covers the aggregation half of the KeyNotFound
|
||||
// fallback: aggregating over an attribute absent from metadata (via the shared
|
||||
// agg-expr rewriter) must fan out across type variants and build, not error.
|
||||
|
||||
@@ -276,6 +276,10 @@ func (b *traceOperatorCTEBuilder) buildQueryCTE(ctx context.Context, queryName s
|
||||
b.stmtBuilder.logger.ErrorContext(ctx, "Failed to prepare where clause", errors.Attr(err), slog.String("filter", query.Filter.Expression))
|
||||
return "", err
|
||||
}
|
||||
// The operator's combined query has no scan budget to guard search() with.
|
||||
if filterWhereClause.RequiresCostGuard {
|
||||
return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "function `search` is not supported in trace operator queries").WithSuggestions("use `search` in a regular traces query")
|
||||
}
|
||||
if !filterWhereClause.IsEmpty() {
|
||||
b.stmtBuilder.logger.DebugContext(ctx, "Adding where clause", slog.Any("where_clause", filterWhereClause.WhereClause))
|
||||
sb.AddWhereClause(filterWhereClause.WhereClause)
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes/telemetrytypestest"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -739,3 +740,19 @@ func TestTraceOperatorStatementBuilderDeduplicatesKeys(t *testing.T) {
|
||||
require.Contains(t, q.Query,
|
||||
"SELECT toString(multiIf(mapContains(attributes_string, 'http.method'), attributes_string['http.method'], NULL)) AS `http.method`, count() AS __result_0 FROM A GROUP BY `http.method` ORDER BY __result_0 DESC")
|
||||
}
|
||||
|
||||
func TestTraceOperatorStatementBuilderRejectsSearch(t *testing.T) {
|
||||
operator := qbtypes.QueryBuilderTraceOperator{Expression: "A => B", Limit: 10}
|
||||
require.NoError(t, operator.ParseExpression())
|
||||
query := func(name, filter string) qbtypes.QueryEnvelope {
|
||||
return qbtypes.QueryEnvelope{Type: qbtypes.QueryTypeBuilder, Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
|
||||
Name: name, Signal: telemetrytypes.SignalTraces, Filter: &qbtypes.Filter{Expression: filter},
|
||||
}}
|
||||
}
|
||||
compositeQuery := &qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{query("A", "search('worldpay')"), query("B", "service.name = 'backend'")}}
|
||||
|
||||
_, err := newTestTraceOperatorStatementBuilder(t).Build(context.Background(), valuer.UUID{}, 1747947419000, 1747983448000, qbtypes.RequestTypeRaw, operator, compositeQuery)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "function `search` is not supported in trace operator queries")
|
||||
}
|
||||
|
||||
@@ -559,8 +559,9 @@ func bodyPath(name string, dataType telemetrytypes.FieldDataType, value any) *te
|
||||
|
||||
func (m *storage) Traits() qbtypes.Traits {
|
||||
return qbtypes.Traits{
|
||||
Split: qbtypes.MainOfSplit,
|
||||
SupportsBodyFunctions: true,
|
||||
OwnContexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextLog},
|
||||
Split: qbtypes.MainOfSplit,
|
||||
SupportsBodyFunctions: true,
|
||||
SupportsSearchFunction: true,
|
||||
OwnContexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextLog},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package tracestelemetryschema
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/huandu/go-sqlbuilder"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/flagger"
|
||||
"github.com/SigNoz/signoz/pkg/flagger/flaggertest"
|
||||
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
func TestFilterExprSearch(t *testing.T) {
|
||||
releaseTime := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
|
||||
startNs := uint64(releaseTime.Add(-5 * time.Minute).UnixNano())
|
||||
endNs := uint64(releaseTime.Add(5 * time.Minute).UnixNano())
|
||||
|
||||
// name and status_message
|
||||
spanSQL := "positionCaseInsensitiveUTF8(name, ?) > 0 OR positionCaseInsensitiveUTF8(status_message, ?) > 0"
|
||||
// attribute paths and the decoded strings and scalars of the JSON text when the JSON column is filled, else every key and value of the three maps
|
||||
attributeSQL := "if(notEmpty(attributes), " +
|
||||
"arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, JSONAllPaths(attributes)) OR (positionCaseInsensitiveUTF8(toJSONString(attributes), ?) > 0 AND arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, arrayMap(t -> if(startsWith(t, '\"'), JSONExtractString(t), t), extractAll(toJSONString(attributes), ?)))), " +
|
||||
"arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, mapKeys(attributes_string)) OR arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, mapValues(attributes_string)) OR " +
|
||||
"arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, mapKeys(attributes_number)) OR arrayExists(x -> positionCaseInsensitiveUTF8(toString(x), ?) > 0, mapValues(attributes_number)) OR " +
|
||||
"arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, mapKeys(attributes_bool)) OR arrayExists(x -> positionCaseInsensitiveUTF8(toString(x), ?) > 0, mapValues(attributes_bool)))"
|
||||
// resource paths and the decoded strings and scalars of the resource JSON text
|
||||
resourceSQL := "arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, JSONAllPaths(resource)) OR (positionCaseInsensitiveUTF8(toJSONString(resource), ?) > 0 AND arrayExists(x -> positionCaseInsensitiveUTF8(x, ?) > 0, arrayMap(t -> if(startsWith(t, '\"'), JSONExtractString(t), t), extractAll(toJSONString(resource), ?))))"
|
||||
// each event's name and attribute keys and values
|
||||
eventSQL := "arrayExists(e -> positionCaseInsensitiveUTF8(JSONExtractString(e, 'name'), ?) > 0 OR " +
|
||||
"arrayExists(x -> positionCaseInsensitiveUTF8(x.1, ?) > 0 OR positionCaseInsensitiveUTF8(x.2, ?) > 0, JSONExtractKeysAndValues(e, 'attributeMap', 'String')), events)"
|
||||
// attributeArgs fills attributeSQL: the term for the paths, the term escaped as JSON text, the term and the token pattern for the decoded values, then the term for each of the six map checks.
|
||||
attributeArgs := func(term, escaped string) []any {
|
||||
return []any{term, escaped, term, jsonTokenPattern, term, term, term, term, term, term}
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
query string
|
||||
expectedQuery string
|
||||
expectedArgs []any
|
||||
expectedTerms []querybuilder.SearchTerm
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "Unscoped_SearchesEveryPart",
|
||||
query: "search('worldpay')",
|
||||
expectedQuery: "WHERE (" + spanSQL + " OR " + attributeSQL + " OR " + resourceSQL + " OR " + eventSQL + ")",
|
||||
expectedArgs: slices.Concat(
|
||||
[]any{"worldpay", "worldpay"},
|
||||
attributeArgs("worldpay", "worldpay"),
|
||||
[]any{"worldpay", "worldpay", "worldpay", jsonTokenPattern},
|
||||
[]any{"worldpay", "worldpay", "worldpay"},
|
||||
),
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "worldpay"}},
|
||||
},
|
||||
{
|
||||
name: "ScopedToSpan",
|
||||
query: "search('declined', span)",
|
||||
expectedQuery: "WHERE (positionCaseInsensitiveUTF8(name, ?) > 0 OR positionCaseInsensitiveUTF8(status_message, ?) > 0)",
|
||||
expectedArgs: []any{"declined", "declined"},
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "declined", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextSpan}}},
|
||||
},
|
||||
{
|
||||
name: "ScopedToAttribute",
|
||||
query: "search('visa', attribute)",
|
||||
expectedQuery: "WHERE (" + attributeSQL + ")",
|
||||
expectedArgs: attributeArgs("visa", "visa"),
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "visa", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextAttribute}}},
|
||||
},
|
||||
{
|
||||
name: "ScopedToResource",
|
||||
query: "search('checkout', 'resource')",
|
||||
expectedQuery: "WHERE (" + resourceSQL + ")",
|
||||
expectedArgs: []any{"checkout", "checkout", "checkout", jsonTokenPattern},
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "checkout", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextResource}}},
|
||||
},
|
||||
{
|
||||
name: "ScopedToEvent",
|
||||
query: "search('timeout', event)",
|
||||
expectedQuery: "WHERE (" + eventSQL + ")",
|
||||
expectedArgs: []any{"timeout", "timeout", "timeout"},
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "timeout", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextEvent}}},
|
||||
},
|
||||
{
|
||||
name: "SlashAndQuote_EscapedForJSONText",
|
||||
query: `search('api/v1 "x"', attribute)`,
|
||||
expectedQuery: "WHERE (" + attributeSQL + ")",
|
||||
expectedArgs: attributeArgs(`api/v1 "x"`, `api\/v1 \"x\"`),
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: `api/v1 "x"`, Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextAttribute}}},
|
||||
},
|
||||
{
|
||||
name: "TwoCalls_ReportBothTerms",
|
||||
query: "search('worldpay', span) OR search('stripe', span)",
|
||||
expectedQuery: "WHERE ((" + spanSQL + ") OR (" + spanSQL + "))",
|
||||
expectedArgs: []any{"worldpay", "worldpay", "stripe", "stripe"},
|
||||
expectedTerms: []querybuilder.SearchTerm{{Text: "worldpay", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextSpan}}, {Text: "stripe", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextSpan}}},
|
||||
},
|
||||
{
|
||||
name: "BodyScope_Rejected",
|
||||
query: "search('worldpay', body)",
|
||||
expectedError: "invalid search scope \"body\" for traces",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
fl := flaggertest.WithBooleanFlags(t, map[string]bool{flagger.FeatureUseTraceAttributesJSON.String(): true})
|
||||
clause, err := querybuilder.PrepareWhereClause(testCase.query, querybuilder.FilterExprVisitorOpts{
|
||||
Context: context.Background(),
|
||||
Logger: instrumentationtest.New().Logger(),
|
||||
Storage: NewStorage(nil),
|
||||
Query: querybuilder.NewQueryInfo(context.Background(), valuer.UUID{}, fl, telemetrytypes.SignalTraces, nil, startNs, endNs),
|
||||
FieldKeys: BuildCompleteFieldKeyMap(releaseTime),
|
||||
})
|
||||
if testCase.expectedError != "" {
|
||||
require.Error(t, err)
|
||||
messages := []string{err.Error()}
|
||||
for _, detail := range errors.AsJSON(err).Errors {
|
||||
messages = append(messages, detail.Message)
|
||||
}
|
||||
assert.Contains(t, strings.Join(messages, " "), testCase.expectedError)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.False(t, clause.IsEmpty())
|
||||
|
||||
sql, args := clause.WhereClause.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
assert.Equal(t, testCase.expectedQuery, sql)
|
||||
assert.Equal(t, testCase.expectedArgs, args)
|
||||
assert.Equal(t, testCase.expectedTerms, clause.SearchTerms)
|
||||
assert.True(t, clause.RequiresCostGuard)
|
||||
})
|
||||
}
|
||||
}
|
||||
74
pkg/telemetryschema/tracestelemetryschema/search.go
Normal file
74
pkg/telemetryschema/tracestelemetryschema/search.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package tracestelemetryschema
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/huandu/go-sqlbuilder"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
// jsonTokenPattern matches each quoted string and each bare number or boolean of a JSON text.
|
||||
const jsonTokenPattern = `"(?:[^"\\]|\\.)*"|[^{}\[\]:,"]+`
|
||||
|
||||
// jsonTextEscaper writes a term the way toJSONString writes it with default settings, which
|
||||
// escape a forward slash too.
|
||||
var jsonTextEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "/", `\/`, "\n", `\n`, "\r", `\r`, "\t", `\t`, "\b", `\b`, "\f", `\f`)
|
||||
|
||||
// searchCondition matches text, ignoring case, in the part of a span that scope names: span (name
|
||||
// and status message), attribute, resource or event, or all of them when scope is unspecified.
|
||||
// Attributes are read from their JSON column when it is filled, the legacy maps otherwise; resource
|
||||
// attributes from their JSON column only.
|
||||
func searchCondition(sb *sqlbuilder.SelectBuilder, scope telemetrytypes.FieldContext, text string) (string, error) {
|
||||
needle := sb.Var(text)
|
||||
in := func(haystack string) string {
|
||||
return fmt.Sprintf("positionCaseInsensitiveUTF8(%s, %s) > 0", haystack, needle)
|
||||
}
|
||||
anyOf := func(array, element string) string {
|
||||
return fmt.Sprintf("arrayExists(x -> %s, %s)", in(element), array)
|
||||
}
|
||||
// A JSON column nests a dotted name, so names are matched as paths and values in the decoded
|
||||
// strings and scalars of its text. The escaped term in the whole text finds the candidate rows
|
||||
// cheaply; only those are decoded.
|
||||
inJSON := func(column string) string {
|
||||
inText := fmt.Sprintf("positionCaseInsensitiveUTF8(toJSONString(%s), %s) > 0", column, sb.Var(jsonTextEscaper.Replace(text)))
|
||||
values := fmt.Sprintf(`arrayMap(t -> if(startsWith(t, '"'), JSONExtractString(t), t), extractAll(toJSONString(%s), %s))`, column, sb.Var(jsonTokenPattern))
|
||||
return fmt.Sprintf("%s OR (%s AND %s)", anyOf("JSONAllPaths("+column+")", "x"), inText, anyOf(values, "x"))
|
||||
}
|
||||
span := func() []string { return []string{in("name"), in("status_message")} }
|
||||
attribute := func() string {
|
||||
maps := []string{
|
||||
anyOf("mapKeys(attributes_string)", "x"), anyOf("mapValues(attributes_string)", "x"),
|
||||
anyOf("mapKeys(attributes_number)", "x"), anyOf("mapValues(attributes_number)", "toString(x)"),
|
||||
anyOf("mapKeys(attributes_bool)", "x"), anyOf("mapValues(attributes_bool)", "toString(x)"),
|
||||
}
|
||||
return fmt.Sprintf("if(notEmpty(attributes), %s, %s)", inJSON("attributes"), strings.Join(maps, " OR "))
|
||||
}
|
||||
resource := func() string { return inJSON("resource") }
|
||||
// An event is a JSON string: only its name and attributes are matched, not its timestamp.
|
||||
event := func() string {
|
||||
return fmt.Sprintf(
|
||||
"arrayExists(e -> %s OR arrayExists(x -> %s OR %s, JSONExtractKeysAndValues(e, 'attributeMap', 'String')), events)",
|
||||
in("JSONExtractString(e, 'name')"), in("x.1"), in("x.2"),
|
||||
)
|
||||
}
|
||||
|
||||
var conditions []string
|
||||
switch scope {
|
||||
case telemetrytypes.FieldContextUnspecified:
|
||||
conditions = append(span(), attribute(), resource(), event())
|
||||
case telemetrytypes.FieldContextSpan:
|
||||
conditions = span()
|
||||
case telemetrytypes.FieldContextAttribute:
|
||||
conditions = []string{attribute()}
|
||||
case telemetrytypes.FieldContextResource:
|
||||
conditions = []string{resource()}
|
||||
case telemetrytypes.FieldContextEvent:
|
||||
conditions = []string{event()}
|
||||
default:
|
||||
return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid search scope %q for traces; expected span, attribute, resource or event", scope.StringValue())
|
||||
}
|
||||
return "(" + strings.Join(conditions, " OR ") + ")", nil
|
||||
}
|
||||
@@ -604,16 +604,24 @@ func stampColumnType(key *telemetrytypes.TelemetryFieldKey, columns []*schema.Co
|
||||
|
||||
func (m *storage) Traits() qbtypes.Traits {
|
||||
return qbtypes.Traits{
|
||||
Split: qbtypes.MainOfSplit,
|
||||
OwnContexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextSpan, telemetrytypes.FieldContextTrace},
|
||||
Split: qbtypes.MainOfSplit,
|
||||
SupportsSearchFunction: true,
|
||||
OwnContexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextSpan, telemetrytypes.FieldContextTrace},
|
||||
}
|
||||
}
|
||||
|
||||
// Compile keeps the trace-specific rules ahead of the shared condition: a
|
||||
// span scope key compiles to a structural predicate, a duration operand
|
||||
// Compile keeps the trace-specific rules ahead of the shared condition: search()
|
||||
// matches text across a span, a span scope key compiles to a structural predicate, a duration operand
|
||||
// accepts duration syntax, and a negative operator on a numeric or bool JSON
|
||||
// attribute reads the absent key as the map's type default.
|
||||
func (m *storage) Compile(ctx context.Context, q qbtypes.QueryInfo, logical *telemetrytypes.LogicalField, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (qbtypes.Compiled, error) {
|
||||
if operator == qbtypes.FilterOperatorSearch {
|
||||
condition, err := searchCondition(sb, logical.FieldContext, fmt.Sprintf("%v", value))
|
||||
if err != nil {
|
||||
return qbtypes.Compiled{}, err
|
||||
}
|
||||
return qbtypes.Compiled{Condition: condition}, nil
|
||||
}
|
||||
if isSpanSearchScopeField(logical.Name) {
|
||||
condition, err := buildSpanScopeCondition(logical.Single(), operator, value, q.StartNs)
|
||||
if err != nil {
|
||||
|
||||
@@ -138,11 +138,13 @@ const (
|
||||
// Traits are the per-signal capabilities the generic flows read as data.
|
||||
type Traits struct {
|
||||
Split FingerprintSplit
|
||||
// SupportsBodyFunctions: has/hasAny/hasAll/hasToken/search. A
|
||||
// SupportsBodyFunctions: has/hasAny/hasAll/hasToken. A
|
||||
// FingerprintOfSplit signal skips them. Every other signal without them
|
||||
// rejects them before resolution.
|
||||
SupportsBodyFunctions bool
|
||||
UnknownKey UnknownKey
|
||||
// SupportsSearchFunction: search(), skipped or rejected the same way.
|
||||
SupportsSearchFunction bool
|
||||
// OwnContexts are the contexts that mean "this signal's own record": a
|
||||
// key under them addresses columns and attributes alike, so the
|
||||
// resolver matches metadata as if no context was given. Strict contexts
|
||||
|
||||
@@ -73,11 +73,12 @@ func NewFlamegraphSpanFromStorable(s *StorableSpan, level int64, selectFields []
|
||||
return span
|
||||
}
|
||||
var attributes map[string]any
|
||||
resource := s.Resource()
|
||||
var scopeFields []string
|
||||
for _, field := range selectFields {
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextResource:
|
||||
if v, ok := s.ResourcesString[field.Name]; ok && v != "" {
|
||||
if v, ok := resource[field.Name]; ok && v != "" {
|
||||
span.Resource[field.Name] = v
|
||||
}
|
||||
case telemetrytypes.FieldContextAttribute:
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestNewFlamegraphSpanFromStorable_SelectFields(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "ResourceFields_EmptyValueSkipped",
|
||||
span: StorableSpan{ResourcesString: map[string]string{"service.name": "checkout", "deployment.environment": ""}},
|
||||
span: StorableSpan{ResourceJSON: jsonAttrs(map[string]any{"service.name": "checkout", "deployment.environment": ""})},
|
||||
selectFields: []telemetrytypes.TelemetryFieldKey{
|
||||
{Name: "service.name", FieldContext: telemetrytypes.FieldContextResource},
|
||||
{Name: "deployment.environment", FieldContext: telemetrytypes.FieldContextResource},
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"maps"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
SpanListViewErrorOrigins SpanListView = "error_origins"
|
||||
SpanListViewUnmarkedFailures SpanListView = "unmarked_failures"
|
||||
@@ -15,6 +21,8 @@ const (
|
||||
UnmarkedFailureExceptionEvent UnmarkedFailureKind = "exception_event"
|
||||
)
|
||||
|
||||
var ErrCodeTraceSpanNotFound = errors.MustNewCode("trace_span_not_found")
|
||||
|
||||
// SpanListView keeps the spans of one kind out of the spans a route covers, in that kind's order.
|
||||
// It is a plain string so that a list of views binds from a repeated query parameter.
|
||||
type SpanListView string
|
||||
@@ -35,7 +43,7 @@ func (UnmarkedFailureKind) Enum() []any {
|
||||
// which spans it covers, and these narrow and page them.
|
||||
type ListTraceSpansParams struct {
|
||||
View SpanListView `query:"view" description:"Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans."`
|
||||
Query string `query:"query" description:"Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view."`
|
||||
Query string `query:"query" description:"A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view."`
|
||||
SelectFields []string `query:"selectFields" description:"Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only."`
|
||||
Offset int `query:"offset" description:"Number of spans to skip. Default: 0."`
|
||||
Limit int `query:"limit" description:"Number of spans to return. Default: 50. Maximum: 1000."`
|
||||
@@ -56,12 +64,54 @@ type Span struct {
|
||||
StatusCodeString string `json:"status_code_string" required:"true"`
|
||||
StatusMessage string `json:"status_message" required:"true" description:"Usually the error text."`
|
||||
ResponseStatusCode string `json:"response_status_code" required:"true" description:"HTTP or gRPC status code, for example 404."`
|
||||
HTTPMethod string `json:"http_method,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
HTTPURL string `json:"http_url,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
HTTPHost string `json:"http_host,omitempty" description:"Host or server address. Omitted when empty, and in a list unless selected."`
|
||||
ExternalHTTPMethod string `json:"external_http_method,omitempty" description:"Method of an outgoing HTTP call. Omitted when empty, and in a list unless selected."`
|
||||
ExternalHTTPURL string `json:"external_http_url,omitempty" description:"Host of an outgoing HTTP call. Omitted when empty, and in a list unless selected."`
|
||||
DBName string `json:"db_name,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
DBOperation string `json:"db_operation,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
TraceState string `json:"trace_state,omitempty" description:"W3C trace state. Omitted when empty, and in a list unless selected."`
|
||||
Scope Scope `json:"scope,omitempty" description:"Instrumentation scope. Omitted when empty, and in a list unless selected."`
|
||||
Resource map[string]string `json:"resource" required:"true" nullable:"false" description:"Always has service.name. All of them for a span read by ID; the selected ones in a list."`
|
||||
Attributes map[string]any `json:"attributes" required:"true" nullable:"false" description:"All of them for a span read by ID; the selected ones in a list."`
|
||||
Events []Event `json:"events" required:"true" nullable:"false" description:"All of them for a span read by ID; none in a list."`
|
||||
References []OtelSpanRef `json:"references" required:"true" nullable:"false" description:"The parent as CHILD_OF, and each span link as FOLLOWS_FROM."`
|
||||
}
|
||||
|
||||
// NewSpan returns the span with everything row stores on it: all attributes, resource attributes
|
||||
// and events.
|
||||
func NewSpan(traceID string, row *StorableSpan) *Span {
|
||||
span := &Span{
|
||||
SpanID: row.SpanID,
|
||||
TraceID: traceID,
|
||||
ParentSpanID: row.ParentSpanID,
|
||||
Name: row.Name,
|
||||
KindString: row.SpanKind,
|
||||
TimeUnix: uint64(row.StartTime.UnixMilli()),
|
||||
DurationNano: row.DurationNano,
|
||||
HasError: row.HasError,
|
||||
StatusCodeString: row.StatusCodeString,
|
||||
StatusMessage: row.StatusMessage,
|
||||
ResponseStatusCode: row.ResponseStatusCode,
|
||||
Resource: map[string]string{"service.name": row.ServiceName},
|
||||
Attributes: row.Attributes(),
|
||||
Events: row.UnmarshalledEvents(),
|
||||
References: row.UnmarshalledRefs(),
|
||||
HTTPMethod: row.HTTPMethod,
|
||||
HTTPURL: row.HTTPURL,
|
||||
HTTPHost: row.HTTPHost,
|
||||
ExternalHTTPMethod: row.ExternalHTTPMethod,
|
||||
ExternalHTTPURL: row.ExternalHTTPURL,
|
||||
DBName: row.DBName,
|
||||
DBOperation: row.DBOperation,
|
||||
TraceState: row.TraceState,
|
||||
Scope: NewScope(row.Scope.Flatten()),
|
||||
}
|
||||
maps.Copy(span.Resource, row.Resource())
|
||||
return span
|
||||
}
|
||||
|
||||
type SameNameSiblingStats struct {
|
||||
SpanCount uint64 `json:"spanCount" required:"true" description:"This span included."`
|
||||
OwnTimeNano uint64 `json:"ownTimeNano" required:"true"`
|
||||
@@ -88,7 +138,7 @@ type SpanItem struct {
|
||||
Span Span `json:"span" required:"true"`
|
||||
TreeStats SpanTreeStats `json:"treeStats" required:"true"`
|
||||
UnmarkedFailureKind UnmarkedFailureKind `json:"unmarkedFailureKind,omitempty" description:"Why the span is an unmarked failure. Omitted for other spans."`
|
||||
Matches []SpanTextMatch `json:"matches,omitempty" nullable:"false" description:"Where the query's words were found, up to three places. Omitted when the query has no words."`
|
||||
Matches []SpanTextMatch `json:"matches,omitempty" nullable:"false" description:"Where the query's search() text was found, up to three places. Omitted when the query has no search()."`
|
||||
}
|
||||
|
||||
type SpanList struct {
|
||||
|
||||
@@ -40,6 +40,10 @@ type TraceStore interface {
|
||||
GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, page ThreadPage) ([]StorableSpan, error)
|
||||
GetThreadCursor(ctx context.Context, traceID string, bounds *TraceBounds, spanID string) (*ThreadCursor, error)
|
||||
|
||||
GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds) (*TraceSkeleton, error)
|
||||
// SearchTraceSpans returns every span of the trace that matches the filter expression query.
|
||||
SearchTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, query string) (*SpanSearch, error)
|
||||
|
||||
GetSpanCountByField(ctx context.Context, traceID string, bounds *TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)
|
||||
GetSpanDurationByField(ctx context.Context, traceID string, bounds *TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package spantypes
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
|
||||
@@ -174,8 +173,7 @@ func (s *ThreadSpan) cursor() ThreadCursor {
|
||||
}
|
||||
|
||||
func newThreadSpan(traceID string, storable *StorableSpan) *ThreadSpan {
|
||||
resources := make(map[string]string, len(storable.ResourcesString))
|
||||
maps.Copy(resources, storable.ResourcesString)
|
||||
resources := storable.Resource()
|
||||
timeUnixNano := uint64(storable.StartTime.UnixNano())
|
||||
attributes := storable.Attributes()
|
||||
// Spans from before the JSON rollout have an empty document and format to nothing.
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"slices"
|
||||
)
|
||||
|
||||
const highlightsDefaultLimit = 10
|
||||
|
||||
type GetTraceHighlightsParams struct {
|
||||
Views []SpanListView `query:"views" description:"The lists to return. Default: all."`
|
||||
Limit int `query:"limit" description:"Spans in each list. Default: 10. Maximum: 1000."`
|
||||
@@ -22,3 +28,51 @@ type TraceHighlights struct {
|
||||
AIUsage *SpanList `json:"aiUsage,omitempty" description:"First page of the ai_usage view."`
|
||||
Links *SpanList `json:"links,omitempty" description:"First page of the links view."`
|
||||
}
|
||||
|
||||
type TraceHighlightsQuery struct {
|
||||
Views []SpanListView
|
||||
Limit int
|
||||
}
|
||||
|
||||
func NewTraceHighlightsQuery(params *GetTraceHighlightsParams) (*TraceHighlightsQuery, error) {
|
||||
limit, err := pageLimit("limit", params.Limit, highlightsDefaultLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := &TraceHighlightsQuery{Limit: limit}
|
||||
for _, view := range params.Views {
|
||||
if err := validateSpanListView(view); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(query.Views, view) {
|
||||
query.Views = append(query.Views, view)
|
||||
}
|
||||
}
|
||||
if len(query.Views) == 0 {
|
||||
for _, view := range SpanListView("").Enum() {
|
||||
query.Views = append(query.Views, view.(SpanListView))
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
// NewTraceHighlights builds the first page of each requested view from the tree.
|
||||
func NewTraceHighlights(skeleton *TraceSkeleton, query *TraceHighlightsQuery) *TraceHighlights {
|
||||
highlights := &TraceHighlights{Services: skeleton.serviceStats()}
|
||||
for _, view := range query.Views {
|
||||
list := NewSpanList(skeleton.page(skeleton.treeOrder, view, 0, query.Limit), nil)
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
highlights.ErrorOrigins = list
|
||||
case SpanListViewUnmarkedFailures:
|
||||
highlights.UnmarkedFailures = list
|
||||
case SpanListViewTimeSpent:
|
||||
highlights.TimeSpent = list
|
||||
case SpanListViewAIUsage:
|
||||
highlights.AIUsage = list
|
||||
case SpanListViewLinks:
|
||||
highlights.Links = list
|
||||
}
|
||||
}
|
||||
return highlights
|
||||
}
|
||||
|
||||
445
pkg/types/spantypes/trace_skeleton.go
Normal file
445
pkg/types/spantypes/trace_skeleton.go
Normal file
@@ -0,0 +1,445 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
noParent int32 = -1
|
||||
|
||||
refTypeChildOf = "CHILD_OF"
|
||||
)
|
||||
|
||||
// SkeletonSpan is one row of the query a TraceSkeleton is built from.
|
||||
type SkeletonSpan struct {
|
||||
Span
|
||||
// StartTime keeps the nanoseconds own time is computed from; TimeUnix is in milliseconds.
|
||||
StartTime time.Time
|
||||
ServiceName string
|
||||
HasExceptionEvent bool
|
||||
HasLink bool
|
||||
// OtherReferences is empty for a span whose only reference is the one to its parent.
|
||||
OtherReferences string
|
||||
// AIUsage is kept when it has a value, pointers included: every row needs its own.
|
||||
AIUsage AISpanUsage
|
||||
}
|
||||
|
||||
// AISpanUsage is the gen_ai token and cost usage of one span; a nil value is absent on the span.
|
||||
type AISpanUsage struct {
|
||||
InputTokens *float64
|
||||
OutputTokens *float64
|
||||
CacheReadTokens *float64
|
||||
CacheWriteTokens *float64
|
||||
ReasoningTokens *float64
|
||||
Cost *float64
|
||||
}
|
||||
|
||||
// TraceSkeleton is the tree of a trace. A span is known by its position, its index in start time
|
||||
// order, and every slice below holds one value per span at that position. It is read-only once built.
|
||||
type TraceSkeleton struct {
|
||||
traceID string
|
||||
|
||||
// spanIDs holds every span id back to back; span i is spanIDs[idOffsets[i]:idOffsets[i+1]].
|
||||
spanIDs string
|
||||
idOffsets []uint32
|
||||
// parents holds the position of each span's parent, or noParent for a root.
|
||||
parents []int32
|
||||
startNano []int64
|
||||
durationNano []uint64
|
||||
hasError []bool
|
||||
hasExceptionEvent []bool
|
||||
hasLink []bool
|
||||
// Each distinct string is stored once in stringTable; these hold its index there.
|
||||
names []uint32
|
||||
services []uint32
|
||||
kinds []uint32
|
||||
responseStatusCodes []uint32
|
||||
statusCodeStrings []uint32
|
||||
statusMessages []uint32
|
||||
stringTable []string
|
||||
// references holds the stored references of a span that has more than the one to its parent.
|
||||
references map[int32]string
|
||||
// storedParentIDs holds the parent id of a root that has one: its parent is missing or on a loop.
|
||||
storedParentIDs map[int32]string
|
||||
// aiUsage holds the usage of the spans that carry any, by span position.
|
||||
aiUsage map[int32]AISpanUsage
|
||||
|
||||
// The children of span i are childList[childStart[i]:childStart[i+1]], in start time order.
|
||||
childStart []int32
|
||||
childList []int32
|
||||
roots []int32
|
||||
// treeOrder lists the spans as a waterfall shows them: a span, then everything below it.
|
||||
treeOrder []int32
|
||||
level []uint32
|
||||
// descendantCount is the number of spans below each span, at any depth.
|
||||
descendantCount []uint32
|
||||
ownTime []uint64
|
||||
// groupOf is the index in groups of the group a span belongs to.
|
||||
groupOf []int32
|
||||
groups []siblingGroup
|
||||
}
|
||||
|
||||
// TraceSkeletonBuilder collects the rows of a trace. They must be added in start time order.
|
||||
type TraceSkeletonBuilder struct {
|
||||
skeleton *TraceSkeleton
|
||||
ids []byte
|
||||
parentIDs []string
|
||||
stringIndex map[string]uint32
|
||||
}
|
||||
|
||||
func NewTraceSkeletonBuilder(traceID string, sizeHint int) *TraceSkeletonBuilder {
|
||||
return &TraceSkeletonBuilder{
|
||||
skeleton: &TraceSkeleton{
|
||||
traceID: traceID,
|
||||
idOffsets: make([]uint32, 1, sizeHint+1),
|
||||
parents: make([]int32, 0, sizeHint),
|
||||
startNano: make([]int64, 0, sizeHint),
|
||||
durationNano: make([]uint64, 0, sizeHint),
|
||||
hasError: make([]bool, 0, sizeHint),
|
||||
hasExceptionEvent: make([]bool, 0, sizeHint),
|
||||
hasLink: make([]bool, 0, sizeHint),
|
||||
names: make([]uint32, 0, sizeHint),
|
||||
services: make([]uint32, 0, sizeHint),
|
||||
kinds: make([]uint32, 0, sizeHint),
|
||||
responseStatusCodes: make([]uint32, 0, sizeHint),
|
||||
statusCodeStrings: make([]uint32, 0, sizeHint),
|
||||
statusMessages: make([]uint32, 0, sizeHint),
|
||||
references: make(map[int32]string),
|
||||
storedParentIDs: make(map[int32]string),
|
||||
aiUsage: make(map[int32]AISpanUsage),
|
||||
},
|
||||
ids: make([]byte, 0, sizeHint*16),
|
||||
parentIDs: make([]string, 0, sizeHint),
|
||||
stringIndex: make(map[string]uint32),
|
||||
}
|
||||
}
|
||||
|
||||
func (builder *TraceSkeletonBuilder) Add(span *SkeletonSpan) {
|
||||
skeleton := builder.skeleton
|
||||
if span.AIUsage.hasValue() {
|
||||
skeleton.aiUsage[int32(len(builder.parentIDs))] = span.AIUsage
|
||||
}
|
||||
if span.OtherReferences != "" {
|
||||
skeleton.references[int32(len(builder.parentIDs))] = span.OtherReferences
|
||||
}
|
||||
builder.ids = append(builder.ids, span.SpanID...)
|
||||
skeleton.idOffsets = append(skeleton.idOffsets, uint32(len(builder.ids)))
|
||||
builder.parentIDs = append(builder.parentIDs, span.ParentSpanID)
|
||||
skeleton.startNano = append(skeleton.startNano, span.StartTime.UnixNano())
|
||||
skeleton.durationNano = append(skeleton.durationNano, span.DurationNano)
|
||||
skeleton.hasError = append(skeleton.hasError, span.HasError)
|
||||
skeleton.hasExceptionEvent = append(skeleton.hasExceptionEvent, span.HasExceptionEvent)
|
||||
skeleton.hasLink = append(skeleton.hasLink, span.HasLink)
|
||||
skeleton.names = append(skeleton.names, builder.intern(span.Name))
|
||||
skeleton.services = append(skeleton.services, builder.intern(span.ServiceName))
|
||||
skeleton.kinds = append(skeleton.kinds, builder.intern(span.KindString))
|
||||
skeleton.responseStatusCodes = append(skeleton.responseStatusCodes, builder.intern(span.ResponseStatusCode))
|
||||
skeleton.statusCodeStrings = append(skeleton.statusCodeStrings, builder.intern(span.StatusCodeString))
|
||||
skeleton.statusMessages = append(skeleton.statusMessages, builder.intern(span.StatusMessage))
|
||||
}
|
||||
|
||||
// Build turns the added rows into the tree. The builder cannot be reused.
|
||||
func (builder *TraceSkeletonBuilder) Build() *TraceSkeleton {
|
||||
skeleton := builder.skeleton
|
||||
skeleton.spanIDs = string(builder.ids)
|
||||
n := len(builder.parentIDs)
|
||||
|
||||
// A span whose parent is not in the trace, or is the span itself, becomes a root.
|
||||
positions := make(map[string]int32, n)
|
||||
for i := range n {
|
||||
positions[skeleton.spanID(int32(i))] = int32(i)
|
||||
}
|
||||
for i, parentID := range builder.parentIDs {
|
||||
parent, ok := positions[parentID]
|
||||
if !ok || parent == int32(i) {
|
||||
parent = noParent
|
||||
if parentID != "" {
|
||||
skeleton.storedParentIDs[int32(i)] = parentID
|
||||
}
|
||||
}
|
||||
skeleton.parents = append(skeleton.parents, parent)
|
||||
}
|
||||
builder.parentIDs, builder.stringIndex, builder.ids = nil, nil, nil
|
||||
|
||||
skeleton.linkChildren()
|
||||
if skeleton.walkFromRoots() < n {
|
||||
skeleton.cutParentLoops()
|
||||
skeleton.linkChildren()
|
||||
skeleton.walkFromRoots()
|
||||
}
|
||||
|
||||
// Walking the tree order backwards reaches every span after all the spans below it.
|
||||
skeleton.descendantCount = make([]uint32, n)
|
||||
for k := n - 1; k >= 0; k-- {
|
||||
i := skeleton.treeOrder[k]
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.descendantCount[parent] += skeleton.descendantCount[i] + 1
|
||||
}
|
||||
}
|
||||
|
||||
skeleton.ownTime = make([]uint64, n)
|
||||
for i := range n {
|
||||
skeleton.ownTime[i] = skeleton.durationNano[i] - skeleton.timeCoveredByChildren(int32(i))
|
||||
}
|
||||
|
||||
skeleton.groupSameNameSiblings()
|
||||
return skeleton
|
||||
}
|
||||
|
||||
// siblingGroup totals the spans that share a name and a parent; a root is a group of its own.
|
||||
type siblingGroup struct {
|
||||
spanCount uint64
|
||||
ownTime uint64
|
||||
errCount uint64
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) len() int {
|
||||
return len(skeleton.parents)
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanID(i int32) string {
|
||||
return skeleton.spanIDs[skeleton.idOffsets[i]:skeleton.idOffsets[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) position(spanID string) (int32, bool) {
|
||||
for i := range int32(skeleton.len()) {
|
||||
if skeleton.spanID(i) == spanID {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) children(i int32) []int32 {
|
||||
return skeleton.childList[skeleton.childStart[i]:skeleton.childStart[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) parentSpanID(i int32) string {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
return skeleton.spanID(parent)
|
||||
}
|
||||
return skeleton.storedParentIDs[i]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanReferences(i int32) []OtelSpanRef {
|
||||
stored, ok := skeleton.references[i]
|
||||
if !ok {
|
||||
return []OtelSpanRef{{TraceId: skeleton.traceID, SpanId: skeleton.parentSpanID(i), RefType: refTypeChildOf}}
|
||||
}
|
||||
refs := []OtelSpanRef{}
|
||||
if err := json.Unmarshal([]byte(stored), &refs); err != nil {
|
||||
return []OtelSpanRef{} // skip malformed values
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
// unmarkedFailureKind is set for a span that reports a failure without the error flag. The response
|
||||
// status column holds an HTTP status or a gRPC status.
|
||||
func (skeleton *TraceSkeleton) unmarkedFailureKind(i int32) UnmarkedFailureKind {
|
||||
if skeleton.hasError[i] {
|
||||
return ""
|
||||
}
|
||||
if code, err := strconv.Atoi(skeleton.stringTable[skeleton.responseStatusCodes[i]]); err == nil {
|
||||
switch {
|
||||
case code >= 400 && code < 500:
|
||||
return UnmarkedFailureHTTP4xx
|
||||
case code >= 500 && code < 600:
|
||||
return UnmarkedFailureHTTP5xx
|
||||
case code >= 1 && code <= 16:
|
||||
return UnmarkedFailureGRPCStatus
|
||||
}
|
||||
}
|
||||
if skeleton.hasExceptionEvent[i] {
|
||||
return UnmarkedFailureExceptionEvent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) treeStats(i int32) SpanTreeStats {
|
||||
stats := SpanTreeStats{
|
||||
Level: skeleton.level[i],
|
||||
ChildCount: uint32(len(skeleton.children(i))),
|
||||
SubtreeSpanCount: skeleton.descendantCount[i],
|
||||
OwnTimeNano: skeleton.ownTime[i],
|
||||
}
|
||||
for p := skeleton.parents[i]; p != noParent && skeleton.hasError[p]; p = skeleton.parents[p] {
|
||||
stats.ErrorAncestorCount++
|
||||
}
|
||||
if group := skeleton.groups[skeleton.groupOf[i]]; group.spanCount > 1 {
|
||||
stats.SameNameSiblings = &SameNameSiblingStats{SpanCount: group.spanCount, OwnTimeNano: group.ownTime, ErrorSpanCount: group.errCount}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// serviceStats totals the spans of each service, the service with the most own time first.
|
||||
func (skeleton *TraceSkeleton) serviceStats() []TraceServiceStats {
|
||||
services := make([]TraceServiceStats, 0)
|
||||
positionOf := make(map[uint32]int)
|
||||
for i := range int32(skeleton.len()) {
|
||||
position, ok := positionOf[skeleton.services[i]]
|
||||
if !ok {
|
||||
position = len(services)
|
||||
positionOf[skeleton.services[i]] = position
|
||||
services = append(services, TraceServiceStats{ServiceName: skeleton.stringTable[skeleton.services[i]]})
|
||||
}
|
||||
services[position].SpanCount++
|
||||
services[position].OwnTimeNano += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
services[position].ErrorSpanCount++
|
||||
}
|
||||
}
|
||||
slices.SortFunc(services, func(a, b TraceServiceStats) int {
|
||||
return cmp.Or(cmp.Compare(b.OwnTimeNano, a.OwnTimeNano), strings.Compare(a.ServiceName, b.ServiceName))
|
||||
})
|
||||
return services
|
||||
}
|
||||
|
||||
func (usage AISpanUsage) hasValue() bool {
|
||||
return usage.InputTokens != nil || usage.OutputTokens != nil || usage.CacheReadTokens != nil ||
|
||||
usage.CacheWriteTokens != nil || usage.ReasoningTokens != nil || usage.Cost != nil
|
||||
}
|
||||
|
||||
// intern returns the index of value in the string table, adding it on first sight.
|
||||
func (builder *TraceSkeletonBuilder) intern(value string) uint32 {
|
||||
if idx, ok := builder.stringIndex[value]; ok {
|
||||
return idx
|
||||
}
|
||||
idx := uint32(len(builder.skeleton.stringTable))
|
||||
builder.skeleton.stringTable = append(builder.skeleton.stringTable, value)
|
||||
builder.stringIndex[value] = idx
|
||||
return idx
|
||||
}
|
||||
|
||||
// linkChildren fills roots, childStart and childList from parents: it counts the children of
|
||||
// every span, turns the counts into start offsets, then places each child.
|
||||
func (skeleton *TraceSkeleton) linkChildren() {
|
||||
n := skeleton.len()
|
||||
skeleton.childStart = make([]int32, n+1)
|
||||
skeleton.roots = skeleton.roots[:0]
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childStart[parent+1]++
|
||||
} else {
|
||||
skeleton.roots = append(skeleton.roots, int32(i))
|
||||
}
|
||||
}
|
||||
for i := range n {
|
||||
skeleton.childStart[i+1] += skeleton.childStart[i]
|
||||
}
|
||||
skeleton.childList = make([]int32, skeleton.childStart[n])
|
||||
next := slices.Clone(skeleton.childStart[:n])
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childList[next[parent]] = int32(i)
|
||||
next[parent]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// walkFromRoots fills treeOrder and level, and returns the number of spans it reached.
|
||||
func (skeleton *TraceSkeleton) walkFromRoots() int {
|
||||
n := skeleton.len()
|
||||
skeleton.treeOrder = make([]int32, 0, n)
|
||||
skeleton.level = make([]uint32, n)
|
||||
// Pushed in reverse, the earliest root and the earliest child are popped first.
|
||||
stack := make([]int32, 0, 64)
|
||||
for r := len(skeleton.roots) - 1; r >= 0; r-- {
|
||||
stack = append(stack, skeleton.roots[r])
|
||||
}
|
||||
for len(stack) > 0 {
|
||||
i := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
skeleton.treeOrder = append(skeleton.treeOrder, i)
|
||||
children := skeleton.children(i)
|
||||
for c := len(children) - 1; c >= 0; c-- {
|
||||
skeleton.level[children[c]] = skeleton.level[i] + 1
|
||||
stack = append(stack, children[c])
|
||||
}
|
||||
}
|
||||
return len(skeleton.treeOrder)
|
||||
}
|
||||
|
||||
// cutParentLoops handles spans no root reaches: they sit on a loop of parents (a under b, b under
|
||||
// a) or below one. The earliest unreached span of each loop becomes a root.
|
||||
func (skeleton *TraceSkeleton) cutParentLoops() {
|
||||
reached := make([]bool, skeleton.len())
|
||||
for _, i := range skeleton.treeOrder {
|
||||
reached[i] = true
|
||||
}
|
||||
for i := range int32(skeleton.len()) {
|
||||
if reached[i] {
|
||||
continue
|
||||
}
|
||||
skeleton.storedParentIDs[i] = skeleton.spanID(skeleton.parents[i])
|
||||
skeleton.parents[i] = noParent
|
||||
stack := []int32{i}
|
||||
for len(stack) > 0 {
|
||||
top := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
if !reached[top] {
|
||||
reached[top] = true
|
||||
stack = append(stack, skeleton.children(top)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// timeCoveredByChildren is the time of span i during which a child was running. Overlapping
|
||||
// children count once, and child time outside the span does not count.
|
||||
func (skeleton *TraceSkeleton) timeCoveredByChildren(i int32) uint64 {
|
||||
start := skeleton.startNano[i]
|
||||
end := start + int64(skeleton.durationNano[i])
|
||||
covered, cursor := int64(0), start
|
||||
for _, child := range skeleton.children(i) {
|
||||
childStart := max(skeleton.startNano[child], cursor)
|
||||
childEnd := min(skeleton.startNano[child]+int64(skeleton.durationNano[child]), end)
|
||||
if childEnd <= childStart {
|
||||
continue
|
||||
}
|
||||
covered += childEnd - childStart
|
||||
cursor = childEnd
|
||||
}
|
||||
return uint64(covered)
|
||||
}
|
||||
|
||||
// groupSameNameSiblings fills groups and groupOf: one group per name among the children of a span.
|
||||
func (skeleton *TraceSkeleton) groupSameNameSiblings() {
|
||||
n := skeleton.len()
|
||||
skeleton.groupOf = make([]int32, n)
|
||||
skeleton.groups = make([]siblingGroup, 0, n)
|
||||
addGroup := func(members []int32) {
|
||||
group := siblingGroup{}
|
||||
for _, i := range members {
|
||||
skeleton.groupOf[i] = int32(len(skeleton.groups))
|
||||
group.spanCount++
|
||||
group.ownTime += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
group.errCount++
|
||||
}
|
||||
}
|
||||
skeleton.groups = append(skeleton.groups, group)
|
||||
}
|
||||
|
||||
for r := range skeleton.roots {
|
||||
addGroup(skeleton.roots[r : r+1])
|
||||
}
|
||||
var siblings []int32
|
||||
for parent := range int32(n) {
|
||||
// Sorting by name puts same-name siblings side by side; the stable sort keeps their time order.
|
||||
siblings = append(siblings[:0], skeleton.children(parent)...)
|
||||
slices.SortStableFunc(siblings, func(a, b int32) int { return int(skeleton.names[a]) - int(skeleton.names[b]) })
|
||||
for first := 0; first < len(siblings); {
|
||||
end := first + 1
|
||||
for end < len(siblings) && skeleton.names[siblings[end]] == skeleton.names[siblings[first]] {
|
||||
end++
|
||||
}
|
||||
addGroup(siblings[first:end])
|
||||
first = end
|
||||
}
|
||||
}
|
||||
}
|
||||
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
@@ -0,0 +1,325 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type skeletonSpec struct {
|
||||
id, parent, name, service string
|
||||
startMs, durationMs int64
|
||||
hasError, hasException bool
|
||||
hasLink bool
|
||||
usage AISpanUsage
|
||||
statusCode string
|
||||
references string
|
||||
}
|
||||
|
||||
// buildSkeleton adds the spans in the given order, which stands for the store's start time order.
|
||||
func buildSkeleton(specs ...skeletonSpec) *TraceSkeleton {
|
||||
builder := NewTraceSkeletonBuilder("trace", len(specs))
|
||||
for _, spec := range specs {
|
||||
span := &SkeletonSpan{
|
||||
Span: Span{
|
||||
SpanID: spec.id,
|
||||
ParentSpanID: spec.parent,
|
||||
DurationNano: uint64(spec.durationMs) * uint64(time.Millisecond),
|
||||
HasError: spec.hasError,
|
||||
Name: spec.name,
|
||||
KindString: "Internal",
|
||||
ResponseStatusCode: spec.statusCode,
|
||||
},
|
||||
StartTime: time.Unix(100, 0).Add(time.Duration(spec.startMs) * time.Millisecond),
|
||||
ServiceName: spec.service,
|
||||
HasExceptionEvent: spec.hasException,
|
||||
HasLink: spec.hasLink,
|
||||
OtherReferences: spec.references,
|
||||
AIUsage: spec.usage,
|
||||
}
|
||||
builder.Add(span)
|
||||
}
|
||||
return builder.Build()
|
||||
}
|
||||
|
||||
func spanIDsOf(skeleton *TraceSkeleton, positions []int32) []string {
|
||||
spanIDs := make([]string, 0, len(positions))
|
||||
for _, i := range positions {
|
||||
spanIDs = append(spanIDs, skeleton.spanID(i))
|
||||
}
|
||||
return spanIDs
|
||||
}
|
||||
|
||||
func positionOf(t *testing.T, skeleton *TraceSkeleton, spanID string) int32 {
|
||||
t.Helper()
|
||||
for i := range int32(skeleton.len()) {
|
||||
if skeleton.spanID(i) == spanID {
|
||||
return i
|
||||
}
|
||||
}
|
||||
require.FailNow(t, "span not in skeleton", spanID)
|
||||
return noParent
|
||||
}
|
||||
|
||||
func TestTraceSkeletonOwnTime(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expected int64
|
||||
}{
|
||||
{
|
||||
// time (ms) 0 10 30 50 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// b |--------------| 30 ms
|
||||
name: "SequentialChildren_SubtractsEach",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "b", parent: "root", startMs: 50, durationMs: 30},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Calls fanned out at once, such as parallel queries. Together they cover 10 to 60.
|
||||
// time (ms) 0 10 20 30 40 50 60 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |-------------------| 40 ms
|
||||
// b |-------------------| 40 ms
|
||||
// c |----| 10 ms
|
||||
name: "ParallelChildren_CountsOverlapOnce",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 40},
|
||||
{id: "b", parent: "root", startMs: 20, durationMs: 40},
|
||||
{id: "c", parent: "root", startMs: 30, durationMs: 10},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Work the parent starts and does not wait for, such as a background job.
|
||||
// time (ms) 0 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |--------------> 500 ms, 20 of them inside root
|
||||
name: "ChildOutlivesParent_ClipsToParentEnd",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 80, durationMs: 500},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew: the child's host clock runs behind the parent's.
|
||||
// time (ms) 0 10 30 110
|
||||
// early |--------------| 30 ms, 20 of them inside root
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildStartsBeforeParent_ClipsToParentStart",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 30},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew again, with a child that also runs past the parent's end.
|
||||
// time (ms) 0 10 110
|
||||
// early |-----------------------------------------------------------> 500 ms
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildCoversParent_LeavesZero",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 500},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
// Only direct children count: a1 is taken from the time of a, not of root.
|
||||
// time (ms) 0 10 30 90 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// a1 |------------------------------------| 75 ms, child of a
|
||||
name: "Grandchild_NotSubtracted",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "a1", parent: "a", startMs: 15, durationMs: 75},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
name: "NoChildren_EqualsDuration",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 70},
|
||||
},
|
||||
expected: 70,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, uint64(testCase.expected)*uint64(time.Millisecond), skeleton.ownTime[positionOf(t, skeleton, "root")])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTree(t *testing.T) {
|
||||
// root 0 to 100
|
||||
// a 10 to 40
|
||||
// a1 15 to 20, error
|
||||
// b 50 to 60
|
||||
// orphan 60 to 70; its parent is not in the trace, so it is a second root
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", service: "web", startMs: 0, durationMs: 100},
|
||||
skeletonSpec{id: "a", parent: "root", name: "a", service: "web", startMs: 10, durationMs: 30},
|
||||
skeletonSpec{id: "a1", parent: "a", name: "a1", service: "db", startMs: 15, durationMs: 5, hasError: true},
|
||||
skeletonSpec{id: "b", parent: "root", name: "b", service: "web", startMs: 50, durationMs: 10},
|
||||
skeletonSpec{id: "orphan", parent: "gone", name: "orphan", service: "worker", startMs: 60, durationMs: 10},
|
||||
)
|
||||
|
||||
assert.Equal(t, []string{"root", "a", "a1", "b", "orphan"}, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
assert.Equal(t, []string{"root", "orphan"}, spanIDsOf(skeleton, skeleton.roots))
|
||||
// root: two children, three spans below it, and 100 less the 30 of a and the 10 of b.
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, ChildCount: 2, SubtreeSpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "root")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 2, OwnTimeNano: uint64(5 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "a1")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, OwnTimeNano: uint64(10 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "orphan")))
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTreeStats(t *testing.T) {
|
||||
// root error
|
||||
// handler error
|
||||
// q1 SELECT, 10 ms
|
||||
// q2 SELECT, 30 ms, error
|
||||
// cache
|
||||
// evict error
|
||||
// q3 SELECT, 20 ms
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", startMs: 0, durationMs: 100, hasError: true},
|
||||
skeletonSpec{id: "handler", parent: "root", name: "handler", startMs: 0, durationMs: 90, hasError: true},
|
||||
skeletonSpec{id: "q1", parent: "handler", name: "SELECT", startMs: 0, durationMs: 10},
|
||||
skeletonSpec{id: "q2", parent: "handler", name: "SELECT", startMs: 10, durationMs: 30, hasError: true},
|
||||
skeletonSpec{id: "cache", parent: "handler", name: "GET cache", startMs: 40, durationMs: 5},
|
||||
skeletonSpec{id: "evict", parent: "cache", name: "evict", startMs: 41, durationMs: 2, hasError: true},
|
||||
skeletonSpec{id: "q3", parent: "handler", name: "SELECT", startMs: 50, durationMs: 20},
|
||||
)
|
||||
|
||||
// q2 has two error spans above it, and shares its name with q1 and q3.
|
||||
stats := skeleton.treeStats(positionOf(t, skeleton, "q2"))
|
||||
assert.Equal(t, uint32(2), stats.ErrorAncestorCount)
|
||||
require.NotNil(t, stats.SameNameSiblings)
|
||||
assert.Equal(t, SameNameSiblingStats{SpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond), ErrorSpanCount: 1}, *stats.SameNameSiblings)
|
||||
|
||||
cache := skeleton.treeStats(positionOf(t, skeleton, "cache"))
|
||||
assert.Nil(t, cache.SameNameSiblings)
|
||||
assert.Equal(t, uint32(2), cache.ErrorAncestorCount)
|
||||
|
||||
// The count stops at the first ancestor that is not an error: cache, the parent of evict.
|
||||
assert.Equal(t, uint32(0), skeleton.treeStats(positionOf(t, skeleton, "evict")).ErrorAncestorCount)
|
||||
}
|
||||
|
||||
func TestTraceSkeletonUnmarkedFailureKind(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
spec skeletonSpec
|
||||
expected UnmarkedFailureKind
|
||||
}{
|
||||
{name: "HTTP400_LowestClientError", spec: skeletonSpec{statusCode: "400"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP499_HighestClientError", spec: skeletonSpec{statusCode: "499"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP200_NotAFailure", spec: skeletonSpec{statusCode: "200"}},
|
||||
// Instrumentation should flag a 5xx as an error; proxies and hand-written spans often do not.
|
||||
{name: "HTTP500_LowestServerError", spec: skeletonSpec{statusCode: "500"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP599_HighestServerError", spec: skeletonSpec{statusCode: "599"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP600_NotAFailure", spec: skeletonSpec{statusCode: "600"}},
|
||||
{name: "GRPC1_LowestFailure", spec: skeletonSpec{statusCode: "1"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC16_HighestFailure", spec: skeletonSpec{statusCode: "16"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC0_OK", spec: skeletonSpec{statusCode: "0"}},
|
||||
{name: "ExceptionEvent_WithoutStatusCode", spec: skeletonSpec{hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "ExceptionEvent_WithSuccessStatusCode", spec: skeletonSpec{statusCode: "200", hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "StatusCodeAndExceptionEvent_ReportsStatusCode", spec: skeletonSpec{statusCode: "404", hasException: true}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "ErrorFlag_NeverUnmarked", spec: skeletonSpec{statusCode: "404", hasException: true, hasError: true}},
|
||||
{name: "NoSignal_NotAFailure", spec: skeletonSpec{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
testCase.spec.id = "span"
|
||||
skeleton := buildSkeleton(testCase.spec)
|
||||
assert.Equal(t, testCase.expected, skeleton.unmarkedFailureKind(0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No valid trace has a parent loop; it comes from instrumentation that reuses span ids. Every span
|
||||
// must still be listed once.
|
||||
func TestTraceSkeletonParentLoop(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expectedRoots []string
|
||||
expectedTreeOrder []string
|
||||
}{
|
||||
{
|
||||
// x is the earliest span of the loop, so it becomes a root; y and under-y stay below it.
|
||||
name: "TwoSpansPointAtEachOther",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 10},
|
||||
{id: "x", parent: "y", startMs: 1, durationMs: 5},
|
||||
{id: "y", parent: "x", startMs: 2, durationMs: 5},
|
||||
{id: "under-y", parent: "y", startMs: 3, durationMs: 1},
|
||||
},
|
||||
expectedRoots: []string{"root", "x"},
|
||||
expectedTreeOrder: []string{"root", "x", "y", "under-y"},
|
||||
},
|
||||
{
|
||||
name: "SpanIsItsOwnParent",
|
||||
specs: []skeletonSpec{
|
||||
{id: "self", parent: "self", startMs: 0, durationMs: 10},
|
||||
{id: "child", parent: "self", startMs: 1, durationMs: 5},
|
||||
},
|
||||
expectedRoots: []string{"self"},
|
||||
expectedTreeOrder: []string{"self", "child"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, testCase.expectedRoots, spanIDsOf(skeleton, skeleton.roots))
|
||||
assert.Equal(t, testCase.expectedTreeOrder, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonSpan_ParentAndReferences(t *testing.T) {
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root"},
|
||||
skeletonSpec{id: "child", parent: "root"},
|
||||
skeletonSpec{id: "linked", parent: "root", references: `[{"traceId":"trace","spanId":"root","refType":"CHILD_OF"},{"traceId":"other","spanId":"far","refType":"FOLLOWS_FROM"}]`},
|
||||
skeletonSpec{id: "orphan", parent: "gone"},
|
||||
// a and b are each other's parent; a, the earliest, becomes a root.
|
||||
skeletonSpec{id: "a", parent: "b"},
|
||||
skeletonSpec{id: "b", parent: "a"},
|
||||
)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
spanID string
|
||||
parentSpanID string
|
||||
references []OtelSpanRef
|
||||
}{
|
||||
{name: "NoStoredReferences_RebuiltFromTheParent", spanID: "child", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}}},
|
||||
{name: "StoredReferences_ReturnedAsStored", spanID: "linked", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}, {TraceId: "other", SpanId: "far", RefType: "FOLLOWS_FROM"}}},
|
||||
{name: "MissingParent_KeepsTheStoredParentID", spanID: "orphan", parentSpanID: "gone", references: []OtelSpanRef{{TraceId: "trace", SpanId: "gone", RefType: "CHILD_OF"}}},
|
||||
{name: "ParentLoop_KeepsTheStoredParentID", spanID: "a", parentSpanID: "b", references: []OtelSpanRef{{TraceId: "trace", SpanId: "b", RefType: "CHILD_OF"}}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
span := skeleton.span(positionOf(t, skeleton, testCase.spanID))
|
||||
assert.Equal(t, testCase.parentSpanID, span.ParentSpanID)
|
||||
assert.Equal(t, testCase.references, span.References)
|
||||
})
|
||||
}
|
||||
}
|
||||
574
pkg/types/spantypes/trace_span_list.go
Normal file
574
pkg/types/spantypes/trace_span_list.go
Normal file
@@ -0,0 +1,574 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
const (
|
||||
SpanScopeTrace SpanScope = "trace"
|
||||
SpanScopeChildren SpanScope = "children"
|
||||
SpanScopeDescendants SpanScope = "descendants"
|
||||
SpanScopeAncestors SpanScope = "ancestors"
|
||||
)
|
||||
|
||||
const (
|
||||
spanListDefaultLimit = 50
|
||||
spanListMaxLimit = 1000
|
||||
|
||||
spanMatchLimit = 3
|
||||
spanMatchSnippetRadius = 40
|
||||
snippetMark = "…"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCodeTraceSpansInvalidLimit = errors.MustNewCode("trace_spans_invalid_limit")
|
||||
ErrCodeTraceSpansInvalidOffset = errors.MustNewCode("trace_spans_invalid_offset")
|
||||
ErrCodeTraceSpansInvalidView = errors.MustNewCode("trace_spans_invalid_view")
|
||||
)
|
||||
|
||||
// SpanScope says which spans of a trace a list route covers: all of them, or the ones related to one span.
|
||||
type SpanScope string
|
||||
|
||||
type SpanListQuery struct {
|
||||
Scope SpanScope
|
||||
// ScopeSpanID is the span the scope is relative to. Empty when the scope is the whole trace.
|
||||
ScopeSpanID string
|
||||
// View is empty when every span the scope covers is wanted.
|
||||
View SpanListView
|
||||
// Query is a filter expression. Empty when there is nothing to match.
|
||||
Query string
|
||||
SelectFields []telemetrytypes.TelemetryFieldKey
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
|
||||
// SpanListPage is one page of a span list picked from the tree, before the stored data of its spans is read.
|
||||
type SpanListPage struct {
|
||||
skeleton *TraceSkeleton
|
||||
view SpanListView
|
||||
// total counts the spans the page was cut from.
|
||||
total uint64
|
||||
positions []int32
|
||||
selectFields []telemetrytypes.TelemetryFieldKey
|
||||
// words holds the query's search() calls; warnings holds what the query could not use.
|
||||
words []SearchWord
|
||||
warnings []string
|
||||
}
|
||||
|
||||
type SpanSearch struct {
|
||||
SpanIDs []string
|
||||
// Words holds the query's search() calls.
|
||||
Words []SearchWord
|
||||
Warnings []string
|
||||
}
|
||||
|
||||
// SearchWord is the text of a search() call and the parts of a span it searches: span, attribute,
|
||||
// resource or event. No contexts means every part.
|
||||
type SearchWord struct {
|
||||
Text string
|
||||
Contexts []telemetrytypes.FieldContext
|
||||
}
|
||||
|
||||
func NewSpanListQuery(params *ListTraceSpansParams, scope SpanScope, scopeSpanID string) (*SpanListQuery, error) {
|
||||
query := &SpanListQuery{Scope: scope, ScopeSpanID: scopeSpanID, View: params.View, Query: strings.TrimSpace(params.Query), Offset: params.Offset}
|
||||
if query.View != "" {
|
||||
if err := validateSpanListView(query.View); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if params.Offset < 0 {
|
||||
return nil, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidOffset, "offset cannot be negative, got %d", params.Offset)
|
||||
}
|
||||
limit, err := pageLimit("limit", params.Limit, spanListDefaultLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query.Limit = limit
|
||||
|
||||
for _, text := range params.SelectFields {
|
||||
if text = strings.TrimSpace(text); text != "" {
|
||||
query.SelectFields = append(query.SelectFields, newSelectField(text))
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
// NewSpanListPage picks the page the query asks for. search holds the spans that match the
|
||||
// query's text, and is nil when the query has none.
|
||||
func NewSpanListPage(skeleton *TraceSkeleton, query *SpanListQuery, search *SpanSearch) (*SpanListPage, error) {
|
||||
scope, err := skeleton.scopePositions(query.Scope, query.ScopeSpanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if search != nil {
|
||||
scope = skeleton.spansAmong(scope, search.SpanIDs)
|
||||
}
|
||||
page := skeleton.page(scope, query.View, query.Offset, query.Limit)
|
||||
page.selectFields = query.SelectFields
|
||||
if search != nil {
|
||||
page.words, page.warnings = search.Words, search.Warnings
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// ReadsAttributes reports whether building the page needs the full stored rows of its spans.
|
||||
func (page *SpanListPage) ReadsAttributes() bool {
|
||||
return len(page.selectFields) > 0 || len(page.words) > 0
|
||||
}
|
||||
|
||||
func (page *SpanListPage) SpanIDs() []string {
|
||||
spanIDs := make([]string, 0, len(page.positions))
|
||||
for _, i := range page.positions {
|
||||
spanIDs = append(spanIDs, page.skeleton.spanID(i))
|
||||
}
|
||||
return spanIDs
|
||||
}
|
||||
|
||||
// NewSpanList builds the page. rows holds the stored data of its spans, read only for the selected
|
||||
// fields and the matched words. A selected field no span of the page has is reported as a warning.
|
||||
func NewSpanList(page *SpanListPage, rows []StorableSpan) *SpanList {
|
||||
byID := make(map[string]*StorableSpan, len(rows))
|
||||
for i := range rows {
|
||||
byID[rows[i].SpanID] = &rows[i]
|
||||
}
|
||||
|
||||
skeleton := page.skeleton
|
||||
list := &SpanList{Total: page.total, Items: make([]SpanItem, 0, len(page.positions)), Warnings: slices.Clone(page.warnings)}
|
||||
found := make([]bool, len(page.selectFields))
|
||||
for _, i := range page.positions {
|
||||
item := SpanItem{Span: skeleton.span(i), TreeStats: skeleton.treeStats(i), UnmarkedFailureKind: skeleton.unmarkedFailureKind(i)}
|
||||
if page.view == SpanListViewAIUsage {
|
||||
skeleton.setUsageAttributes(&item.Span, i)
|
||||
}
|
||||
row := byID[skeleton.spanID(i)]
|
||||
item.Span.selectFields(row, page.selectFields, found)
|
||||
item.Matches = findWords(row, page.words)
|
||||
list.Items = append(list.Items, item)
|
||||
}
|
||||
for k, field := range page.selectFields {
|
||||
if !found[k] && len(list.Items) > 0 {
|
||||
list.Warnings = append(list.Warnings, fmt.Sprintf("field `%s` was not found on any returned span", telemetrytypes.TelemetryFieldKeyToText(&field)))
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func validateSpanListView(view SpanListView) error {
|
||||
if !slices.Contains(SpanListView("").Enum(), any(view)) {
|
||||
return errors.NewInvalidInputf(ErrCodeTraceSpansInvalidView, "invalid view %q, expected one of error_origins, unmarked_failures, time_spent, ai_usage, links", string(view))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSelectField reads a name into its context and bare name. The data type is not used.
|
||||
func newSelectField(text string) telemetrytypes.TelemetryFieldKey {
|
||||
key := telemetrytypes.GetFieldKeyFromKeyText(text)
|
||||
key.FieldDataType = telemetrytypes.FieldDataTypeUnspecified
|
||||
return key
|
||||
}
|
||||
|
||||
// selectFields fills span with the selected fields of row and marks in found the ones row has. A
|
||||
// name is read as a trace list query reads it: a field of the span itself first, then an attribute.
|
||||
func (span *Span) selectFields(row *StorableSpan, fields []telemetrytypes.TelemetryFieldKey, found []bool) {
|
||||
if row == nil || len(fields) == 0 {
|
||||
return
|
||||
}
|
||||
resource, attributes := row.Resource(), row.Attributes()
|
||||
for k, field := range fields {
|
||||
onRow, isSpanField := span.selectSpanField(row, &field)
|
||||
if !isSpanField {
|
||||
onRow = span.selectAttribute(resource, attributes, &field)
|
||||
}
|
||||
found[k] = found[k] || onRow
|
||||
}
|
||||
}
|
||||
|
||||
// selectSpanField copies a field of the span itself from row. known is false when field does not
|
||||
// name one, and found is false when the span has no value for it.
|
||||
func (span *Span) selectSpanField(row *StorableSpan, field *telemetrytypes.TelemetryFieldKey) (found, known bool) {
|
||||
name := field.Name
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextSpan:
|
||||
case telemetrytypes.FieldContextScope:
|
||||
return span.selectScope(row, name), true
|
||||
default:
|
||||
return false, false
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "span_id", "trace_id", "parent_span_id", "name", "kind_string", "timestamp", "duration_nano",
|
||||
"has_error", "status_code_string", "status_message", "response_status_code":
|
||||
// Every span already carries these.
|
||||
return true, true
|
||||
case "http_method":
|
||||
return setString(&span.HTTPMethod, row.HTTPMethod), true
|
||||
case "http_url":
|
||||
return setString(&span.HTTPURL, row.HTTPURL), true
|
||||
case "http_host":
|
||||
return setString(&span.HTTPHost, row.HTTPHost), true
|
||||
case "external_http_method":
|
||||
return setString(&span.ExternalHTTPMethod, row.ExternalHTTPMethod), true
|
||||
case "external_http_url":
|
||||
return setString(&span.ExternalHTTPURL, row.ExternalHTTPURL), true
|
||||
case "db_name":
|
||||
return setString(&span.DBName, row.DBName), true
|
||||
case "db_operation":
|
||||
return setString(&span.DBOperation, row.DBOperation), true
|
||||
case "trace_state":
|
||||
return setString(&span.TraceState, row.TraceState), true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// selectScope copies the scope's name, version or, for any other name, a scope attribute from row,
|
||||
// keeping the scope attributes already selected.
|
||||
func (span *Span) selectScope(row *StorableSpan, name string) bool {
|
||||
if name == scopeName || name == scopeVersion {
|
||||
name = "scope." + name
|
||||
}
|
||||
selected := NewSelectedScope(row.Scope.Flatten(), []string{name})
|
||||
if len(selected) == 0 {
|
||||
return false
|
||||
}
|
||||
if span.Scope == nil {
|
||||
span.Scope = Scope{}
|
||||
}
|
||||
for key, value := range selected {
|
||||
attributes, isAttributes := value.(map[string]any)
|
||||
if selectedAttributes, ok := span.Scope[key].(map[string]any); isAttributes && ok {
|
||||
maps.Copy(selectedAttributes, attributes)
|
||||
continue
|
||||
}
|
||||
span.Scope[key] = value
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// selectAttribute copies an attribute or a resource attribute, and reports whether the span has it.
|
||||
// A name without a context is looked up in both.
|
||||
func (span *Span) selectAttribute(resource map[string]string, attributes map[string]any, field *telemetrytypes.TelemetryFieldKey) bool {
|
||||
found := false
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextResource:
|
||||
if value, ok := resource[field.Name]; ok {
|
||||
span.Resource[field.Name], found = value, true
|
||||
}
|
||||
}
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextAttribute, telemetrytypes.FieldContextSpan:
|
||||
if value, ok := attributes[field.Name]; ok {
|
||||
span.Attributes[field.Name], found = value, true
|
||||
}
|
||||
}
|
||||
// The context word can be part of an attribute name, as in an attribute named resource.type.
|
||||
if text := telemetrytypes.TelemetryFieldKeyToText(field); !found {
|
||||
if value, ok := attributes[text]; ok {
|
||||
span.Attributes[text], found = value, true
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func setString(target *string, value string) bool {
|
||||
*target = value
|
||||
return value != ""
|
||||
}
|
||||
|
||||
// findWords returns up to three places in the span where one of the words occurs, ignoring case,
|
||||
// each word only in the parts its search() call searches.
|
||||
func findWords(row *StorableSpan, words []SearchWord) []SpanTextMatch {
|
||||
if row == nil || len(words) == 0 {
|
||||
return nil
|
||||
}
|
||||
found := make([]SpanTextMatch, 0)
|
||||
// check notes the first of texts that holds a word, and reports whether enough places were found.
|
||||
check := func(context telemetrytypes.FieldContext, field string, texts ...string) bool {
|
||||
for _, text := range texts {
|
||||
for _, word := range words {
|
||||
if len(word.Contexts) > 0 && !slices.Contains(word.Contexts, context) {
|
||||
continue
|
||||
}
|
||||
if snippet, ok := snippetAround(text, word.Text); ok {
|
||||
found = append(found, SpanTextMatch{Field: field, Snippet: snippet})
|
||||
return len(found) == spanMatchLimit
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if check(telemetrytypes.FieldContextSpan, "name", row.Name) || check(telemetrytypes.FieldContextSpan, "status_message", row.StatusMessage) {
|
||||
return found
|
||||
}
|
||||
attributes := row.Attributes()
|
||||
for _, key := range slices.Sorted(maps.Keys(attributes)) {
|
||||
if check(telemetrytypes.FieldContextAttribute, "attributes."+key, attributeText(attributes[key]), key) {
|
||||
return found
|
||||
}
|
||||
}
|
||||
resource := row.Resource()
|
||||
for _, key := range slices.Sorted(maps.Keys(resource)) {
|
||||
if check(telemetrytypes.FieldContextResource, "resource."+key, resource[key], key) {
|
||||
return found
|
||||
}
|
||||
}
|
||||
for index, event := range row.UnmarshalledEvents() {
|
||||
texts := []string{event.Name}
|
||||
for _, key := range slices.Sorted(maps.Keys(event.AttributeMap)) {
|
||||
texts = append(texts, attributeText(event.AttributeMap[key]), key)
|
||||
}
|
||||
if check(telemetrytypes.FieldContextEvent, fmt.Sprintf("events[%d]", index), texts...) {
|
||||
return found
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// attributeText writes a number in plain digits, as the store does when it matches a word:
|
||||
// fmt writes 1234567 as 1.234567e+06.
|
||||
func attributeText(value any) string {
|
||||
if number, ok := value.(float64); ok {
|
||||
return strconv.FormatFloat(number, 'f', -1, 64)
|
||||
}
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
|
||||
// snippetAround returns the text around the first place word occurs in value, ignoring case.
|
||||
func snippetAround(value, word string) (string, bool) {
|
||||
at, wordEnd, ok := indexFold(value, word)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
start := max(at-spanMatchSnippetRadius, 0)
|
||||
end := min(wordEnd+spanMatchSnippetRadius, len(value))
|
||||
for start > 0 && !utf8.RuneStart(value[start]) {
|
||||
start--
|
||||
}
|
||||
for end < len(value) && !utf8.RuneStart(value[end]) {
|
||||
end++
|
||||
}
|
||||
snippet := value[start:end]
|
||||
if start > 0 {
|
||||
snippet = snippetMark + snippet
|
||||
}
|
||||
if end < len(value) {
|
||||
snippet += snippetMark
|
||||
}
|
||||
return snippet, true
|
||||
}
|
||||
|
||||
// indexFold returns the byte range of the first place word occurs in value, ignoring case. The word
|
||||
// is found in the lowered text, and the position is then walked back to the original: a lowered
|
||||
// character can take fewer or more bytes.
|
||||
func indexFold(value, word string) (start, end int, ok bool) {
|
||||
word = strings.ToLower(word)
|
||||
at := strings.Index(strings.ToLower(value), word)
|
||||
if at < 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
start, end = -1, len(value)
|
||||
lowered := 0
|
||||
for i, char := range value {
|
||||
if lowered == at {
|
||||
start = i
|
||||
}
|
||||
if lowered == at+len(word) {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
lowered += utf8.RuneLen(unicode.ToLower(char))
|
||||
}
|
||||
return start, end, start >= 0
|
||||
}
|
||||
|
||||
func pageLimit(name string, value, fallback int) (int, error) {
|
||||
switch {
|
||||
case value < 0 || value > spanListMaxLimit:
|
||||
return 0, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidLimit, "%s must be between 1 and %d, got %d", name, spanListMaxLimit, value)
|
||||
case value == 0:
|
||||
return fallback, nil
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// page cuts one page out of the spans of scope. A view keeps the ones of its kind, in its own order.
|
||||
func (skeleton *TraceSkeleton) page(scope []int32, view SpanListView, offset, limit int) *SpanListPage {
|
||||
positions := scope
|
||||
if view != "" {
|
||||
positions = skeleton.viewPositions(view, scope)
|
||||
}
|
||||
page := &SpanListPage{skeleton: skeleton, view: view, total: uint64(len(positions))}
|
||||
if offset < len(positions) {
|
||||
page.positions = positions[offset:min(offset+limit, len(positions))]
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// scopePositions lists the spans a scope covers, in the scope's own order.
|
||||
func (skeleton *TraceSkeleton) scopePositions(scope SpanScope, spanID string) ([]int32, error) {
|
||||
if scope == SpanScopeTrace {
|
||||
return skeleton.treeOrder, nil
|
||||
}
|
||||
span, ok := skeleton.position(spanID)
|
||||
if !ok {
|
||||
return nil, errors.NewNotFoundf(ErrCodeTraceSpanNotFound, "span %s not found in trace %s", spanID, skeleton.traceID)
|
||||
}
|
||||
switch scope {
|
||||
case SpanScopeChildren:
|
||||
return skeleton.children(span), nil
|
||||
case SpanScopeDescendants:
|
||||
// The spans below a span follow it directly in tree order.
|
||||
at := slices.Index(skeleton.treeOrder, span)
|
||||
return skeleton.treeOrder[at+1 : at+1+int(skeleton.descendantCount[span])], nil
|
||||
case SpanScopeAncestors:
|
||||
ancestors := make([]int32, 0, skeleton.level[span])
|
||||
for parent := skeleton.parents[span]; parent != noParent; parent = skeleton.parents[parent] {
|
||||
ancestors = append(ancestors, parent)
|
||||
}
|
||||
return ancestors, nil
|
||||
}
|
||||
return nil, errors.NewInternalf(errors.CodeInternal, "unknown span scope %q", string(scope))
|
||||
}
|
||||
|
||||
// spansAmong keeps the spans of scope whose id is one of spanIDs, in the order of scope.
|
||||
func (skeleton *TraceSkeleton) spansAmong(scope []int32, spanIDs []string) []int32 {
|
||||
wanted := make(map[string]struct{}, len(spanIDs))
|
||||
for _, spanID := range spanIDs {
|
||||
wanted[spanID] = struct{}{}
|
||||
}
|
||||
spans := make([]int32, 0, min(len(scope), len(spanIDs)))
|
||||
for _, i := range scope {
|
||||
if _, ok := wanted[skeleton.spanID(i)]; ok {
|
||||
spans = append(spans, i)
|
||||
}
|
||||
}
|
||||
return spans
|
||||
}
|
||||
|
||||
// viewPositions lists the spans of scope that are in a view, in the order of the view.
|
||||
func (skeleton *TraceSkeleton) viewPositions(view SpanListView, scope []int32) []int32 {
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
return skeleton.spansWhere(scope, skeleton.errorStartsAt)
|
||||
case SpanListViewUnmarkedFailures:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.unmarkedFailureKind(i) != "" })
|
||||
case SpanListViewLinks:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.hasLink[i] })
|
||||
case SpanListViewTimeSpent:
|
||||
return skeleton.timeSpentSpans(scope)
|
||||
case SpanListViewAIUsage:
|
||||
return skeleton.aiUsageSpans(scope)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// errorStartsAt reports whether span i is an error span with no error span among its children.
|
||||
func (skeleton *TraceSkeleton) errorStartsAt(i int32) bool {
|
||||
return skeleton.hasError[i] && !slices.ContainsFunc(skeleton.children(i), func(child int32) bool { return skeleton.hasError[child] })
|
||||
}
|
||||
|
||||
// spansWhere lists the spans of scope that match, in start time order.
|
||||
func (skeleton *TraceSkeleton) spansWhere(scope []int32, match func(i int32) bool) []int32 {
|
||||
spans := make([]int32, 0)
|
||||
for _, i := range scope {
|
||||
if match(i) {
|
||||
spans = append(spans, i)
|
||||
}
|
||||
}
|
||||
slices.Sort(spans)
|
||||
return spans
|
||||
}
|
||||
|
||||
// timeSpentSpans lists one span for each sibling group in scope, its longest there, the group with
|
||||
// the most own time first. Equal groups fall back to span order, so that every page cuts the same ranking.
|
||||
func (skeleton *TraceSkeleton) timeSpentSpans(scope []int32) []int32 {
|
||||
longest := slices.Repeat([]int32{-1}, len(skeleton.groups))
|
||||
for _, i := range scope {
|
||||
group := skeleton.groupOf[i]
|
||||
if longest[group] < 0 || skeleton.durationNano[i] > skeleton.durationNano[longest[group]] {
|
||||
longest[group] = i
|
||||
}
|
||||
}
|
||||
spans := slices.DeleteFunc(longest, func(i int32) bool { return i < 0 })
|
||||
groupOwnTime := func(i int32) uint64 { return skeleton.groups[skeleton.groupOf[i]].ownTime }
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(groupOwnTime(b), groupOwnTime(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// aiUsageSpans lists the spans of scope that carry gen_ai usage by cost, or by tokens when none
|
||||
// of them carries a cost; equal spans fall back to span order.
|
||||
func (skeleton *TraceSkeleton) aiUsageSpans(scope []int32) []int32 {
|
||||
spans := skeleton.spansWhere(scope, func(i int32) bool {
|
||||
_, ok := skeleton.aiUsage[i]
|
||||
return ok
|
||||
})
|
||||
hasCost := slices.ContainsFunc(spans, func(i int32) bool { return skeleton.aiUsage[i].Cost != nil })
|
||||
weight := func(i int32) float64 {
|
||||
usage := skeleton.aiUsage[i]
|
||||
if hasCost {
|
||||
return floatValue(usage.Cost)
|
||||
}
|
||||
return floatValue(usage.InputTokens) + floatValue(usage.OutputTokens)
|
||||
}
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(weight(b), weight(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// span returns span i with service.name as its only resource attribute.
|
||||
func (skeleton *TraceSkeleton) span(i int32) Span {
|
||||
return Span{
|
||||
SpanID: skeleton.spanID(i),
|
||||
TraceID: skeleton.traceID,
|
||||
ParentSpanID: skeleton.parentSpanID(i),
|
||||
Name: skeleton.stringTable[skeleton.names[i]],
|
||||
KindString: skeleton.stringTable[skeleton.kinds[i]],
|
||||
TimeUnix: uint64(skeleton.startNano[i] / 1_000_000),
|
||||
DurationNano: skeleton.durationNano[i],
|
||||
HasError: skeleton.hasError[i],
|
||||
StatusCodeString: skeleton.stringTable[skeleton.statusCodeStrings[i]],
|
||||
StatusMessage: skeleton.stringTable[skeleton.statusMessages[i]],
|
||||
ResponseStatusCode: skeleton.stringTable[skeleton.responseStatusCodes[i]],
|
||||
Resource: map[string]string{"service.name": skeleton.stringTable[skeleton.services[i]]},
|
||||
Attributes: map[string]any{},
|
||||
Events: []Event{},
|
||||
References: skeleton.spanReferences(i),
|
||||
}
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) setUsageAttributes(span *Span, i int32) {
|
||||
usage := skeleton.aiUsage[i]
|
||||
for key, value := range map[string]*float64{
|
||||
aiobservabilitytypes.GenAIUsageInputTokens: usage.InputTokens,
|
||||
aiobservabilitytypes.GenAIUsageOutputTokens: usage.OutputTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheReadInputTokens: usage.CacheReadTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheCreationInputTokens: usage.CacheWriteTokens,
|
||||
aiobservabilitytypes.GenAIUsageReasoningOutputTokens: usage.ReasoningTokens,
|
||||
aiobservabilitytypes.SignozGenAITotalCost: usage.Cost,
|
||||
} {
|
||||
if value != nil {
|
||||
span.Attributes[key] = *value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func floatValue(value *float64) float64 {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return *value
|
||||
}
|
||||
361
pkg/types/spantypes/trace_span_list_test.go
Normal file
361
pkg/types/spantypes/trace_span_list_test.go
Normal file
@@ -0,0 +1,361 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
// checkoutSkeleton is one request with a failing payment call, a group of same-name queries and
|
||||
// an orphan. usage sets the gen_ai usage of the named spans.
|
||||
func checkoutSkeleton(usage map[string]AISpanUsage) *TraceSkeleton {
|
||||
return buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "POST /checkout", service: "web", startMs: 0, durationMs: 100, hasError: true},
|
||||
skeletonSpec{id: "pay", parent: "root", name: "charge", service: "payment", startMs: 0, durationMs: 40, hasError: true, hasLink: true},
|
||||
skeletonSpec{id: "grpc", parent: "pay", name: "Charge", service: "payment", startMs: 5, durationMs: 5, statusCode: "14", usage: usage["grpc"]},
|
||||
skeletonSpec{id: "caught", parent: "pay", name: "retry", service: "payment", startMs: 10, durationMs: 5, hasException: true},
|
||||
skeletonSpec{id: "q1", parent: "root", name: "SELECT", service: "db", startMs: 40, durationMs: 10, usage: usage["q1"]},
|
||||
skeletonSpec{id: "q2", parent: "root", name: "SELECT", service: "db", startMs: 50, durationMs: 25, hasLink: true, usage: usage["q2"]},
|
||||
skeletonSpec{id: "auth", parent: "root", name: "GET /auth", service: "auth", startMs: 75, durationMs: 5, statusCode: "404", usage: usage["auth"]},
|
||||
skeletonSpec{id: "orphan", parent: "gone", name: "flush", service: "worker", startMs: 90, durationMs: 60},
|
||||
)
|
||||
}
|
||||
|
||||
func TestTraceSkeletonPage_Ranking(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
view SpanListView
|
||||
usage map[string]AISpanUsage
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
// own time: orphan 60, the two SELECTs 35 together, pay 30, root 20, then the 5s in start order.
|
||||
name: "TimeSpent_GroupsSameNameSiblings",
|
||||
view: SpanListViewTimeSpent,
|
||||
expected: []string{"orphan", "q2", "pay", "root", "grpc", "caught", "auth"},
|
||||
},
|
||||
{
|
||||
// grpc has tokens and no cost, so it ranks last.
|
||||
name: "AIUsage_ByCost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {Cost: value(0.01)}, "auth": {Cost: value(0.5)}, "grpc": {InputTokens: value(900)}},
|
||||
expected: []string{"auth", "q1", "grpc"},
|
||||
},
|
||||
{
|
||||
// auth carries no token or cost value, so it is not listed.
|
||||
name: "AIUsage_ByTokensWhenNoSpanHasACost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {InputTokens: value(10), OutputTokens: value(5)}, "q2": {InputTokens: value(100)}, "auth": {}},
|
||||
expected: []string{"q2", "q1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(testCase.usage)
|
||||
page := skeleton.page(skeleton.treeOrder, testCase.view, 0, 50)
|
||||
assert.Equal(t, testCase.expected, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(len(testCase.expected)), page.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonPage_CutsTheViewOfTheGivenSpans(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(nil)
|
||||
|
||||
// Among the children of root: the two SELECTs as one, then pay, then auth.
|
||||
page := skeleton.page(skeleton.children(positionOf(t, skeleton, "root")), SpanListViewTimeSpent, 1, 5)
|
||||
assert.Equal(t, []string{"pay", "auth"}, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(3), page.total)
|
||||
}
|
||||
|
||||
func TestNewSpanList_OnlyAIUsageCarriesUsageAttributes(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
skeleton := checkoutSkeleton(map[string]AISpanUsage{"q1": {InputTokens: value(120), OutputTokens: value(30), Cost: value(0.02)}})
|
||||
|
||||
usage := NewSpanList(skeleton.page(skeleton.treeOrder, SpanListViewAIUsage, 0, 50), nil)
|
||||
require.Len(t, usage.Items, 1)
|
||||
assert.Equal(t, map[string]any{"gen_ai.usage.input_tokens": 120.0, "gen_ai.usage.output_tokens": 30.0, "signoz.gen_ai.usage.tokens.cost": 0.02}, usage.Items[0].Span.Attributes)
|
||||
|
||||
// The same span in any other list carries no attributes.
|
||||
for _, item := range NewSpanList(skeleton.page(skeleton.treeOrder, "", 0, 50), nil).Items {
|
||||
assert.Empty(t, item.Span.Attributes, item.Span.SpanID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSpanListPage(t *testing.T) {
|
||||
// root ─┬─ pay ─┬─ grpc
|
||||
// │ └─ caught
|
||||
// ├─ q1
|
||||
// ├─ q2
|
||||
// └─ auth
|
||||
// orphan (its parent was never received)
|
||||
testCases := []struct {
|
||||
name string
|
||||
query SpanListQuery
|
||||
search *SpanSearch
|
||||
expected []string
|
||||
expectedTotal uint64
|
||||
}{
|
||||
{
|
||||
name: "Trace_TreeOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, Limit: 50},
|
||||
expected: []string{"root", "pay", "grpc", "caught", "q1", "q2", "auth", "orphan"},
|
||||
expectedTotal: 8,
|
||||
},
|
||||
{
|
||||
name: "Trace_OffsetAndLimit_KeepsTotal",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, Offset: 6, Limit: 5},
|
||||
expected: []string{"auth", "orphan"},
|
||||
expectedTotal: 8,
|
||||
},
|
||||
{
|
||||
name: "Children_OneLevel_StartOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "root", Limit: 50},
|
||||
expected: []string{"pay", "q1", "q2", "auth"},
|
||||
expectedTotal: 4,
|
||||
},
|
||||
{
|
||||
name: "Descendants_TreeOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeDescendants, ScopeSpanID: "pay", Limit: 50},
|
||||
expected: []string{"grpc", "caught"},
|
||||
expectedTotal: 2,
|
||||
},
|
||||
{
|
||||
name: "Ancestors_ParentFirst",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "grpc", Limit: 50},
|
||||
expected: []string{"pay", "root"},
|
||||
expectedTotal: 2,
|
||||
},
|
||||
{
|
||||
name: "Ancestors_StopAtMissingParent",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "orphan", Limit: 50},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
// root carries the error up from pay, so it is not where the error starts.
|
||||
name: "Ancestors_View_OnlySpansOfTheView",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "grpc", View: SpanListViewErrorOrigins, Limit: 50},
|
||||
expected: []string{"pay"},
|
||||
expectedTotal: 1,
|
||||
},
|
||||
{
|
||||
// orphan and root rank in the view too, but are not below root.
|
||||
name: "Descendants_View_OnlySpansInScope",
|
||||
query: SpanListQuery{Scope: SpanScopeDescendants, ScopeSpanID: "root", View: SpanListViewTimeSpent, Limit: 50},
|
||||
expected: []string{"q2", "pay", "grpc", "caught", "auth"},
|
||||
expectedTotal: 5,
|
||||
},
|
||||
{
|
||||
// the store returns the matching spans in no order; the list keeps the order of the scope.
|
||||
name: "Search_KeepsScopeOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeDescendants, ScopeSpanID: "root", Limit: 50},
|
||||
search: &SpanSearch{SpanIDs: []string{"orphan", "auth", "grpc", "pay"}},
|
||||
expected: []string{"pay", "grpc", "auth"},
|
||||
expectedTotal: 3,
|
||||
},
|
||||
{
|
||||
name: "Search_View_BothApply",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, View: SpanListViewUnmarkedFailures, Limit: 50},
|
||||
search: &SpanSearch{SpanIDs: []string{"auth", "pay", "q1"}},
|
||||
expected: []string{"auth"},
|
||||
expectedTotal: 1,
|
||||
},
|
||||
{
|
||||
name: "Search_NothingMatches",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, Limit: 50},
|
||||
search: &SpanSearch{},
|
||||
expected: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
page, err := NewSpanListPage(checkoutSkeleton(nil), &testCase.query, testCase.search)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, page.SpanIDs())
|
||||
assert.Equal(t, testCase.expectedTotal, page.total)
|
||||
})
|
||||
}
|
||||
|
||||
_, err := NewSpanListPage(checkoutSkeleton(nil), &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "missing", Limit: 50}, nil)
|
||||
assert.True(t, errors.Ast(err, errors.TypeNotFound))
|
||||
}
|
||||
|
||||
func TestNewSpanListPage_TimeSpent_ShowsTheGroupByItsLongestSpanInScope(t *testing.T) {
|
||||
// root ─┬─ q1 (SELECT, 10 ms) ── row
|
||||
// └─ q2 (SELECT, 25 ms)
|
||||
// q2 is the longest SELECT, but only q1 is an ancestor of row.
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /orders", service: "web", startMs: 0, durationMs: 100},
|
||||
skeletonSpec{id: "q1", parent: "root", name: "SELECT", service: "db", startMs: 10, durationMs: 10},
|
||||
skeletonSpec{id: "row", parent: "q1", name: "decode", service: "db", startMs: 12, durationMs: 2},
|
||||
skeletonSpec{id: "q2", parent: "root", name: "SELECT", service: "db", startMs: 30, durationMs: 25},
|
||||
)
|
||||
|
||||
page, err := NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "row", View: SpanListViewTimeSpent, Limit: 50}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"root", "q1"}, page.SpanIDs())
|
||||
|
||||
page, err = NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeTrace, View: SpanListViewTimeSpent, Limit: 50}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"root", "q2", "row"}, page.SpanIDs())
|
||||
}
|
||||
|
||||
func TestSnippetAround_CaseFoldingThatChangesByteLength(t *testing.T) {
|
||||
// Lowering İ makes the text a byte longer, so a position in the lowered text does not map back.
|
||||
snippet, ok := snippetAround("İ WORLDPay declined", "worldpay")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "İ WORLDPay declined", snippet)
|
||||
}
|
||||
|
||||
func TestFindWords(t *testing.T) {
|
||||
long := strings.Repeat("é", 30) + "aWorldpay" + strings.Repeat("b", 60)
|
||||
row := &StorableSpan{
|
||||
Name: "charge_card",
|
||||
StatusMessage: long,
|
||||
AttributesString: map[string]string{"payment.provider": "worldpay", "http.route": "/pay"},
|
||||
AttributesNumber: map[string]float64{"order.id": 1234567},
|
||||
AttributesBool: map[string]bool{"payment.retried": true},
|
||||
ResourceJSON: jsonAttrs(map[string]any{"service.name": "payments"}),
|
||||
Events: []string{`{"name":"retry","timeUnixNano":1795447774760897000,"attributeMap":{"reason":"worldpay timeout"},"isError":true}`},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
words []SearchWord
|
||||
expected []SpanTextMatch
|
||||
}{
|
||||
{
|
||||
// a long text is cut 40 bytes on each side of the word; the cut lands inside an é and widens to its start.
|
||||
name: "IgnoresCase_CutsLongText",
|
||||
words: []SearchWord{{Text: "WORLDPAY"}},
|
||||
expected: []SpanTextMatch{
|
||||
{Field: "status_message", Snippet: "…" + strings.Repeat("é", 20) + "aWorldpay" + strings.Repeat("b", 40) + "…"},
|
||||
{Field: "attributes.payment.provider", Snippet: "worldpay"},
|
||||
{Field: "events[0]", Snippet: "worldpay timeout"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "AttributeName_ResourceValue",
|
||||
words: []SearchWord{{Text: "route"}, {Text: "payments"}},
|
||||
expected: []SpanTextMatch{{Field: "attributes.http.route", Snippet: "http.route"}, {Field: "resource.service.name", Snippet: "payments"}},
|
||||
},
|
||||
{
|
||||
name: "Number_PlainDigits_Bool",
|
||||
words: []SearchWord{{Text: "1234567"}, {Text: "true"}},
|
||||
expected: []SpanTextMatch{{Field: "attributes.order.id", Snippet: "1234567"}, {Field: "attributes.payment.retried", Snippet: "true"}},
|
||||
},
|
||||
{
|
||||
// the labels and the timestamp of a stored event are not part of what it says.
|
||||
name: "EventEnvelope_NotMatched",
|
||||
words: []SearchWord{{Text: "17954"}, {Text: "isError"}, {Text: "attributeMap"}},
|
||||
expected: []SpanTextMatch{},
|
||||
},
|
||||
{
|
||||
// the status message and an attribute also hold the word, but the call searches only events.
|
||||
name: "ScopedWord_OnlyItsParts",
|
||||
words: []SearchWord{{Text: "worldpay", Contexts: []telemetrytypes.FieldContext{telemetrytypes.FieldContextEvent}}},
|
||||
expected: []SpanTextMatch{{Field: "events[0]", Snippet: "worldpay timeout"}},
|
||||
},
|
||||
{
|
||||
name: "NoWord",
|
||||
words: nil,
|
||||
expected: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.expected, findWords(row, testCase.words))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSpanListPage_AIUsage_RanksByTokensWhenNoListedSpanHasACost(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
// agent ─┬─ plan (cost)
|
||||
// └─ tools ─┬─ search (10 tokens)
|
||||
// └─ fetch (100 tokens)
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "agent"},
|
||||
skeletonSpec{id: "plan", parent: "agent", usage: AISpanUsage{Cost: value(0.5)}},
|
||||
skeletonSpec{id: "tools", parent: "agent"},
|
||||
skeletonSpec{id: "search", parent: "tools", usage: AISpanUsage{InputTokens: value(10)}},
|
||||
skeletonSpec{id: "fetch", parent: "tools", usage: AISpanUsage{InputTokens: value(100)}},
|
||||
)
|
||||
|
||||
page, err := NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "tools", View: SpanListViewAIUsage, Limit: 50}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"fetch", "search"}, page.SpanIDs())
|
||||
}
|
||||
|
||||
// A name is read the way the query builder reads a select field of a trace list.
|
||||
func TestNewSpanList_SelectFields(t *testing.T) {
|
||||
skeleton := buildSkeleton(skeletonSpec{id: "root", name: "POST /checkout", service: "web"})
|
||||
rows := []StorableSpan{{
|
||||
SpanID: "root",
|
||||
AttributesString: map[string]string{"http.route": "/checkout", "env": "span-env", "name": "an attribute", "resource.type": "db"},
|
||||
ResourceJSON: jsonAttrs(map[string]any{"env": "resource-env"}),
|
||||
HTTPMethod: "POST",
|
||||
Scope: scopeColumn("", "", map[string]any{"lib.lang": "go", "team": "payments"}),
|
||||
}}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
field string
|
||||
attributes map[string]any
|
||||
resource map[string]string
|
||||
httpMethod string
|
||||
scope Scope
|
||||
warnings []string
|
||||
}{
|
||||
{name: "NoContext_BothSides", field: "env", attributes: map[string]any{"env": "span-env"}, resource: map[string]string{"service.name": "web", "env": "resource-env"}},
|
||||
{name: "ResourceContext_OneSide", field: "resource.env", attributes: map[string]any{}, resource: map[string]string{"service.name": "web", "env": "resource-env"}},
|
||||
{name: "AttributeContext_OneSide", field: "attribute.env", attributes: map[string]any{"env": "span-env"}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "SpanContext_ReadsTheAttribute", field: "span.http.route", attributes: map[string]any{"http.route": "/checkout"}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "ContextWord_PartOfTheAttributeName", field: "resource.type", attributes: map[string]any{"resource.type": "db"}, resource: map[string]string{"service.name": "web"}},
|
||||
// The span already carries its name, and the attribute called name needs attribute.name.
|
||||
{name: "SpanField_Returned_NotReadAsAnAttribute", field: "name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "SpanField_Selected", field: "http_method", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, httpMethod: "POST"},
|
||||
{name: "SpanField_EmptyOnTheSpan_Warns", field: "db_name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `db_name` was not found on any returned span"}},
|
||||
{name: "ScopeField_EmptyOnTheSpan_Warns", field: "scope.name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `scope.name` was not found on any returned span"}},
|
||||
{name: "ScopeAttribute_Selected", field: "scope.lib.lang", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, scope: Scope{"attributes": map[string]any{"lib.lang": "go"}}},
|
||||
{name: "ScopeAttribute_Missing_Warns", field: "scope.nope", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `scope.nope` was not found on any returned span"}},
|
||||
{name: "Unknown_Warns", field: "nope", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `nope` was not found on any returned span"}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
page := skeleton.page(skeleton.treeOrder, "", 0, 50)
|
||||
page.selectFields = []telemetrytypes.TelemetryFieldKey{newSelectField(testCase.field)}
|
||||
|
||||
list := NewSpanList(page, rows)
|
||||
require.Len(t, list.Items, 1)
|
||||
assert.Equal(t, testCase.attributes, list.Items[0].Span.Attributes)
|
||||
assert.Equal(t, testCase.resource, list.Items[0].Span.Resource)
|
||||
assert.Equal(t, testCase.httpMethod, list.Items[0].Span.HTTPMethod)
|
||||
assert.Equal(t, testCase.scope, list.Items[0].Span.Scope)
|
||||
assert.Equal(t, testCase.warnings, list.Warnings)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSpanList_SelectScopeFields_KeepsEachAttribute(t *testing.T) {
|
||||
skeleton := buildSkeleton(skeletonSpec{id: "root", name: "GET /cart", service: "cart"})
|
||||
rows := []StorableSpan{{SpanID: "root", Scope: scopeColumn("io.opentelemetry.http", "1.2.0", map[string]any{"lib.lang": "go", "team": "payments"})}}
|
||||
page := skeleton.page(skeleton.treeOrder, "", 0, 50)
|
||||
page.selectFields = []telemetrytypes.TelemetryFieldKey{newSelectField("scope.lib.lang"), newSelectField("scope.name"), newSelectField("scope.team")}
|
||||
|
||||
list := NewSpanList(page, rows)
|
||||
require.Len(t, list.Items, 1)
|
||||
assert.Equal(t, Scope{"name": "io.opentelemetry.http", "attributes": map[string]any{"lib.lang": "go", "team": "payments"}}, list.Items[0].Span.Scope)
|
||||
assert.Empty(t, list.Warnings)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package spantypes
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
@@ -113,7 +112,7 @@ type StorableSpan struct {
|
||||
AttributesNumber map[string]float64 `ch:"attributes_number"`
|
||||
AttributesBool map[string]bool `ch:"attributes_bool"`
|
||||
AttributesJSON telemetrystoretypes.JSONValue `ch:"attributes"`
|
||||
ResourcesString map[string]string `ch:"resources_string"`
|
||||
ResourceJSON telemetrystoretypes.JSONValue `ch:"resource"`
|
||||
Scope telemetrystoretypes.JSONValue `ch:"scope"`
|
||||
Events []string `ch:"events"`
|
||||
StatusMessage string `ch:"status_message"`
|
||||
@@ -296,6 +295,16 @@ func (item *StorableSpan) Attributes() map[string]any {
|
||||
return attributes
|
||||
}
|
||||
|
||||
// Resource flattens the JSON column into dotted keys, rendering non-string values as text.
|
||||
func (item *StorableSpan) Resource() map[string]string {
|
||||
flat := item.ResourceJSON.Flatten()
|
||||
resource := make(map[string]string, len(flat))
|
||||
for key, value := range flat {
|
||||
resource[key] = fmt.Sprint(value)
|
||||
}
|
||||
return resource
|
||||
}
|
||||
|
||||
func (item *StorableSpan) UnmarshalledEvents() []Event {
|
||||
events := make([]Event, 0, len(item.Events))
|
||||
for _, eventStr := range item.Events {
|
||||
@@ -317,9 +326,6 @@ func (item *StorableSpan) UnmarshalledRefs() []OtelSpanRef {
|
||||
}
|
||||
|
||||
func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
|
||||
resources := make(map[string]string)
|
||||
maps.Copy(resources, item.ResourcesString)
|
||||
|
||||
formatted := aiobservabilitytypes.FormatMessages(item.AttributesJSON.Nest())
|
||||
return &WaterfallSpan{
|
||||
Attributes: item.Attributes(),
|
||||
@@ -339,7 +345,7 @@ func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
|
||||
KindString: item.SpanKind,
|
||||
Name: item.Name,
|
||||
ParentSpanID: item.ParentSpanID,
|
||||
Resource: resources,
|
||||
Resource: item.Resource(),
|
||||
Scope: NewScope(item.Scope.Flatten()),
|
||||
ResponseStatusCode: item.ResponseStatusCode,
|
||||
SpanID: item.SpanID,
|
||||
|
||||
7
tests/fixtures/traces.py
vendored
7
tests/fixtures/traces.py
vendored
@@ -184,16 +184,19 @@ class TracesEvent(ABC):
|
||||
name: str
|
||||
time_unix_nano: np.uint64
|
||||
attribute_map: dict[str, str]
|
||||
is_error: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
timestamp: datetime.datetime,
|
||||
attribute_map: dict[str, str] = {},
|
||||
is_error: bool = False,
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.time_unix_nano = np.uint64(int(timestamp.timestamp() * 1e9))
|
||||
self.attribute_map = attribute_map
|
||||
self.is_error = is_error
|
||||
|
||||
def np_arr(self) -> np.array:
|
||||
return np.array([self.name, self.time_unix_nano, json.dumps(self.attribute_map)])
|
||||
@@ -598,13 +601,15 @@ class Traces(ABC):
|
||||
)
|
||||
# DB shape per event: {"name", "timeUnixNano", "attributeMap"}. Must match
|
||||
# what the consume-layer parser in pkg/types/spantypes expects.
|
||||
# The collector writes isError only when it is set.
|
||||
self._events_db = [
|
||||
json.dumps(
|
||||
{
|
||||
"name": event.name,
|
||||
"timeUnixNano": int(event.time_unix_nano),
|
||||
"attributeMap": dict(event.attribute_map),
|
||||
},
|
||||
}
|
||||
| ({"isError": True} if event.is_error else {}),
|
||||
separators=(",", ":"),
|
||||
)
|
||||
for event in events
|
||||
|
||||
116
tests/integration/tests/queriertraces/17_search.py
Normal file
116
tests/integration/tests/queriertraces/17_search.py
Normal file
@@ -0,0 +1,116 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import BuilderQuery, OrderBy, RequestType, TelemetryFieldKey, get_attribute_backend_now, get_rows, make_query_request
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesStatusCode
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"expression,expected_names",
|
||||
[
|
||||
pytest.param("search('worldpay')", {"call-worldpay", "charge-card", "post-payment", "notify", "edge-proxy"}, id="every_part"),
|
||||
pytest.param("search('WORLDPAY')", {"call-worldpay", "charge-card", "post-payment", "notify", "edge-proxy"}, id="case_insensitive"),
|
||||
pytest.param("search('worldpay', span)", {"call-worldpay", "charge-card"}, id="scope_span"),
|
||||
pytest.param("search('worldpay', attribute)", {"post-payment"}, id="scope_attribute"),
|
||||
pytest.param("search('worldpay', resource)", {"edge-proxy"}, id="scope_resource"),
|
||||
pytest.param("search('worldpay', event)", {"notify"}, id="scope_event"),
|
||||
pytest.param("search('worldpay', attribute, resource)", {"post-payment", "edge-proxy"}, id="scopes_union"),
|
||||
pytest.param("search('payment.provider')", {"post-payment"}, id="attribute_name"),
|
||||
pytest.param("search('{', attribute)", set(), id="json_punctuation"),
|
||||
pytest.param("NOT search('worldpay')", {"render-receipt"}, id="negated"),
|
||||
pytest.param("search('worldpay') AND has_error = true", {"charge-card"}, id="and_field_filter"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_traces_search(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
expression: str,
|
||||
expected_names: set[str],
|
||||
) -> None:
|
||||
"""Each span carries the text in a different part, so search() and each scope reach exactly the right ones."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
shop = {"service.name": "shop"}
|
||||
|
||||
def span(offset_s: int, name: str, **kwargs) -> Traces:
|
||||
kwargs.setdefault("resources", shop)
|
||||
return Traces(
|
||||
timestamp=now - timedelta(seconds=offset_s),
|
||||
duration=timedelta(seconds=1),
|
||||
trace_id=TraceIdGenerator.trace_id(),
|
||||
span_id=TraceIdGenerator.span_id(),
|
||||
name=name,
|
||||
kind=TracesKind.SPAN_KIND_SERVER,
|
||||
attribute_write_mode=write_mode,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
span(1, "call-worldpay"),
|
||||
span(2, "charge-card", status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="Worldpay declined the card"),
|
||||
span(3, "post-payment", attributes={"payment.provider": "worldpay"}),
|
||||
span(4, "notify", events=[TracesEvent("retry", now - timedelta(seconds=4), {"reason": "worldpay timeout"})]),
|
||||
span(5, "edge-proxy", resources={"service.name": "worldpay-edge"}),
|
||||
span(6, "render-receipt"),
|
||||
]
|
||||
)
|
||||
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),
|
||||
start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(now.timestamp() * 1000),
|
||||
request_type=RequestType.RAW,
|
||||
queries=[
|
||||
BuilderQuery(
|
||||
signal="traces",
|
||||
name="A",
|
||||
limit=100,
|
||||
filter_expression=expression,
|
||||
select_fields=[TelemetryFieldKey("span.name")],
|
||||
order=[OrderBy(TelemetryFieldKey("timestamp"), "desc")],
|
||||
).to_dict()
|
||||
],
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert {row["data"]["name"] for row in get_rows(response)} == expected_names
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"expression,expected_error",
|
||||
[
|
||||
pytest.param("search('worldpay', body)", "invalid search scope", id="scope_not_on_spans"),
|
||||
pytest.param("worldpay", "full text search is not supported", id="bare_word"),
|
||||
],
|
||||
)
|
||||
def test_traces_search_rejected(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
expression: str,
|
||||
expected_error: str,
|
||||
) -> None:
|
||||
"""A scope a span does not have, and text outside search(), are rejected with a 400."""
|
||||
now = get_attribute_backend_now(signoz, "json").replace(second=0, microsecond=0)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),
|
||||
start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(now.timestamp() * 1000),
|
||||
request_type=RequestType.RAW,
|
||||
queries=[BuilderQuery(signal="traces", name="A", limit=10, filter_expression=expression).to_dict()],
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert expected_error in response.text
|
||||
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
@@ -0,0 +1,194 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
|
||||
|
||||
SPAN_LISTS = ("errorOrigins", "unmarkedFailures", "timeSpent", "aiUsage", "links")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_trace_highlights(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
other_trace_id = TraceIdGenerator.trace_id()
|
||||
names = ("root", "place_order", "charge_card", "inventory_http", "inventory_grpc", "render", "notify", "consume", "model", "tool")
|
||||
ids = {name: TraceIdGenerator.span_id() for name in names}
|
||||
gateway, orders, agent = (f"td-highlights-{service}-{attribute_backend}" for service in ("gateway", "orders", "agent"))
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(key: str, parent: str, name: str, service: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
|
||||
return Traces(
|
||||
timestamp=start + timedelta(milliseconds=offset_ms),
|
||||
duration=timedelta(milliseconds=duration_ms),
|
||||
trace_id=trace_id,
|
||||
span_id=ids[key],
|
||||
parent_span_id=ids[parent] if parent else "",
|
||||
name=name,
|
||||
resources={"service.name": service, "k8s.pod.name": f"{service}-0"},
|
||||
attribute_write_mode=write_mode,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
span("root", "", "POST /checkout", gateway, 0, 1000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.response.status_code": 500}),
|
||||
# the error is carried up from charge_card through place_order to the root
|
||||
span("place_order", "root", "place_order", orders, 10, 600, status_code=TracesStatusCode.STATUS_CODE_ERROR),
|
||||
span("charge_card", "place_order", "charge_card", orders, 20, 300, kind=TracesKind.SPAN_KIND_CLIENT, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="card declined", attributes={"payment.provider": "worldpay"}),
|
||||
# four failures that do not carry the error flag
|
||||
span("inventory_http", "place_order", "GET /inventory", orders, 330, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 404}),
|
||||
span("inventory_grpc", "place_order", "inventory.Check", orders, 380, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"rpc.grpc.status_code": 5}),
|
||||
span("render", "root", "render_receipt", gateway, 700, 50, events=[TracesEvent("exception", now, {"exception.message": "template missing, fell back"}, is_error=True)]),
|
||||
span("notify", "root", "POST /notify", gateway, 752, 5, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 503}),
|
||||
# a link out to another trace
|
||||
span("consume", "root", "consume order.created", orders, 760, 20, kind=TracesKind.SPAN_KIND_CONSUMER, links=[TracesLink(trace_id=other_trace_id, span_id="aaaaaaaaaaaaaaaa", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)]),
|
||||
span("model", "root", "chat gpt-4o-mini", agent, 800, 100, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"gen_ai.request.model": "gpt-4o-mini", "gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": 0.01}),
|
||||
span("tool", "root", "execute_tool", agent, 910, 30, attributes={"gen_ai.tool.name": "get_weather"}),
|
||||
]
|
||||
)
|
||||
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights"), headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# own time is the duration minus what the children cover
|
||||
assert [(service["serviceName"], service["spanCount"], service["errorSpanCount"], service["ownTimeNano"]) for service in highlights["services"]] == [
|
||||
(orders, 5, 2, 620_000_000),
|
||||
(gateway, 3, 1, 250_000_000),
|
||||
(agent, 2, 0, 130_000_000),
|
||||
]
|
||||
|
||||
# one entry for the error, at the span that threw it
|
||||
errors = highlights["errorOrigins"]
|
||||
assert errors["total"] == 1
|
||||
error = errors["items"][0]
|
||||
assert error["span"] == {
|
||||
"span_id": ids["charge_card"],
|
||||
"trace_id": trace_id,
|
||||
"parent_span_id": ids["place_order"],
|
||||
"name": "charge_card",
|
||||
"kind_string": "Client",
|
||||
"time_unix": int(start.timestamp()) * 1_000 + 20,
|
||||
"duration_nano": 300_000_000,
|
||||
"has_error": True,
|
||||
"status_code_string": "STATUS_CODE_ERROR",
|
||||
"status_message": "card declined",
|
||||
"response_status_code": "",
|
||||
"resource": {"service.name": orders},
|
||||
"attributes": {},
|
||||
"events": [],
|
||||
"references": [{"traceId": trace_id, "spanId": ids["place_order"], "refType": "CHILD_OF"}],
|
||||
}
|
||||
assert error["treeStats"] == {"level": 2, "childCount": 0, "subtreeSpanCount": 0, "ownTimeNano": 300_000_000, "errorAncestorCount": 2}
|
||||
assert "unmarkedFailureKind" not in error
|
||||
assert "matches" not in error
|
||||
|
||||
unmarked = highlights["unmarkedFailures"]
|
||||
assert unmarked["total"] == 4
|
||||
assert [(item["span"]["span_id"], item["unmarkedFailureKind"]) for item in unmarked["items"]] == [(ids["inventory_http"], "http_4xx"), (ids["inventory_grpc"], "grpc_status"), (ids["render"], "exception_event"), (ids["notify"], "http_5xx")]
|
||||
assert unmarked["items"][0]["span"]["response_status_code"] == "404"
|
||||
|
||||
links = highlights["links"]
|
||||
assert links["total"] == 1
|
||||
assert links["items"][0]["span"]["span_id"] == ids["consume"]
|
||||
assert {"traceId": other_trace_id, "spanId": "aaaaaaaaaaaaaaaa", "refType": "FOLLOWS_FROM"} in links["items"][0]["span"]["references"]
|
||||
|
||||
# no other list carries attributes
|
||||
ai_usage = highlights["aiUsage"]
|
||||
# the tool span carries no token or cost value, so it is not listed
|
||||
assert ai_usage["total"] == 1
|
||||
assert ai_usage["items"][0]["span"]["span_id"] == ids["model"]
|
||||
assert ai_usage["items"][0]["span"]["attributes"] == {"gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": pytest.approx(0.01)}
|
||||
|
||||
# every span is its own entry here, most own time first
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 10
|
||||
assert [item["span"]["span_id"] for item in time_spent["items"][:3]] == [ids["charge_card"], ids["place_order"], ids["root"]]
|
||||
assert time_spent["items"][0]["treeStats"]["ownTimeNano"] == 300_000_000
|
||||
assert "sameNameSiblings" not in time_spent["items"][0]["treeStats"]
|
||||
assert time_spent["items"][1]["treeStats"] == {"level": 1, "childCount": 3, "subtreeSpanCount": 3, "ownTimeNano": 220_000_000, "errorAncestorCount": 1}
|
||||
|
||||
# the totals of the trace are not here: they come from the summary route
|
||||
assert set(highlights) == {"services", *SPAN_LISTS}
|
||||
for name in SPAN_LISTS:
|
||||
for item in highlights[name]["items"]:
|
||||
assert item["span"]["events"] == [], name
|
||||
assert list(item["span"]["resource"]) == ["service.name"], name
|
||||
|
||||
|
||||
def test_trace_highlights_limits(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
root_id = TraceIdGenerator.span_id()
|
||||
resources = {"service.name": "td-highlights-limits"}
|
||||
start = now - timedelta(seconds=30)
|
||||
spans = [Traces(timestamp=start, duration=timedelta(seconds=20), trace_id=trace_id, span_id=root_id, name="POST /import", kind=TracesKind.SPAN_KIND_SERVER, resources=resources)]
|
||||
for i in range(150):
|
||||
failed = {"status_code": TracesStatusCode.STATUS_CODE_ERROR, "status_message": f"failure {i:03d}"} if i < 12 else {}
|
||||
spans.append(Traces(timestamp=start + timedelta(seconds=1, milliseconds=i * 10), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), parent_span_id=root_id, name="write_item", resources=resources, **failed))
|
||||
insert_traces(spans)
|
||||
|
||||
url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(url, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# the default: 10 spans of a list, with the total behind it
|
||||
assert highlights["errorOrigins"]["total"] == 12
|
||||
assert [item["span"]["status_message"] for item in highlights["errorOrigins"]["items"]] == [f"failure {i:03d}" for i in range(10)]
|
||||
assert highlights["aiUsage"] == {"total": 0, "items": []}
|
||||
|
||||
# the 150 same-name children are one entry of the timeSpent list, shown by one of them
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 2
|
||||
group = next(item for item in time_spent["items"] if item["span"]["name"] == "write_item")
|
||||
assert group["treeStats"]["sameNameSiblings"] == {"spanCount": 150, "ownTimeNano": 150 * 5_000_000, "errorSpanCount": 12}
|
||||
assert group["span"]["parent_span_id"] == root_id
|
||||
root = next(item for item in time_spent["items"] if item["span"]["span_id"] == root_id)
|
||||
assert root["treeStats"]["childCount"] == 150
|
||||
assert root["treeStats"]["subtreeSpanCount"] == 150
|
||||
|
||||
sized = requests.get(url, params={"limit": 3}, headers=headers, timeout=10).json()["data"]
|
||||
assert len(sized["errorOrigins"]["items"]) == 3
|
||||
assert sized["errorOrigins"]["total"] == 12
|
||||
|
||||
# the highest value accepted returns everything
|
||||
largest = requests.get(url, params={"limit": 1000}, headers=headers, timeout=10)
|
||||
assert largest.status_code == HTTPStatus.OK, largest.text
|
||||
assert len(largest.json()["data"]["errorOrigins"]["items"]) == 12
|
||||
|
||||
# views names the lists to return; the others are left out
|
||||
picked = requests.get(url, params={"views": ["error_origins", "time_spent"]}, headers=headers, timeout=10)
|
||||
assert picked.status_code == HTTPStatus.OK, picked.text
|
||||
assert set(picked.json()["data"]) == {"services", "errorOrigins", "timeSpent"}
|
||||
assert picked.json()["data"]["errorOrigins"]["total"] == 12
|
||||
assert picked.json()["data"]["timeSpent"]["total"] == 2
|
||||
|
||||
for params in ({"limit": 1001}, {"limit": -1}, {"views": "fastest"}, {"views": "all"}):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, f"{params}: {response.text}"
|
||||
|
||||
unknown = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/highlights"), headers=headers, timeout=10)
|
||||
assert unknown.status_code == HTTPStatus.NOT_FOUND, unknown.text
|
||||
111
tests/integration/tests/tracedetail/06_span.py
Normal file
111
tests/integration/tests/tracedetail/06_span.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_get_trace_span(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
other_trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": f"td-span-{attribute_backend}", "k8s.pod.name": "orders-0"}
|
||||
root_id, target_id, plain_id, orphan_id, gone_id = (TraceIdGenerator.span_id() for _ in range(5))
|
||||
long_statement = "SELECT * FROM orders WHERE id IN (" + ", ".join(str(i) for i in range(2000)) + ")"
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(span_id: str, parent_id: str, name: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
|
||||
return Traces(timestamp=start + timedelta(milliseconds=offset_ms), duration=timedelta(milliseconds=duration_ms), trace_id=trace_id, span_id=span_id, parent_span_id=parent_id, name=name, resources=resources, attribute_write_mode=write_mode, **kwargs)
|
||||
|
||||
# POST /orders root, error, attribute http.route
|
||||
# ├─ query_orders error "deadlock detected", 4 attributes (one is 12 KB), a scope, 1 event, a link to another trace
|
||||
# └─ fetch_page no attributes, no events
|
||||
#
|
||||
# flush_metrics its parent was never received; status 404
|
||||
insert_traces(
|
||||
[
|
||||
span(root_id, "", "POST /orders", 0, 2000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.route": "/orders"}),
|
||||
span(
|
||||
target_id,
|
||||
root_id,
|
||||
"query_orders",
|
||||
30,
|
||||
1000,
|
||||
kind=TracesKind.SPAN_KIND_CLIENT,
|
||||
status_code=TracesStatusCode.STATUS_CODE_ERROR,
|
||||
status_message="deadlock detected",
|
||||
attributes={"db.system": "postgresql", "db.name": "orders", "db.statement": long_statement, "db.rows": 42},
|
||||
scope={"name": "orders-db", "version": "1.2.0"},
|
||||
events=[TracesEvent("retry", start, {"attempt": "2"})],
|
||||
links=[TracesLink(trace_id=other_trace_id, span_id="bbbbbbbbbbbbbbbb", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)],
|
||||
),
|
||||
span(plain_id, root_id, "fetch_page", 1100, 8),
|
||||
span(orphan_id, gone_id, "flush_metrics", 1500, 100, attributes={"http.response.status_code": 404}),
|
||||
]
|
||||
)
|
||||
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(f"{spans_url}/{target_id}", headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
# the response is the span itself: everything it stores, with no value cut
|
||||
assert response.json()["data"] == {
|
||||
"span_id": target_id,
|
||||
"trace_id": trace_id,
|
||||
"parent_span_id": root_id,
|
||||
"name": "query_orders",
|
||||
"kind_string": "Client",
|
||||
"time_unix": int(start.timestamp()) * 1_000 + 30,
|
||||
"duration_nano": 1_000_000_000,
|
||||
"has_error": True,
|
||||
"status_code_string": "STATUS_CODE_ERROR",
|
||||
"status_message": "deadlock detected",
|
||||
"response_status_code": "",
|
||||
"db_name": "orders",
|
||||
"scope": {"name": "orders-db", "version": "1.2.0"},
|
||||
"resource": resources,
|
||||
"attributes": {"db.system": "postgresql", "db.name": "orders", "db.statement": long_statement, "db.rows": 42},
|
||||
"events": [{"name": "retry", "timeUnixNano": int(start.timestamp()) * 1_000_000_000, "attributeMap": {"attempt": "2"}}],
|
||||
"references": [{"traceId": trace_id, "spanId": root_id, "refType": "CHILD_OF"}, {"traceId": other_trace_id, "spanId": "bbbbbbbbbbbbbbbb", "refType": "FOLLOWS_FROM"}],
|
||||
}
|
||||
|
||||
root = requests.get(f"{spans_url}/{root_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert root["parent_span_id"] == ""
|
||||
assert root["kind_string"] == "Server"
|
||||
assert root["attributes"] == {"http.route": "/orders"}
|
||||
|
||||
# a span that stores no attributes and no events returns them empty, not null
|
||||
plain = requests.get(f"{spans_url}/{plain_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert plain["attributes"] == {}
|
||||
assert plain["events"] == []
|
||||
assert plain["resource"] == resources
|
||||
assert "db_name" not in plain
|
||||
assert "scope" not in plain
|
||||
|
||||
# a span whose parent was never received keeps the parent's id
|
||||
orphan = requests.get(f"{spans_url}/{orphan_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert orphan["parent_span_id"] == gone_id
|
||||
assert orphan["response_status_code"] == "404"
|
||||
assert orphan["has_error"] is False
|
||||
|
||||
unknown_span = requests.get(f"{spans_url}/{TraceIdGenerator.span_id()}", headers=headers, timeout=10)
|
||||
assert unknown_span.status_code == HTTPStatus.NOT_FOUND, unknown_span.text
|
||||
|
||||
unknown_trace = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/spans/{target_id}"), headers=headers, timeout=10)
|
||||
assert unknown_trace.status_code == HTTPStatus.NOT_FOUND, unknown_trace.text
|
||||
346
tests/integration/tests/tracedetail/07_spans.py
Normal file
346
tests/integration/tests/tracedetail/07_spans.py
Normal file
@@ -0,0 +1,346 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesStatusCode
|
||||
|
||||
|
||||
def test_list_trace_spans_scopes_views_and_paging(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": "td-spans-views"}
|
||||
start = now - timedelta(seconds=10)
|
||||
root_id, orphan_id, orphan_child_id = (TraceIdGenerator.span_id() for _ in range(3))
|
||||
|
||||
# POST /batch 1000 ms
|
||||
# ├─ batch-0 80 ms
|
||||
# │ ├─ write_item ×3
|
||||
# │ └─ write_item error "write failed in batch-0"
|
||||
# ├─ batch-1 the same four below it
|
||||
# └─ batch-2 the same four below it
|
||||
#
|
||||
# flush its parent was never received
|
||||
# └─ flush_item
|
||||
spans = [Traces(timestamp=start, duration=timedelta(seconds=1), trace_id=trace_id, span_id=root_id, name="POST /batch", kind=TracesKind.SPAN_KIND_SERVER, resources=resources)]
|
||||
tree_order = [root_id]
|
||||
branches: list[list[str]] = []
|
||||
failed_leaves: list[str] = []
|
||||
for branch in range(3):
|
||||
branch_id = TraceIdGenerator.span_id()
|
||||
spans.append(Traces(timestamp=start + timedelta(milliseconds=100 * branch + 10), duration=timedelta(milliseconds=80), trace_id=trace_id, span_id=branch_id, parent_span_id=root_id, name=f"batch-{branch}", resources=resources))
|
||||
below = [branch_id]
|
||||
for leaf in range(4):
|
||||
leaf_id = TraceIdGenerator.span_id()
|
||||
failed = {"status_code": TracesStatusCode.STATUS_CODE_ERROR, "status_message": f"write failed in batch-{branch}"} if leaf == 3 else {}
|
||||
spans.append(Traces(timestamp=start + timedelta(milliseconds=100 * branch + 20 + 10 * leaf), duration=timedelta(milliseconds=5 + leaf), trace_id=trace_id, span_id=leaf_id, parent_span_id=branch_id, name="write_item", resources=resources, **failed))
|
||||
below.append(leaf_id)
|
||||
if leaf == 3:
|
||||
failed_leaves.append(leaf_id)
|
||||
branches.append(below)
|
||||
tree_order += below
|
||||
spans.append(Traces(timestamp=start + timedelta(milliseconds=500), duration=timedelta(milliseconds=20), trace_id=trace_id, span_id=orphan_id, parent_span_id=TraceIdGenerator.span_id(), name="flush", resources=resources))
|
||||
spans.append(Traces(timestamp=start + timedelta(milliseconds=505), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=orphan_child_id, parent_span_id=orphan_id, name="flush_item", resources=resources))
|
||||
tree_order += [orphan_id, orphan_child_id]
|
||||
insert_traces(spans)
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
|
||||
# without a view: every span in tree order, 50 a page
|
||||
response = requests.get(spans_url, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
everything = response.json()["data"]
|
||||
assert everything["total"] == 18
|
||||
assert [item["span"]["span_id"] for item in everything["items"]] == tree_order
|
||||
assert [item["treeStats"]["level"] for item in everything["items"]] == [0] + [1, 2, 2, 2, 2] * 3 + [0, 1]
|
||||
assert all("matches" not in item for item in everything["items"])
|
||||
assert "warnings" not in everything
|
||||
|
||||
# offset and limit cut the same order, and the total stays
|
||||
seen = []
|
||||
for offset in range(0, 20, 7):
|
||||
page = requests.get(spans_url, params={"offset": offset, "limit": 7}, headers=headers, timeout=10).json()["data"]
|
||||
assert page["total"] == 18
|
||||
seen += [item["span"]["span_id"] for item in page["items"]]
|
||||
assert seen == tree_order
|
||||
|
||||
# a view keeps the spans of its kind, in its own order, and pages the same way
|
||||
errors = requests.get(spans_url, params={"view": "error_origins", "offset": 1, "limit": 5}, headers=headers, timeout=10).json()["data"]
|
||||
assert errors["total"] == 3
|
||||
assert [item["span"]["span_id"] for item in errors["items"]] == failed_leaves[1:]
|
||||
assert [item["span"]["status_message"] for item in errors["items"]] == ["write failed in batch-1", "write failed in batch-2"]
|
||||
assert [item["span"]["parent_span_id"] for item in errors["items"]] == [branches[1][0], branches[2][0]]
|
||||
|
||||
# one entry for each group of same-name siblings, shown by its longest span
|
||||
time_spent = requests.get(spans_url, params={"view": "time_spent"}, headers=headers, timeout=10).json()["data"]
|
||||
assert time_spent["total"] == 9
|
||||
assert time_spent["items"][0]["span"]["span_id"] == root_id
|
||||
assert {item["span"]["span_id"] for item in time_spent["items"] if item["span"]["name"] == "write_item"} == set(failed_leaves)
|
||||
|
||||
for view in ("unmarked_failures", "ai_usage", "links"):
|
||||
assert requests.get(spans_url, params={"view": view}, headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}, view
|
||||
|
||||
# children: one level below, in start order
|
||||
children_url = f"{spans_url}/{branches[1][0]}/children"
|
||||
children = requests.get(children_url, headers=headers, timeout=10).json()["data"]
|
||||
assert children["total"] == 4
|
||||
assert [item["span"]["span_id"] for item in children["items"]] == branches[1][1:]
|
||||
assert children["items"][0]["treeStats"]["sameNameSiblings"] == {"spanCount": 4, "ownTimeNano": 26_000_000, "errorSpanCount": 1}
|
||||
assert [item["span"]["span_id"] for item in requests.get(f"{spans_url}/{root_id}/children", headers=headers, timeout=10).json()["data"]["items"]] == [branch[0] for branch in branches]
|
||||
assert requests.get(f"{spans_url}/{branches[1][1]}/children", headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}
|
||||
|
||||
# descendants: everything below, in tree order; a view keeps the ones of its kind that are below
|
||||
descendants = requests.get(f"{spans_url}/{root_id}/descendants", headers=headers, timeout=10).json()["data"]
|
||||
assert descendants["total"] == 15
|
||||
assert [item["span"]["span_id"] for item in descendants["items"]] == tree_order[1:16]
|
||||
assert [item["span"]["span_id"] for item in requests.get(f"{spans_url}/{branches[2][0]}/descendants", headers=headers, timeout=10).json()["data"]["items"]] == branches[2][1:]
|
||||
page = requests.get(f"{spans_url}/{root_id}/descendants", params={"view": "error_origins", "limit": 2}, headers=headers, timeout=10).json()["data"]
|
||||
assert page["total"] == 3
|
||||
assert [item["span"]["span_id"] for item in page["items"]] == failed_leaves[:2]
|
||||
|
||||
# ancestors: the one chain of parents, the parent first; nothing from the other branches
|
||||
ancestors_url = f"{spans_url}/{failed_leaves[1]}/ancestors"
|
||||
ancestors = requests.get(ancestors_url, headers=headers, timeout=10).json()["data"]
|
||||
assert ancestors["total"] == 2
|
||||
assert [item["span"]["span_id"] for item in ancestors["items"]] == [branches[1][0], root_id]
|
||||
assert requests.get(f"{spans_url}/{root_id}/ancestors", headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}
|
||||
|
||||
# the chain stops at a parent that was never received
|
||||
assert [item["span"]["span_id"] for item in requests.get(f"{spans_url}/{orphan_child_id}/ancestors", headers=headers, timeout=10).json()["data"]["items"]] == [orphan_id]
|
||||
assert requests.get(f"{spans_url}/{orphan_id}/ancestors", headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_list_trace_spans_select_fields(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column finds nothing."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": f"td-spans-fields-{attribute_backend}", "k8s.pod.name": "checkout-0"}
|
||||
root_id, charge_id, payment_id, notify_id = (TraceIdGenerator.span_id() for _ in range(4))
|
||||
long_statement = "SELECT * FROM payments WHERE id IN (" + ", ".join(str(i) for i in range(2000)) + ")"
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(span_id: str, parent_id: str, name: str, offset_ms: int, **kwargs) -> Traces:
|
||||
return Traces(timestamp=start + timedelta(milliseconds=offset_ms), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=span_id, parent_span_id=parent_id, name=name, resources=resources, attribute_write_mode=write_mode, **kwargs)
|
||||
|
||||
# POST /checkout attribute http.route
|
||||
# ├─ charge_card
|
||||
# │ └─ POST /v1/payments attributes payment.provider, http.request.method, http.response.status_code, db.statement (12 KB); a scope
|
||||
# └─ notify one event
|
||||
insert_traces(
|
||||
[
|
||||
span(root_id, "", "POST /checkout", 0, kind=TracesKind.SPAN_KIND_SERVER, attributes={"http.route": "/checkout"}),
|
||||
span(charge_id, root_id, "charge_card", 20),
|
||||
span(
|
||||
payment_id,
|
||||
charge_id,
|
||||
"POST /v1/payments",
|
||||
30,
|
||||
attributes={"payment.provider": "worldpay", "http.request.method": "POST", "http.response.status_code": 402, "db.statement": long_statement},
|
||||
scope={"name": "payments-lib", "version": "2.0.1"},
|
||||
),
|
||||
span(notify_id, root_id, "notify", 40, events=[TracesEvent("retry", start, {"reason": "timeout"})]),
|
||||
]
|
||||
)
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
|
||||
# without selectFields a span carries service.name and nothing else
|
||||
plain = requests.get(spans_url, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in plain["items"]] == [root_id, charge_id, payment_id, notify_id]
|
||||
assert all(item["span"]["attributes"] == {} and item["span"]["events"] == [] for item in plain["items"])
|
||||
assert all(item["span"]["resource"] == {"service.name": resources["service.name"]} for item in plain["items"])
|
||||
assert all("http_method" not in item["span"] and "scope" not in item["span"] for item in plain["items"])
|
||||
assert "warnings" not in plain
|
||||
|
||||
# the named fields are filled where a span has them; a long value comes back whole
|
||||
selected = requests.get(spans_url, params={"selectFields": ["payment.provider", "db.statement", "http.route", "resource.k8s.pod.name"]}, headers=headers, timeout=10)
|
||||
assert selected.status_code == HTTPStatus.OK, selected.text
|
||||
selected = selected.json()["data"]
|
||||
assert [item["span"]["attributes"] for item in selected["items"]] == [{"http.route": "/checkout"}, {}, {"payment.provider": "worldpay", "db.statement": long_statement}, {}]
|
||||
assert all(item["span"]["resource"] == resources for item in selected["items"])
|
||||
assert all(item["span"]["events"] == [] for item in selected["items"])
|
||||
assert selected["items"][2]["unmarkedFailureKind"] == "http_4xx"
|
||||
assert "warnings" not in selected
|
||||
|
||||
# a context picks one side: an attribute name is not looked up in the resource
|
||||
children_url = f"{spans_url}/{charge_id}/children"
|
||||
scoped = requests.get(children_url, params={"selectFields": ["attribute.payment.provider", "attribute.k8s.pod.name"]}, headers=headers, timeout=10).json()["data"]
|
||||
assert scoped["items"][0]["span"]["attributes"] == {"payment.provider": "worldpay"}
|
||||
assert scoped["items"][0]["span"]["resource"] == {"service.name": resources["service.name"]}
|
||||
assert scoped["warnings"] == ["field `attribute.k8s.pod.name` was not found on any returned span"]
|
||||
|
||||
# a field of the span itself is filled where a span has it; one a list does not return is named in warnings
|
||||
own = requests.get(spans_url, params={"selectFields": ["http_method", "scope.name", "flags"]}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"].get("http_method"), item["span"].get("scope")) for item in own["items"]] == [(None, None), (None, None), ("POST", {"name": "payments-lib"}), (None, None)]
|
||||
assert own["warnings"] == ["field `flags` was not found on any returned span"]
|
||||
|
||||
# a field no span of the page has is named in warnings
|
||||
missing = requests.get(children_url, params={"selectFields": ["payment.provider", "not.there"]}, headers=headers, timeout=10).json()["data"]
|
||||
assert missing["items"][0]["span"]["attributes"] == {"payment.provider": "worldpay"}
|
||||
assert missing["warnings"] == ["field `not.there` was not found on any returned span"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_list_trace_spans_query(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column finds nothing."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": f"td-spans-query-{attribute_backend}", "k8s.pod.name": "checkout-0"}
|
||||
names = ("root", "by_name", "by_status", "by_attribute", "by_event", "unrelated")
|
||||
ids = {name: TraceIdGenerator.span_id() for name in names}
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(key: str, parent: str, name: str, offset_ms: int, **kwargs) -> Traces:
|
||||
return Traces(timestamp=start + timedelta(milliseconds=offset_ms), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=ids[key], parent_span_id=ids[parent] if parent else "", name=name, resources=resources, attribute_write_mode=write_mode, **kwargs)
|
||||
|
||||
# POST /checkout
|
||||
# ├─ call worldpay the word is in the name
|
||||
# ├─ charge_card error, the word is in the status message
|
||||
# │ └─ POST /v1/payments the word is in an attribute
|
||||
# ├─ notify the word is in an event
|
||||
# └─ render_receipt error, the word is nowhere
|
||||
insert_traces(
|
||||
[
|
||||
span("root", "", "POST /checkout", 0, kind=TracesKind.SPAN_KIND_SERVER, attributes={"http.route": "/checkout"}),
|
||||
span("by_name", "root", "call worldpay", 10),
|
||||
span("by_status", "root", "charge_card", 20, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="Worldpay declined the card"),
|
||||
span("by_attribute", "by_status", "POST /v1/payments", 30, attributes={"payment.provider": "worldpay", "http.response.status_code": 402, "order.id": 1234567, "payment.retried": True, "url.full": "https://pay.example.com/v1/charges", "gateway.reply": 'said "come back later"'}),
|
||||
span("by_event", "root", "notify", 40, events=[TracesEvent("retry", start, {"reason": "worldpay timeout"})]),
|
||||
span("unrelated", "root", "render_receipt", 50, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="template missing"),
|
||||
]
|
||||
)
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
|
||||
# search() finds the text wherever it occurs, ignoring case; the list keeps its own order
|
||||
response = requests.get(spans_url, params={"query": "search('worldpay')"}, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
found = response.json()["data"]
|
||||
assert found["total"] == 4
|
||||
assert [item["span"]["span_id"] for item in found["items"]] == [ids[name] for name in ("by_name", "by_status", "by_attribute", "by_event")]
|
||||
assert {item["span"]["span_id"]: [match["field"] for match in item["matches"]] for item in found["items"]} == {
|
||||
ids["by_name"]: ["name"],
|
||||
ids["by_status"]: ["status_message"],
|
||||
ids["by_attribute"]: ["attributes.payment.provider"],
|
||||
ids["by_event"]: ["events[0]"],
|
||||
}
|
||||
assert found["items"][1]["matches"][0]["snippet"] == "Worldpay declined the card"
|
||||
# the attributes read to locate the word are not returned
|
||||
assert all(item["span"]["attributes"] == {} for item in found["items"])
|
||||
assert "warnings" not in found
|
||||
|
||||
# offset and limit page the matches
|
||||
page = requests.get(spans_url, params={"query": "search('worldpay')", "limit": 3, "offset": 3}, headers=headers, timeout=10).json()["data"]
|
||||
assert page["total"] == 4
|
||||
assert [item["span"]["span_id"] for item in page["items"]] == [ids["by_event"]]
|
||||
|
||||
# a filter expression without search() has no text to show
|
||||
failed = requests.get(spans_url, params={"query": "has_error = true"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in failed["items"]] == [ids["by_status"], ids["unrelated"]]
|
||||
assert all("matches" not in item for item in failed["items"])
|
||||
|
||||
by_attribute = requests.get(spans_url, params={"query": "payment.provider = 'worldpay'"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in by_attribute["items"]] == [ids["by_attribute"]]
|
||||
|
||||
both = requests.get(spans_url, params={"query": "search('worldpay') AND has_error = true"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in both["items"]] == [ids["by_status"]]
|
||||
|
||||
# a query narrows the spans a route covers, and a view narrows them further
|
||||
children = requests.get(f"{spans_url}/{ids['root']}/children", params={"query": "search('worldpay')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in children["items"]] == [ids[name] for name in ("by_name", "by_status", "by_event")]
|
||||
origins = requests.get(spans_url, params={"query": "search('worldpay')", "view": "error_origins"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in origins["items"]] == [ids["by_status"]]
|
||||
|
||||
# search() also finds an attribute's name and a resource attribute
|
||||
by_key = requests.get(spans_url, params={"query": "search('payment.provider')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"]["span_id"], item["matches"][0]["field"]) for item in by_key["items"]] == [(ids["by_attribute"], "attributes.payment.provider")]
|
||||
by_resource = requests.get(spans_url, params={"query": "search('td-spans-query')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert by_resource["total"] == 6
|
||||
assert {item["matches"][0]["field"] for item in by_resource["items"]} == {"resource.service.name"}
|
||||
|
||||
# a number and a bool are matched as they are written
|
||||
by_number = requests.get(spans_url, params={"query": "search('1234567')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"]["span_id"], item["matches"]) for item in by_number["items"]] == [(ids["by_attribute"], [{"field": "attributes.order.id", "snippet": "1234567"}])]
|
||||
by_bool = requests.get(spans_url, params={"query": "search('true')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"]["span_id"], item["matches"][0]["field"]) for item in by_bool["items"]] == [(ids["by_attribute"], "attributes.payment.retried")]
|
||||
|
||||
# a slash inside a value is matched as written
|
||||
by_url = requests.get(spans_url, params={"query": "search('example.com/v1')"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"]["span_id"], item["matches"][0]["field"]) for item in by_url["items"]] == [(ids["by_attribute"], "attributes.url.full")]
|
||||
|
||||
# a quote inside a value is matched as written
|
||||
by_quote = requests.get(spans_url, params={"query": """search('said "come back later"')"""}, headers=headers, timeout=10).json()["data"]
|
||||
assert [(item["span"]["span_id"], item["matches"][0]["field"]) for item in by_quote["items"]] == [(ids["by_attribute"], "attributes.gateway.reply")]
|
||||
|
||||
# of an event only the name and the attributes are matched, not the labels it is stored with
|
||||
assert requests.get(spans_url, params={"query": "search('retry')"}, headers=headers, timeout=10).json()["data"]["total"] == 1
|
||||
assert requests.get(spans_url, params={"query": "search('attributeMap')"}, headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}
|
||||
|
||||
assert requests.get(spans_url, params={"query": "search('stripe')"}, headers=headers, timeout=10).json()["data"] == {"total": 0, "items": []}
|
||||
|
||||
# a second argument limits search() to one part of the span
|
||||
scoped = requests.get(spans_url, params={"query": "search('worldpay', attribute)"}, headers=headers, timeout=10).json()["data"]
|
||||
assert [item["span"]["span_id"] for item in scoped["items"]] == [ids["by_attribute"]]
|
||||
|
||||
# text outside search() is not a full-text search on traces
|
||||
bare = requests.get(spans_url, params={"query": "worldpay"}, headers=headers, timeout=10)
|
||||
assert bare.status_code == HTTPStatus.BAD_REQUEST, bare.text
|
||||
|
||||
unknown_key = requests.get(spans_url, params={"query": "no.such.key = 'x'"}, headers=headers, timeout=10).json()["data"]
|
||||
assert unknown_key["total"] == 0
|
||||
assert "no.such.key" in unknown_key["warnings"][0]
|
||||
|
||||
broken = requests.get(spans_url, params={"query": "has_error ="}, headers=headers, timeout=10)
|
||||
assert broken.status_code == HTTPStatus.BAD_REQUEST, broken.text
|
||||
|
||||
|
||||
def test_list_trace_spans_rejects_invalid_requests(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
span_id = TraceIdGenerator.span_id()
|
||||
insert_traces([Traces(timestamp=now - timedelta(seconds=10), duration=timedelta(seconds=1), trace_id=trace_id, span_id=span_id, name="GET /health", resources={"service.name": "td-spans-invalid"})])
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
|
||||
for url in (spans_url, f"{spans_url}/{span_id}/descendants"):
|
||||
for params in ({"view": "fastest"}, {"limit": 1001}, {"limit": -1}, {"offset": -1}, {"limit": "all"}):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, f"{url} {params}: {response.text}"
|
||||
assert requests.get(url, params={"limit": 1000}, headers=headers, timeout=10).status_code == HTTPStatus.OK
|
||||
|
||||
for scope in ("children", "descendants", "ancestors"):
|
||||
unknown_span = requests.get(f"{spans_url}/{TraceIdGenerator.span_id()}/{scope}", headers=headers, timeout=10)
|
||||
assert unknown_span.status_code == HTTPStatus.NOT_FOUND, f"{scope}: {unknown_span.text}"
|
||||
|
||||
unknown_trace = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/spans"), headers=headers, timeout=10)
|
||||
assert unknown_trace.status_code == HTTPStatus.NOT_FOUND, unknown_trace.text
|
||||
Reference in New Issue
Block a user