Compare commits

...

80 Commits

Author SHA1 Message Date
nityanandagohain
4547ba6bf7 Merge remote-tracking branch 'origin/main' into issue_nerve_651_5
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/types/spantypes/trace_span_list.go
#	pkg/types/spantypes/trace_span_list_test.go
#	tests/integration/tests/tracedetail/07_spans.py
2026-12-03 13:57:23 +05:30
nityanandagohain
685a54959b Merge remote-tracking branch 'origin/issue_nerve_651_4' into issue_nerve_651_5 2026-12-03 13:55:36 +05:30
nityanandagohain
2b4c9c2edc Merge remote-tracking branch 'origin/main' into issue_nerve_651_4
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/handler.go
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/modules/tracedetail/tracedetail.go
2026-12-03 10:29:56 +05:30
nityanandagohain
96b5443b28 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-12-03 10:27:42 +05:30
nityanandagohain
353e25c320 Merge remote-tracking branch 'origin/main' into issue_nerve_651_3
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/handler.go
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/modules/tracedetail/tracedetail.go
2026-12-03 09:45:42 +05:30
nityanandagohain
3a64e85459 style(trace-details): group search.go imports by origin
Assisted-by: Claude Opus 5.5
2026-12-02 21:05:20 +05:30
nityanandagohain
c5b98e86c1 fix(trace-details): search resource attributes in the resource JSON column only
Assisted-by: Claude Opus 5.5
2026-12-02 20:56:36 +05:30
nityanandagohain
82617fac20 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5 2026-12-02 20:52:54 +05:30
nityanandagohain
8f12a9c99d Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-12-02 20:52:27 +05:30
nityanandagohain
133ac48aaf fix: read from json column 2026-12-02 20:45:35 +05:30
nityanandagohain
a676fd3fca fix(trace-details): find snippets only in the parts each search() call searches
Assisted-by: Claude Opus 5.5
2026-12-02 09:39:32 +05:30
nityanandagohain
2ad6292730 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5 2026-12-02 09:35:55 +05:30
nityanandagohain
22739f406b fix(trace-details): return selected scope attributes in span lists
Assisted-by: Claude Opus 5.5
2026-12-02 09:35:44 +05:30
nityanandagohain
d38d9c10a3 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5 2026-12-02 09:23:38 +05:30
nityanandagohain
7e6eba82bd test(trace-details): pass span usage by value in the span list tests
Assisted-by: Claude Opus 5.5
2026-12-02 09:23:27 +05:30
nityanandagohain
b41341a87d Merge branch 'issue_nerve_651_4' into issue_nerve_651_5 2026-12-02 09:23:02 +05:30
nityanandagohain
14f8a813c4 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-12-02 09:22:56 +05:30
nityanandagohain
142b98a31e Merge branch 'issue_nerve_651_2' into issue_nerve_651_3 2026-12-02 09:22:46 +05:30
nityanandagohain
687ce8c5d6 refactor(trace-details): build service stats and test usage without pointer copies
Assisted-by: Claude Opus 5.5
2026-12-02 09:22:35 +05:30
nityanandagohain
31644c65ba Merge branch 'issue_nerve_651_4' into issue_nerve_651_5 2026-12-02 09:19:54 +05:30
nityanandagohain
3593339907 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-12-02 09:19:12 +05:30
nityanandagohain
88ed8d6e2a Merge branch 'issue_nerve_651_2' into issue_nerve_651_3 2026-12-02 09:17:55 +05:30
nityanandagohain
a8d30be82e Merge remote-tracking branch 'origin/main' into issue_nerve_651_2
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/handler.go
#	pkg/modules/tracedetail/impltracedetail/store.go
#	pkg/types/spantypes/trace_highlights.go
2026-12-02 09:16:51 +05:30
nityanandagohain
4171a5835a fix(trace-details): match search() text in decoded JSON values, not across punctuation 2026-12-01 20:16:11 +05:30
nityanandagohain
736d108485 chore(openapi): regenerate specs
Assisted-by: Claude Opus 5.5
2026-12-01 19:58:04 +05:30
nityanandagohain
b339f056e2 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5
# Conflicts:
#	docs/api/openapi.yml
#	frontend/src/api/generated/services/sigNoz.schemas.ts
#	pkg/types/spantypes/span.go
2026-12-01 19:57:09 +05:30
nityanandagohain
98c709e362 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-12-01 19:55:47 +05:30
nityanandagohain
dd81355d60 chore(openapi): regenerate specs
Assisted-by: Claude Opus 5.5
2026-12-01 19:54:39 +05:30
nityanandagohain
536fe6c065 Merge branch 'issue_nerve_651_2' into issue_nerve_651_3
# Conflicts:
#	frontend/src/api/generated/services/sigNoz.schemas.ts
#	pkg/types/spantypes/span.go
2026-12-01 19:53:42 +05:30
nityanandagohain
0e000f6a00 Merge branch 'issue_nerve_651_1' into issue_nerve_651_2 2026-12-01 19:52:06 +05:30
nityanandagohain
a527841297 fix: address comment 2026-12-01 18:52:47 +05:30
nityanandagohain
dc57e60a73 fix: add authz 2026-12-01 17:30:33 +05:30
nityanandagohain
080291be69 fix: address comments 2026-12-01 14:49:55 +05:30
nityanandagohain
935ad00c12 fix: address comments 2026-11-30 13:35:53 +05:30
nityanandagohain
8fc0d1e775 feat(querybuilder): support search() on traces 2026-11-30 13:01:03 +05:30
nityanandagohain
0bac4990ef fix: address comments 2026-11-30 10:42:27 +05:30
nityanandagohain
f028897749 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/modules/tracedetail/impltracedetail/store.go
#	pkg/types/spantypes/store.go
2026-11-27 18:50:38 +05:30
nityanandagohain
f4023c9f6f fix(trace-details): pass the org id to the span list tree read
Assisted-by: Claude Opus 5.5
2026-11-27 18:46:41 +05:30
nityanandagohain
791d150554 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-11-27 18:45:47 +05:30
nityanandagohain
56a3148a77 Merge branch 'issue_nerve_651_2' into issue_nerve_651_3
# Conflicts:
#	pkg/modules/tracedetail/tracedetail.go
2026-11-27 18:45:46 +05:30
nityanandagohain
af7d1d31fd fix: address comment 2026-11-27 12:34:39 +05:30
nityanandagohain
eed2c7d177 perf(trace-details): find a word with a substring search, then map the position back
Assisted-by: Claude Fable 5.2
2026-11-25 17:53:54 +05:30
nityanandagohain
ff3bff481a fix(trace-details): match escaped JSON text and keep snippets for any case 2026-11-25 17:42:36 +05:30
nityanandagohain
5902ba86c4 fix(trace-details): search the resource JSON before the resource map 2026-11-25 17:25:35 +05:30
nityanandagohain
5870d1f2b5 refactor(querybuilder): keep the existing visitor options untouched
FullTextCondition moves to the end of the struct, so the lines of the
other options are not re-aligned.

Assisted-by: Claude Fable 5.2
2026-11-25 17:10:11 +05:30
nityanandagohain
d63c6fb344 Merge branch 'issue_nerve_651_4' into issue_nerve_651_5
Assisted-by: Claude Fable 5.2
2026-11-25 17:09:26 +05:30
nityanandagohain
9341922a83 feat(trace-details): select the span's own fields in a list
selectFields fills http_method, db_name, scope.name and the other
optional fields of a span the way a trace list query reads them.

Assisted-by: Claude Fable 5.2
2026-11-25 17:05:19 +05:30
nityanandagohain
015e0ab502 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4
Assisted-by: Claude Fable 5.2
2026-11-25 17:05:15 +05:30
nityanandagohain
af8e036412 refactor(trace-details): fill the optional span fields with plain assignments
Assisted-by: Claude Fable 5.2
2026-11-25 17:00:39 +05:30
nityanandagohain
94ead23432 chore(trace-details): regenerate the api spec for the optional span fields
Assisted-by: Claude Fable 5.2
2026-11-25 16:54:36 +05:30
nityanandagohain
9ed59f872b feat(trace-details): return the derived fields and the scope of a span
A span read by id now carries http_method, http_url, http_host,
external_http_method, external_http_url, db_name, db_operation,
trace_state and scope. Each is left out when the span has none.

Assisted-by: Claude Fable 5.2
2026-11-25 16:54:35 +05:30
nityanandagohain
63caf73fdb fix(trace-details): read selectFields as a trace list query does
A context word can be part of an attribute name, a span context reads
the attribute, and a field of the span itself is not read as an
attribute.

Assisted-by: Claude Fable 5.2
2026-11-25 16:49:56 +05:30
nityanandagohain
9ef7def96c Merge branch 'issue_nerve_651_4' into issue_nerve_651_5
A list reads its spans by id only for selectFields or matched words;
the status and references come with the trace tree.

Assisted-by: Claude Fable 5.2
2026-11-25 16:16:47 +05:30
nityanandagohain
d2ca350b51 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4
The list picker now comes from the highlights branch; this branch adds
the scopes, selectFields and the routes on top of it.

Assisted-by: Claude Fable 5.2
2026-11-25 16:12:49 +05:30
nityanandagohain
478a7645e4 Merge branch 'issue_nerve_651_2' into issue_nerve_651_3 2026-11-25 16:11:30 +05:30
nityanandagohain
1d0b83cb6d refactor(trace-details): pick a page from any set of spans
The span list routes use the same picker for the children, descendants
and ancestors of a span, so it takes the spans to pick from, an offset
and a limit. Highlights pass the whole trace.

Assisted-by: Claude Fable 5.2
2026-11-25 16:11:29 +05:30
nityanandagohain
6f5d3af7f7 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4 2026-11-25 15:53:25 +05:30
nityanandagohain
b0386a0850 Merge branch 'issue_nerve_651_2' into issue_nerve_651_3 2026-11-25 15:44:04 +05:30
nityanandagohain
ca4f2f5236 fix: address comment 2026-11-25 15:37:43 +05:30
nityanandagohain
9777092344 fix: use single query 2026-11-25 15:26:13 +05:30
nityanandagohain
de7a4c084c Merge branch 'issue_nerve_651_1' into issue_nerve_651_2 2026-11-25 14:42:09 +05:30
nityanandagohain
eaf4cb9a81 fix: address comments 2026-11-25 13:15:52 +05:30
nityanandagohain
0acf668098 fix: address comments 2026-11-25 13:07:28 +05:30
nityanandagohain
f0868980ac feat(trace-details): implement query on the span list routes 2026-11-25 11:58:41 +05:30
nityanandagohain
4d3edfc60f feat(trace-details): implement the span list routes 2026-11-24 17:22:11 +05:30
nityanandagohain
d79b50e6fc feat(trace-details): implement the single span route 2026-11-24 16:26:59 +05:30
nityanandagohain
122a28eecc feat(trace-details): implement the trace highlights route 2026-11-24 16:06:09 +05:30
nityanandagohain
319149f3f9 chore(trace-details): regenerate the api spec for the highlights without the summary 2026-11-24 15:32:46 +05:30
nityanandagohain
3ad9300dd3 chore(trace-details): regenerate the api spec without the span percentile route 2026-11-24 15:17:44 +05:30
nityanandagohain
de2f960771 chore(trace-details): regenerate the api spec for the span list views 2026-11-24 14:50:53 +05:30
nityanandagohain
9e5e145b46 feat(trace-details): add the API contract for the trace highlights and span routes 2026-11-24 14:37:21 +05:30
nityanandagohain
e892107960 chore(trace-details): regenerate the api spec for the http_5xx reason 2026-11-23 22:06:05 +05:30
nityanandagohain
273ec41fb3 Merge remote-tracking branch 'origin/main' into issue_nerve_651_1 2026-11-23 21:33:18 +05:30
nityanandagohain
b81bbea9f1 refactor(trace-details): drop the tree list from the trace overview 2026-11-23 21:32:34 +05:30
nityanandagohain
8954823bf9 fix: update descriptions 2026-11-23 15:04:13 +05:30
nityanandagohain
08cca0f59b feat(trace-details): replace the inspect contract with overview and span routes 2026-11-23 14:07:12 +05:30
nityanandagohain
690a2af781 chore(trace-details): regenerate the api spec for the trace inspect routes
Assisted-by: Claude Fable 5.2
2026-11-20 15:38:17 +05:30
nityanandagohain
82c8c1c43d refactor(trace-details): split the trace inspect contract into three routes
One route returned one of three shapes behind a type field, which needed
optional sibling fields. Each part now has its own route and response type.

Assisted-by: Claude Fable 5.2
2026-11-20 15:38:16 +05:30
nityanandagohain
75686f4004 fix(trace-details): update the trace inspect contract for the tree and the span cap 2026-11-19 21:18:30 +05:30
nityanandagohain
2df97d39e2 feat(trace-details): add the API contract for the trace inspect endpoint
Adds GET /api/v1/traces/{traceID}/inspect to the API spec with its query
  parameters and response types. The handler answers 501 for now; the
  implementation follows in separate PRs (overview, open a span, search).

  The response holds one of three parts, named by :
  - overview: identity, errors, failures not marked as errors, slowest spans,
    most expensive spans, span links and the tree
  - span: one span's summary and full record, with its ancestors and descendants
  - find: the spans matching a search, or every span with allSpans

  Every list has total, items and nextCursor, and every item starts with the
  span and its direct parent.

  Refs SigNoz/nerve-pod#651
2026-11-19 16:42:40 +05:30
24 changed files with 1029 additions and 115 deletions

View File

@@ -13195,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
@@ -19805,15 +19805,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.'
@@ -19991,15 +19993,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.'
@@ -20114,15 +20118,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.'
@@ -20237,15 +20243,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.'

View File

@@ -14851,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;
@@ -16437,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;
/**
@@ -16488,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;
/**
@@ -16527,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;
/**
@@ -16566,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;
/**

View File

@@ -326,18 +326,26 @@ func (m *module) ListTraceSpans(ctx context.Context, orgID valuer.UUID, 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)
page, err := spantypes.NewSpanListPage(skeleton, query, search)
if err != nil {
return nil, err
}
// The attributes of the page's spans are read only when the response shows some of them.
// The full rows of the page's spans are read only for selected fields and for search() snippets.
var rows []spantypes.StorableSpan
if len(query.SelectFields) > 0 {
if page.ReadsAttributes() {
rows, err = m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, page.SpanIDs())
if err != nil {
return nil, err

View File

@@ -72,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
@@ -88,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))
@@ -97,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 {
@@ -109,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
}
@@ -175,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,
@@ -188,30 +192,30 @@ 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) {
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 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
}
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
usageColumns, err := store.genAIUsageColumns(ctx, q, keys)
if err != nil {
return nil, err
}
@@ -219,12 +223,12 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
}
// genAIUsageColumns returns the token and cost columns of a span, resolved across attribute evolutions.
func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
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
}
@@ -234,7 +238,7 @@ func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo,
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),
@@ -246,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",
@@ -270,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
}
@@ -296,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
@@ -310,8 +314,8 @@ 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",
@@ -320,11 +324,11 @@ func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, trac
"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
}
@@ -363,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))
@@ -383,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)
}
@@ -392,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",
@@ -429,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
@@ -453,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))
@@ -463,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
@@ -507,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))
@@ -522,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")
}
@@ -536,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
}
@@ -548,17 +552,17 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
return sb.Or(conds...), nil
}
func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
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 := 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()))
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
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
}
@@ -584,7 +588,7 @@ func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, tr
sb.OrderByAsc("span_id")
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := s.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
rows, err := store.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace skeleton")
}
@@ -618,3 +622,53 @@ func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, tr
}
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
}

View File

@@ -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 {

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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")
})
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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.

View File

@@ -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)

View File

@@ -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")
}

View File

@@ -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},
}
}

View File

@@ -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)
})
}
}

View 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
}

View File

@@ -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 {

View File

@@ -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

View File

@@ -43,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."`
@@ -138,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 {

View File

@@ -41,6 +41,8 @@ type TraceStore interface {
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)

View File

@@ -5,7 +5,10 @@ import (
"fmt"
"maps"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
@@ -22,6 +25,10 @@ const (
const (
spanListDefaultLimit = 50
spanListMaxLimit = 1000
spanMatchLimit = 3
spanMatchSnippetRadius = 40
snippetMark = "…"
)
var (
@@ -38,7 +45,9 @@ type SpanListQuery struct {
// 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
View SpanListView
// Query is a filter expression. Empty when there is nothing to match.
Query string
SelectFields []telemetrytypes.TelemetryFieldKey
Offset int
Limit int
@@ -52,18 +61,32 @@ type SpanListPage struct {
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, Offset: params.Offset}
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 strings.TrimSpace(params.Query) != "" {
return nil, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "query is not implemented yet")
}
if params.Offset < 0 {
return nil, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidOffset, "offset cannot be negative, got %d", params.Offset)
}
@@ -81,16 +104,29 @@ func NewSpanListQuery(params *ListTraceSpansParams, scope SpanScope, scopeSpanID
return query, nil
}
func NewSpanListPage(skeleton *TraceSkeleton, query *SpanListQuery) (*SpanListPage, error) {
// 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 {
@@ -100,7 +136,7 @@ func (page *SpanListPage) SpanIDs() []string {
}
// NewSpanList builds the page. rows holds the stored data of its spans, read only for the selected
// fields. A selected field no span of the page has is reported as a warning.
// 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 {
@@ -108,14 +144,16 @@ func NewSpanList(page *SpanListPage, rows []StorableSpan) *SpanList {
}
skeleton := page.skeleton
list := &SpanList{Total: page.total, Items: make([]SpanItem, 0, len(page.positions))}
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)
}
item.Span.selectFields(byID[skeleton.spanID(i)], page.selectFields, found)
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 {
@@ -247,6 +285,113 @@ func setString(target *string, value string) bool {
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:
@@ -296,6 +441,21 @@ func (skeleton *TraceSkeleton) scopePositions(scope SpanScope, spanID string) ([
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 {

View File

@@ -1,6 +1,7 @@
package spantypes
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -99,6 +100,7 @@ func TestNewSpanListPage(t *testing.T) {
testCases := []struct {
name string
query SpanListQuery
search *SpanSearch
expected []string
expectedTotal uint64
}{
@@ -151,18 +153,39 @@ func TestNewSpanListPage(t *testing.T) {
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)
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})
_, err := NewSpanListPage(checkoutSkeleton(nil), &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "missing", Limit: 50}, nil)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
}
@@ -177,15 +200,85 @@ func TestNewSpanListPage_TimeSpent_ShowsTheGroupByItsLongestSpanInScope(t *testi
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})
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})
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)
@@ -199,7 +292,7 @@ func TestNewSpanListPage_AIUsage_RanksByTokensWhenNoListedSpanHasACost(t *testin
skeletonSpec{id: "fetch", parent: "tools", usage: AISpanUsage{InputTokens: value(100)}},
)
page, err := NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "tools", View: SpanListViewAIUsage, Limit: 50})
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())
}

View 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

View File

@@ -198,6 +198,127 @@ def test_list_trace_spans_select_fields(
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