Compare commits

..

2 Commits

Author SHA1 Message Date
Vinícius Lourenço
649c3a250c build(web): pin hashed asset names that the immutable cache relies on 2026-11-23 22:46:11 -03:00
Vinícius Lourenço
f7b1383427 perf(web): cache hashed frontend assets as immutable 2026-11-23 22:46:09 -03:00
57 changed files with 273 additions and 4464 deletions

View File

@@ -94,7 +94,7 @@ jobs:
postgres:15 \
clickhouse/clickhouse-server:25.12.5 \
clickhouse/clickhouse-keeper:25.12.5 \
signoz/signoz-otel-collector:v0.144.17 \
signoz/signoz-otel-collector:v0.144.16-rc.1 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,18 +85,13 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.17
- v0.144.16-rc.1
postgres-version:
- 15
exclude:
- sqlstore-provider: postgres
clickhouse-version: 26.8.34
if: |
((github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))) && contains(github.event.pull_request.labels.*.name, 'safe-to-integrate')
continue-on-error: ${{ matrix.clickhouse-version == '26.8.34' }}
runs-on: ubuntu-latest
steps:
- name: checkout

View File

@@ -474,14 +474,6 @@ auditor:
compression: lz4
# The maximum time to drain buffered events on shutdown. Undelivered events are dropped after it.
shutdown_timeout: 30s
tls:
# Whether to connect to the brokers over TLS.
enabled: false
# The PEM CA bundle that verifies broker certificates. Empty uses the system roots.
ca_file: ""
# The client certificate and key, for brokers that require client auth. Set both or neither.
cert_file: ""
key_file: ""
##################### Cloud Integration #####################
cloudintegration:

File diff suppressed because it is too large Load Diff

View File

@@ -2,10 +2,7 @@ package kafkaauditor
import (
"context"
"crypto/tls"
"crypto/x509"
"log/slog"
"os"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/plugin/kslog"
@@ -13,7 +10,6 @@ import (
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/auditor/auditorserver"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/types/audittypes"
@@ -43,25 +39,13 @@ func newProvider(_ context.Context, providerSettings factory.ProviderSettings, c
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
opts := []kgo.Opt{
client, err := kgo.NewClient(
kgo.SeedBrokers(config.Kafka.Brokers...),
kgo.ClientID(config.Kafka.ClientID),
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
kgo.ProducerLinger(0),
kgo.WithLogger(kslog.New(settings.Logger())),
}
if config.Kafka.TLS.Enabled {
tlsConfig, err := newTLSConfig(config.Kafka.TLS)
if err != nil {
return nil, err
}
// franz-go sets ServerName per broker from the dialed address.
opts = append(opts, kgo.DialTLSConfig(tlsConfig))
}
client, err := kgo.NewClient(opts...)
)
if err != nil {
return nil, err
}
@@ -146,30 +130,3 @@ func compressionCodec(name string) kgo.CompressionCodec {
return kgo.NoCompression()
}
}
func newTLSConfig(config auditor.TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{}
if config.CAFile != "" {
caPEM, err := os.ReadFile(config.CAFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot read auditor::kafka::tls::ca_file")
}
tlsConfig.RootCAs = x509.NewCertPool()
if !tlsConfig.RootCAs.AppendCertsFromPEM(caPEM) {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "auditor::kafka::tls::ca_file %q holds no PEM certificate", config.CAFile)
}
}
if config.CertFile != "" {
cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot load auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return tlsConfig, nil
}

View File

@@ -1,269 +0,0 @@
package kafkaauditor
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/twmb/franz-go/pkg/kfake"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/types/audittypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/version"
)
func TestExport_MutualTLS(t *testing.T) {
certificates := newTestCertificates(t)
cluster, err := kfake.NewCluster(
kfake.NumBrokers(1),
kfake.SeedTopics(1, "tls_audit"),
kfake.TLS(&tls.Config{
Certificates: []tls.Certificate{certificates.server},
ClientCAs: certificates.caPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}),
)
require.NoError(t, err)
t.Cleanup(cluster.Close)
testCases := []struct {
name string
tls auditor.TLSConfig
err bool
}{
{
name: "CAAndClientCertificate_Delivers",
tls: certificates.client,
},
{
name: "TLSDisabled_Fails",
tls: auditor.TLSConfig{},
err: true,
},
{
name: "WithoutClientCertificate_Fails",
tls: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
err: true,
},
{
name: "WithoutCA_Fails",
tls: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
config := auditor.Config{
Provider: "kafka",
BufferSize: 10,
BatchSize: 5,
FlushInterval: 50 * time.Millisecond,
Kafka: auditor.KafkaConfig{
Brokers: cluster.ListenAddrs(),
Topic: "tls_audit",
ClientID: "signoz-tls-test",
Compression: "lz4",
ShutdownTimeout: 30 * time.Second,
TLS: testCase.tls,
},
}
auditor, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, version.Info)
require.NoError(t, err)
provider := auditor.(*provider)
defer provider.client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = provider.export(ctx, []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, testCase.name)})
if testCase.err {
assert.True(t, errors.Is(err, context.DeadlineExceeded))
return
}
require.NoError(t, err)
})
}
consumerTLS, err := newTLSConfig(certificates.client)
require.NoError(t, err)
consumer, err := kgo.NewClient(
kgo.SeedBrokers(cluster.ListenAddrs()...),
kgo.DialTLSConfig(consumerTLS),
kgo.ConsumeTopics("tls_audit"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
require.NoError(t, err)
defer consumer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fetches := consumer.PollFetches(ctx)
require.Empty(t, fetches.Errors())
assert.Len(t, fetches.Records(), 1)
}
func TestNewTLSConfig(t *testing.T) {
certificates := newTestCertificates(t)
notPEMFile := filepath.Join(t.TempDir(), "not-pem.crt")
require.NoError(t, os.WriteFile(notPEMFile, []byte("not a pem"), 0o600))
testCases := []struct {
name string
config auditor.TLSConfig
err bool
wantRootCAs bool
wantCertificates int
}{
{
name: "NoFiles_UsesSystemRoots",
config: auditor.TLSConfig{Enabled: true},
},
{
name: "CAOnly",
config: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
wantRootCAs: true,
},
{
name: "CAAndClientCertificate",
config: certificates.client,
wantRootCAs: true,
wantCertificates: 1,
},
{
name: "CAFileMissing",
config: auditor.TLSConfig{Enabled: true, CAFile: filepath.Join(t.TempDir(), "missing-ca.crt")},
err: true,
},
{
name: "CAFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CAFile: notPEMFile},
err: true,
},
{
name: "KeyFileMissing",
config: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: filepath.Join(t.TempDir(), "missing.key")},
err: true,
},
{
name: "CertFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CertFile: notPEMFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tlsConfig, err := newTLSConfig(testCase.config)
if testCase.err {
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
return
}
require.NoError(t, err)
assert.Equal(t, testCase.wantRootCAs, tlsConfig.RootCAs != nil)
assert.Len(t, tlsConfig.Certificates, testCase.wantCertificates)
})
}
}
type testCertificates struct {
caPool *x509.CertPool
server tls.Certificate
client auditor.TLSConfig
}
// Issues a CA, a broker certificate for 127.0.0.1 and a client certificate, writing the client side as ca.crt, tls.crt and tls.key.
func newTestCertificates(t *testing.T) testCertificates {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
caTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "test-ca"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCertSign,
}
caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
require.NoError(t, err)
ca, err := x509.ParseCertificate(caDER)
require.NoError(t, err)
serverCertPEM, serverKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "broker"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
})
server, err := tls.X509KeyPair(serverCertPEM, serverKeyPEM)
require.NoError(t, err)
clientCertPEM, clientKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(3),
Subject: pkix.Name{CommonName: "signoz"},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
})
dir := t.TempDir()
client := auditor.TLSConfig{
Enabled: true,
CAFile: filepath.Join(dir, "ca.crt"),
CertFile: filepath.Join(dir, "tls.crt"),
KeyFile: filepath.Join(dir, "tls.key"),
}
require.NoError(t, os.WriteFile(client.CAFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o600))
require.NoError(t, os.WriteFile(client.CertFile, clientCertPEM, 0o600))
require.NoError(t, os.WriteFile(client.KeyFile, clientKeyPEM, 0o600))
caPool := x509.NewCertPool()
caPool.AddCert(ca)
return testCertificates{caPool: caPool, server: server, client: client}
}
func issueTestCertificate(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, template *x509.Certificate) ([]byte, []byte) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template.NotBefore = time.Now().Add(-time.Hour)
template.NotAfter = time.Now().Add(time.Hour)
template.KeyUsage = x509.KeyUsageDigitalSignature
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
require.NoError(t, err)
keyDER, err := x509.MarshalECPrivateKey(key)
require.NoError(t, err)
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
}

3
frontend/.gitignore vendored
View File

@@ -1,4 +1,7 @@
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
/public/assets/
# Sentry Config File
.env.sentry-build-plugin
.qodo

View File

@@ -28,7 +28,7 @@ You are operating within a constrained context window and strict system prompts.
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
- Never override a `@signozhq/ui` component's styles: no `--<component>-*` CSS variables, no `:global` class or `data-*` selectors, no restyling through `className`/`style`. Use its props, and put layout on a wrapper you own. When it can't do what the design needs, file a UI suggestion in `SigNoz/uforge-pod` (`ui-suggestion.yml` template) and link it in the PR.
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.

View File

@@ -9,12 +9,12 @@
- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)
- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)
- [ ] No magic numbers - use `--spacing-*` tokens
- [ ] Typography uses `--{variant}-{size}-{weight}-*` text style tokens (see Typography)
- [ ] No overrides of `@signozhq/ui` components (see below)
- [ ] Global escapes only for third-party overrides (`@signozhq/ui` is not third-party)
- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
- [ ] Global escapes only for third-party overrides
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
.icon { } // -> styles.icon (separate class, not scoped under .button)
}
// GOOD: Flat structure
@@ -289,32 +289,88 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## @signozhq/ui Components
## Overriding @signozhq/ui Components
Don't override them. That covers setting a component's `--<component>-*` CSS variables, targeting its classes or `data-*` attributes through `:global(...)`, and restyling it with `className` or `style`. An override keeps working until the component changes, then breaks with no type error or lint warning, and the screen drifts from every other one using that component.
Components expose CSS variables for customization.
- Use the component's props (`variant`, `color`, `size`, ...) for how it looks.
- Put layout (position, margin, width inside a flex or grid parent) on a wrapper element you own.
- If the component can't do what the design needs, file a [UI suggestion](https://github.com/SigNoz/uforge-pod/issues/new?template=ui-suggestion.yml) in `SigNoz/uforge-pod` and ship with the component as it renders until the suggestion is decided. Link the issue in the PR.
You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.
Never write a override without confirm it exists.
Override via:
### Method 1: CSS Variables (Preferred)
Each component exposes `--<component>-<property>` variables:
```scss
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
// Override Button
.customButton {
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--label-base-400-font-size);
}
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
// Override Input
.customInput {
--input-height: 2.5rem;
--input-border-color: var(--l2-border);
--input-padding: var(--spacing-2) var(--spacing-6);
--input-placeholder-color: var(--l3-foreground);
}
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
}
```
### Method 2: Data Attributes
Components use data attributes for variants/states. Target them for state-specific overrides:
```scss
// Target variant
.wrapper :global([data-variant="outlined"]) {
--button-border-color: var(--accent-primary);
}
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
}
// Target color
.wrapper :global([data-color="destructive"]) {
--button-background: var(--danger-background);
}
// Target state (Radix patterns)
.popover :global([data-state="open"]) {
opacity: 1;
}
.tooltip :global([data-side="top"]) {
margin-bottom: var(--spacing-2);
}
```
### Common Component CSS Variables
**Button:**
- `--button-background`, `--button-border-radius`, `--button-padding`
- `--button-font-size`, `--button-height`, `--button-gap`
- `--button-hover-background`, `--button-disabled-opacity`
**Input:**
- `--input-height`, `--input-border-color`, `--input-background`
- `--input-padding`, `--input-font-size`, `--input-placeholder-color`
- `--input-focus-outline-color`, `--input-hover-border-color`
- `--input-prefix-*`, `--input-suffix-*` for adornments
**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`
## Good Patterns
### Structure
@@ -378,21 +434,24 @@ Don't override them. That covers setting a component's `--<component>-*` CSS var
### Keyframes (Local Scoping)
CSS Modules scope `@keyframes` like classes: the build renames `fadeIn` to `_fadeIn_<hash>` and rewrites every `animation` in the same module that names it. Don't wrap it in `:local(...)`; Sass rejects `:local(@keyframes fadeIn)` with `expected selector`.
Without `:local()`, keyframe names are global and can clash across modules:
```scss
// GOOD: Local to this module
// BAD: Global keyframe - can conflict with other modules
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
// GOOD: Locally scoped keyframe
:local(@keyframes fadeIn) {
from { opacity: 0; }
to { opacity: 1; }
}
.modal {
animation: fadeIn 200ms ease;
}
// BAD: Doesn't compile
:local(@keyframes fadeIn) { }
```
## JS Import Patterns

View File

@@ -14204,19 +14204,7 @@ export interface SpantypesTraceAITokensDTO {
}
export interface SpantypesTraceAISummaryDTO {
/**
* @type integer
* @minimum 0
* @description Number of model call spans: spans with gen_ai.request.model.
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
* @description Number of tool call spans: spans with gen_ai.tool.name.
*/
toolCallCount: number;
/**
* @type number
*/
@@ -14644,266 +14632,6 @@ export interface SpantypesPostableWaterfallDTO {
uncollapsedSpans?: string[] | null;
}
export interface SpantypesSameNameSiblingStatsDTO {
/**
* @type integer
* @minimum 0
* @description Number of spans in the group that are marked as errors.
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
* @description Total own time of the group, in nanoseconds.
*/
ownTimeNano: number;
/**
* @type integer
* @minimum 0
* @description Number of spans in the group, this span included.
*/
spanCount: number;
}
/**
* Span attributes. A span read by ID has all of them; a span in a list has only the selected ones.
*/
export type SpantypesSpanDTOAttributes = { [key: string]: unknown };
/**
* Resource attributes. Always includes service.name. A span read by ID has all of them; a span in a list also has the selected ones.
*/
export type SpantypesSpanDTOResource = { [key: string]: string };
export interface SpantypesSpanDTO {
/**
* @type object
* @description Span attributes. A span read by ID has all of them; a span in a list has only the selected ones.
*/
attributes: SpantypesSpanDTOAttributes;
/**
* @type integer
* @minimum 0
* @description Duration, in nanoseconds.
*/
duration_nano: number;
/**
* @type array
* @description Span events. A span read by ID has all of them; a span in a list has none.
*/
events: SpantypesEventDTO[];
/**
* @type boolean
* @description Whether the span is marked as an error.
*/
has_error: boolean;
/**
* @type string
* @description Span kind, for example Server, Client or Internal.
*/
kind_string: string;
/**
* @type string
*/
name: string;
/**
* @type string
* @description ID of the parent span. Empty for a root.
*/
parent_span_id: string;
/**
* @type array
* @description References to other spans: the parent as CHILD_OF, and each span link as FOLLOWS_FROM.
*/
references: SpantypesOtelSpanRefDTO[];
/**
* @type object
* @description Resource attributes. Always includes service.name. A span read by ID has all of them; a span in a list also has the selected ones.
*/
resource: SpantypesSpanDTOResource;
/**
* @type string
* @description HTTP or gRPC status code of the response, for example 404. Empty when the span has none.
*/
response_status_code: string;
/**
* @type string
*/
span_id: string;
/**
* @type string
* @description OpenTelemetry status code of the span.
*/
status_code_string: string;
/**
* @type string
* @description Status message, usually the error text. Empty when the span has none.
*/
status_message: string;
/**
* @type integer
* @minimum 0
* @description Start time, in nanoseconds since the Unix epoch.
*/
timestamp: number;
/**
* @type string
*/
trace_id: string;
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
* @description Where the word was found: name, status_message, attributes.<name>, resource.<name> or events[<index>].
*/
field: string;
/**
* @type string
* @description The word with some of the text around it.
*/
snippet: string;
}
export interface SpantypesSpanTreeStatsDTO {
/**
* @type integer
* @minimum 0
* @description Number of direct children.
*/
childCount: number;
/**
* @type integer
* @minimum 0
* @description Number of ancestors in a row, starting at the parent, that are marked as errors. On an error span it shows how far up the error spread.
*/
errorAncestorCount: number;
/**
* @type integer
* @minimum 0
* @description Depth in the trace: 0 for a root, 1 for its children, and so on.
*/
level: number;
/**
* @type integer
* @minimum 0
* @description Time spent in the span itself, in nanoseconds: its duration minus the time its children cover.
*/
ownTimeNano: number;
/**
* @description Totals for the spans that share this span's name and parent, this span included. Omitted when no other span does.
*/
sameNameSiblings?: SpantypesSameNameSiblingStatsDTO;
/**
* @type integer
* @minimum 0
* @description Number of spans below this one, at any depth.
*/
subtreeSpanCount: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
http_5xx = 'http_5xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesSpanItemDTO {
/**
* @type array
* @description Where the words of the query were found, up to three places. A list does not return all attributes or any events, so this is how to see why a span matched. Omitted when the query has no words.
*/
matches?: SpantypesSpanTextMatchDTO[];
span: SpantypesSpanDTO;
/**
* @description Numbers computed from the span's place in the trace.
*/
treeStats: SpantypesSpanTreeStatsDTO;
/**
* @description Why the span counts as failed although it is not marked as an error. Omitted for every other span.
*/
unmarkedFailureReason?: SpantypesUnmarkedFailureReasonDTO;
}
export interface SpantypesSpanListDTO {
/**
* @type array
* @description The spans of this page.
*/
items: SpantypesSpanItemDTO[];
/**
* @type integer
* @minimum 0
* @description Number of spans that match the request, across all pages.
*/
total: number;
/**
* @type array
* @description Reasons the result may be incomplete, for example a query key that is not known or a selected field that no returned span has. Omitted when there are none.
*/
warnings?: string[];
}
export enum SpantypesSpanListViewDTO {
error_origins = 'error_origins',
unmarked_failures = 'unmarked_failures',
time_spent = 'time_spent',
ai_usage = 'ai_usage',
links = 'links',
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
* @description Number of spans of the service that are marked as errors.
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
* @description Total own time of the service's spans, in nanoseconds.
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
* @description Number of spans of the service.
*/
spanCount: number;
}
export interface SpantypesTraceHighlightsDTO {
/**
* @description The spans with the highest gen_ai cost or token usage. First page of the ai_usage view of the span list. Empty for a trace where no span carries that usage.
*/
aiUsage?: SpantypesSpanListDTO;
/**
* @description The spans where an error started. First page of the error_origins view of the span list.
*/
errorOrigins?: SpantypesSpanListDTO;
/**
* @description Spans that link to other spans. First page of the links view of the span list.
*/
links?: SpantypesSpanListDTO;
/**
* @type array
* @description Totals for each service of the trace, highest own time first.
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @description Where the time went, same-name siblings counted as one. First page of the time_spent view of the span list.
*/
timeSpent?: SpantypesSpanListDTO;
/**
* @description Spans that failed without being marked as errors. First page of the unmarked_failures view of the span list.
*/
unmarkedFailures?: SpantypesSpanListDTO;
}
export interface SpantypesUpdatableSpanMapperDTO {
config?: SpantypesSpanMapperConfigDTO;
/**
@@ -16369,197 +16097,6 @@ export type GetTraceAggregations200 = {
status: string;
};
export type GetTraceHighlightsPathParameters = {
traceID: string;
};
export type GetTraceHighlightsParams = {
/**
* @type array
* @description The lists to return, each named by its view. Default: all of them.
*/
views?: SpantypesSpanListViewDTO[];
/**
* @type integer
* @description Number of spans in each list. Default: 10. Maximum: 1000.
*/
limit?: number;
};
export type GetTraceHighlights200 = {
data: SpantypesTraceHighlightsDTO;
/**
* @type string
*/
status: string;
};
export type ListTraceSpansPathParameters = {
traceID: string;
};
export type ListTraceSpansParams = {
/**
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
*/
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
*/
query?: string;
/**
* @type array
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
*/
selectFields?: string[];
/**
* @type integer
* @description Number of spans to skip. Default: 0.
*/
offset?: number;
/**
* @type integer
* @description Number of spans to return. Default: 50. Maximum: 1000.
*/
limit?: number;
};
export type ListTraceSpans200 = {
data: SpantypesSpanListDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSpanPathParameters = {
traceID: string;
spanID: string;
};
export type GetTraceSpan200 = {
data: SpantypesSpanDTO;
/**
* @type string
*/
status: string;
};
export type ListTraceSpanAncestorsPathParameters = {
traceID: string;
spanID: string;
};
export type ListTraceSpanAncestorsParams = {
/**
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
*/
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
*/
query?: string;
/**
* @type array
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
*/
selectFields?: string[];
/**
* @type integer
* @description Number of spans to skip. Default: 0.
*/
offset?: number;
/**
* @type integer
* @description Number of spans to return. Default: 50. Maximum: 1000.
*/
limit?: number;
};
export type ListTraceSpanAncestors200 = {
data: SpantypesSpanListDTO;
/**
* @type string
*/
status: string;
};
export type ListTraceSpanChildrenPathParameters = {
traceID: string;
spanID: string;
};
export type ListTraceSpanChildrenParams = {
/**
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
*/
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
*/
query?: string;
/**
* @type array
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
*/
selectFields?: string[];
/**
* @type integer
* @description Number of spans to skip. Default: 0.
*/
offset?: number;
/**
* @type integer
* @description Number of spans to return. Default: 50. Maximum: 1000.
*/
limit?: number;
};
export type ListTraceSpanChildren200 = {
data: SpantypesSpanListDTO;
/**
* @type string
*/
status: string;
};
export type ListTraceSpanDescendantsPathParameters = {
traceID: string;
spanID: string;
};
export type ListTraceSpanDescendantsParams = {
/**
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
*/
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
*/
query?: string;
/**
* @type array
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
*/
selectFields?: string[];
/**
* @type integer
* @description Number of spans to skip. Default: 0.
*/
offset?: number;
/**
* @type integer
* @description Number of spans to return. Default: 50. Maximum: 1000.
*/
limit?: number;
};
export type ListTraceSpanDescendants200 = {
data: SpantypesSpanListDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};

View File

@@ -22,11 +22,6 @@ import type {
GetFlamegraphPathParameters,
GetTraceAggregations200,
GetTraceAggregationsPathParameters,
GetTraceHighlights200,
GetTraceHighlightsParams,
GetTraceHighlightsPathParameters,
GetTraceSpan200,
GetTraceSpanPathParameters,
GetTraceSummary200,
GetTraceSummaryPathParameters,
GetTraceThread200,
@@ -34,18 +29,6 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
ListTraceSpanAncestors200,
ListTraceSpanAncestorsParams,
ListTraceSpanAncestorsPathParameters,
ListTraceSpanChildren200,
ListTraceSpanChildrenParams,
ListTraceSpanChildrenPathParameters,
ListTraceSpanDescendants200,
ListTraceSpanDescendantsParams,
ListTraceSpanDescendantsPathParameters,
ListTraceSpans200,
ListTraceSpansParams,
ListTraceSpansPathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -176,710 +159,7 @@ export const useGetTraceAggregations = <
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns the spans to look at, for a trace of any size: per-service totals and the first spans of each view of the span list. views names the lists to return; without it all of them are returned. Read more of a list from the span list with the view of the same name. The totals of the trace come from the trace summary.
* @summary Get highlights of a trace
*/
export const getTraceHighlights = (
{ traceID }: GetTraceHighlightsPathParameters,
params?: GetTraceHighlightsParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetTraceHighlights200>({
url: `/api/v1/traces/${traceID}/highlights`,
method: 'GET',
params,
signal,
});
};
export const getGetTraceHighlightsQueryKey = (
{ traceID }: GetTraceHighlightsPathParameters,
params?: GetTraceHighlightsParams,
) => {
return [
`/api/v1/traces/${traceID}/highlights`,
...(params ? [params] : []),
] as const;
};
export const getGetTraceHighlightsQueryOptions = <
TData = Awaited<ReturnType<typeof getTraceHighlights>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: GetTraceHighlightsPathParameters,
params?: GetTraceHighlightsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getTraceHighlights>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getGetTraceHighlightsQueryKey({ traceID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof getTraceHighlights>>
> = ({ signal }) => getTraceHighlights({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof getTraceHighlights>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetTraceHighlightsQueryResult = NonNullable<
Awaited<ReturnType<typeof getTraceHighlights>>
>;
export type GetTraceHighlightsQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get highlights of a trace
*/
export function useGetTraceHighlights<
TData = Awaited<ReturnType<typeof getTraceHighlights>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: GetTraceHighlightsPathParameters,
params?: GetTraceHighlightsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getTraceHighlights>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetTraceHighlightsQueryOptions(
{ traceID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Get highlights of a trace
*/
export const invalidateGetTraceHighlights = async (
queryClient: QueryClient,
{ traceID }: GetTraceHighlightsPathParameters,
params?: GetTraceHighlightsParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetTraceHighlightsQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns a page of the spans of a trace, in tree order from the top: a span is followed by the spans below it. view keeps only the spans of one kind, query narrows them, and selectFields names the attributes to fill. Values are returned whole.
* @summary List spans of a trace
*/
export const listTraceSpans = (
{ traceID }: ListTraceSpansPathParameters,
params?: ListTraceSpansParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListTraceSpans200>({
url: `/api/v1/traces/${traceID}/spans`,
method: 'GET',
params,
signal,
});
};
export const getListTraceSpansQueryKey = (
{ traceID }: ListTraceSpansPathParameters,
params?: ListTraceSpansParams,
) => {
return [
`/api/v1/traces/${traceID}/spans`,
...(params ? [params] : []),
] as const;
};
export const getListTraceSpansQueryOptions = <
TData = Awaited<ReturnType<typeof listTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: ListTraceSpansPathParameters,
params?: ListTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpans>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getListTraceSpansQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof listTraceSpans>>> = ({
signal,
}) => listTraceSpans({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpans>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type ListTraceSpansQueryResult = NonNullable<
Awaited<ReturnType<typeof listTraceSpans>>
>;
export type ListTraceSpansQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary List spans of a trace
*/
export function useListTraceSpans<
TData = Awaited<ReturnType<typeof listTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: ListTraceSpansPathParameters,
params?: ListTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpans>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListTraceSpansQueryOptions(
{ traceID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary List spans of a trace
*/
export const invalidateListTraceSpans = async (
queryClient: QueryClient,
{ traceID }: ListTraceSpansPathParameters,
params?: ListTraceSpansParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getListTraceSpansQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns one span with every attribute, resource attribute and event. Values are returned whole. It returns only the stored span: its tree stats come with it in any span list, and the spans around it come from the children, descendants and ancestors routes.
* @summary Get span of a trace
*/
export const getTraceSpan = (
{ traceID, spanID }: GetTraceSpanPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetTraceSpan200>({
url: `/api/v1/traces/${traceID}/spans/${spanID}`,
method: 'GET',
signal,
});
};
export const getGetTraceSpanQueryKey = ({
traceID,
spanID,
}: GetTraceSpanPathParameters) => {
return [`/api/v1/traces/${traceID}/spans/${spanID}`] as const;
};
export const getGetTraceSpanQueryOptions = <
TData = Awaited<ReturnType<typeof getTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: GetTraceSpanPathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getTraceSpan>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getGetTraceSpanQueryKey({ traceID, spanID });
const queryFn: QueryFunction<Awaited<ReturnType<typeof getTraceSpan>>> = ({
signal,
}) => getTraceSpan({ traceID, spanID }, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof getTraceSpan>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetTraceSpanQueryResult = NonNullable<
Awaited<ReturnType<typeof getTraceSpan>>
>;
export type GetTraceSpanQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get span of a trace
*/
export function useGetTraceSpan<
TData = Awaited<ReturnType<typeof getTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: GetTraceSpanPathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getTraceSpan>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetTraceSpanQueryOptions({ traceID, spanID }, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Get span of a trace
*/
export const invalidateGetTraceSpan = async (
queryClient: QueryClient,
{ traceID, spanID }: GetTraceSpanPathParameters,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetTraceSpanQueryKey({ traceID, spanID }) },
options,
);
return queryClient;
};
/**
* Returns a page of the spans above a span: the chain of parents from the span up to its root, the parent first, and nothing from other branches. The span itself is not included. It takes the same parameters as the span list. The list is empty for a root, and stops where a parent was never received.
* @summary List ancestors of a span
*/
export const listTraceSpanAncestors = (
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
params?: ListTraceSpanAncestorsParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListTraceSpanAncestors200>({
url: `/api/v1/traces/${traceID}/spans/${spanID}/ancestors`,
method: 'GET',
params,
signal,
});
};
export const getListTraceSpanAncestorsQueryKey = (
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
params?: ListTraceSpanAncestorsParams,
) => {
return [
`/api/v1/traces/${traceID}/spans/${spanID}/ancestors`,
...(params ? [params] : []),
] as const;
};
export const getListTraceSpanAncestorsQueryOptions = <
TData = Awaited<ReturnType<typeof listTraceSpanAncestors>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
params?: ListTraceSpanAncestorsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ??
getListTraceSpanAncestorsQueryKey({ traceID, spanID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof listTraceSpanAncestors>>
> = ({ signal }) =>
listTraceSpanAncestors({ traceID, spanID }, params, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type ListTraceSpanAncestorsQueryResult = NonNullable<
Awaited<ReturnType<typeof listTraceSpanAncestors>>
>;
export type ListTraceSpanAncestorsQueryError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary List ancestors of a span
*/
export function useListTraceSpanAncestors<
TData = Awaited<ReturnType<typeof listTraceSpanAncestors>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
params?: ListTraceSpanAncestorsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListTraceSpanAncestorsQueryOptions(
{ traceID, spanID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary List ancestors of a span
*/
export const invalidateListTraceSpanAncestors = async (
queryClient: QueryClient,
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
params?: ListTraceSpanAncestorsParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getListTraceSpanAncestorsQueryKey({ traceID, spanID }, params) },
options,
);
return queryClient;
};
/**
* Returns a page of the direct children of a span, one level below it and nothing deeper, in start order. It takes the same parameters as the span list. The list is empty for a span without children.
* @summary List children of a span
*/
export const listTraceSpanChildren = (
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
params?: ListTraceSpanChildrenParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListTraceSpanChildren200>({
url: `/api/v1/traces/${traceID}/spans/${spanID}/children`,
method: 'GET',
params,
signal,
});
};
export const getListTraceSpanChildrenQueryKey = (
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
params?: ListTraceSpanChildrenParams,
) => {
return [
`/api/v1/traces/${traceID}/spans/${spanID}/children`,
...(params ? [params] : []),
] as const;
};
export const getListTraceSpanChildrenQueryOptions = <
TData = Awaited<ReturnType<typeof listTraceSpanChildren>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
params?: ListTraceSpanChildrenParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanChildren>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ??
getListTraceSpanChildrenQueryKey({ traceID, spanID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof listTraceSpanChildren>>
> = ({ signal }) => listTraceSpanChildren({ traceID, spanID }, params, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanChildren>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type ListTraceSpanChildrenQueryResult = NonNullable<
Awaited<ReturnType<typeof listTraceSpanChildren>>
>;
export type ListTraceSpanChildrenQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary List children of a span
*/
export function useListTraceSpanChildren<
TData = Awaited<ReturnType<typeof listTraceSpanChildren>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
params?: ListTraceSpanChildrenParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanChildren>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListTraceSpanChildrenQueryOptions(
{ traceID, spanID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary List children of a span
*/
export const invalidateListTraceSpanChildren = async (
queryClient: QueryClient,
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
params?: ListTraceSpanChildrenParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getListTraceSpanChildrenQueryKey({ traceID, spanID }, params) },
options,
);
return queryClient;
};
/**
* Returns a page of the spans below a span, at any depth, in tree order. It takes the same parameters as the span list, so view=error_origins returns the errors that started below the span.
* @summary List descendants of a span
*/
export const listTraceSpanDescendants = (
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
params?: ListTraceSpanDescendantsParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListTraceSpanDescendants200>({
url: `/api/v1/traces/${traceID}/spans/${spanID}/descendants`,
method: 'GET',
params,
signal,
});
};
export const getListTraceSpanDescendantsQueryKey = (
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
params?: ListTraceSpanDescendantsParams,
) => {
return [
`/api/v1/traces/${traceID}/spans/${spanID}/descendants`,
...(params ? [params] : []),
] as const;
};
export const getListTraceSpanDescendantsQueryOptions = <
TData = Awaited<ReturnType<typeof listTraceSpanDescendants>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
params?: ListTraceSpanDescendantsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ??
getListTraceSpanDescendantsQueryKey({ traceID, spanID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof listTraceSpanDescendants>>
> = ({ signal }) =>
listTraceSpanDescendants({ traceID, spanID }, params, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type ListTraceSpanDescendantsQueryResult = NonNullable<
Awaited<ReturnType<typeof listTraceSpanDescendants>>
>;
export type ListTraceSpanDescendantsQueryError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary List descendants of a span
*/
export function useListTraceSpanDescendants<
TData = Awaited<ReturnType<typeof listTraceSpanDescendants>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
params?: ListTraceSpanDescendantsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListTraceSpanDescendantsQueryOptions(
{ traceID, spanID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary List descendants of a span
*/
export const invalidateListTraceSpanDescendants = async (
queryClient: QueryClient,
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
params?: ListTraceSpanDescendantsParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{
queryKey: getListTraceSpanDescendantsQueryKey({ traceID, spanID }, params),
},
options,
);
return queryClient;
};
/**
* Returns the totals of a trace and no spans: its time range, root span, span and error counts, and whether any spans are missing. AI traces also include model and tool call counts, and token and cost totals. For the spans to look at, use the trace highlights.
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace
*/
export const getTraceSummary = (

View File

@@ -8,7 +8,7 @@
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
@@ -34,9 +34,9 @@
--button-height: auto;
--button-padding: var(--spacing-4) var(--spacing-6);
--button-border-radius: var(--radius-3);
--button-font-size: var(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
@@ -64,8 +64,8 @@
// While Noz works, the row names the step it's on.
.live .activitySummary {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
}

View File

@@ -59,7 +59,7 @@
border: none;
background: none;
font: inherit;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -134,8 +134,8 @@
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
--button-variant-ghost-hover-background-color: var(--l3-background);
@@ -180,8 +180,8 @@
height: 44px;
padding: 0 var(--spacing-7);
border-bottom: 1px solid var(--l2-border);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -8,8 +8,8 @@
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: 20px;
letter-spacing: -0.005em;
color: var(--text-vanilla-400);
@@ -73,7 +73,7 @@
// Wide enough to hold the action buttons that replace it.
min-width: 16px;
text-align: right;
font-size: var(--paragraph-small-400-font-size);
font-size: var(--periscope-font-size-small);
line-height: 18px;
color: var(--l3-foreground);
opacity: calc(1 - var(--actions-opacity, 0));
@@ -87,7 +87,7 @@
width: 100%;
border-bottom: 1px solid var(--accent-primary);
--input-padding: 1px 0;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-hover-border-color: transparent;
}

View File

@@ -56,7 +56,7 @@
--button-border-radius: 3px;
--button-justify-content: flex-start;
--button-gap: var(--spacing-4);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l2-background);
--button-variant-outlined-border: 1px solid var(--l1-border);
--button-variant-outlined-color: var(--l2-foreground);
@@ -144,8 +144,8 @@
.groupLabel {
display: block;
padding: 0 0 7px;
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
font-feature-settings:
'tnum' on,

View File

@@ -71,7 +71,7 @@
align-items: flex-start;
background: var(--l2-background);
color: var(--l1-foreground);
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -44,8 +44,8 @@
--button-height: 32px;
--button-padding: 0 var(--spacing-6);
--button-border-radius: var(--radius-round);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-secondary-background-color: var(--l3-background);
--button-secondary-hover-background-color: var(--l3-background-hover);
--button-secondary-solid-foreground: var(--l1-foreground);

View File

@@ -1,42 +1,13 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import {
act,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import {
AUTHZ_CHECK_URL,
authzMockResponse,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
jest.mock('@monaco-editor/react', () => ({
__esModule: true,
default: ({
value,
onChange,
}: {
value: string;
onChange: (next?: string) => void;
}): JSX.Element => (
<textarea
data-testid="monaco-editor"
value={value}
onChange={(e): void => onChange(e.target.value)}
/>
),
}));
const CUSTOM_ROLE_ID = '019c24aa-3333-0001-aaaa-111111111111';
const rolesApiBase = '*/api/v1/roles';
const VIEW_ROLE_URL = `${ROUTES.ROLE_DETAILS.replace(
@@ -437,125 +408,4 @@ describe('EditRolePage', () => {
);
});
});
describe('JSON view opened from the URL', () => {
const roleGrants = roleWithTransactionGroups.data.transactionGroups;
function renderJsonView(client?: QueryClient): ReturnType<typeof render> {
const page = <CreateEditRolePage />;
return render(
client ? (
<QueryClientProvider client={client}>{page}</QueryClientProvider>
) : (
page
),
undefined,
{
initialRoute: `/settings/roles/${CUSTOM_ROLE_ID}/edit?name=Custom%20Role&viewMode=json`,
},
);
}
function readBuffer(editor: HTMLElement): unknown {
return JSON.parse((editor as HTMLTextAreaElement).value);
}
it('shows the role grants when the role loads after the authz check', async () => {
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) =>
res(ctx.delay(300), ctx.status(200), ctx.json(roleWithTransactionGroups)),
),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('shows the role grants when the role loads before the authz check', async () => {
server.use(
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
const payload = await req.json();
return res(
ctx.delay(300),
ctx.status(200),
ctx.json(
authzMockResponse(
payload,
payload.map(() => true),
),
),
);
}),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('saves what was typed in the buffer even when the role refetches afterwards', async () => {
const updatedBodies: unknown[] = [];
let roleReads = 0;
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) => {
roleReads += 1;
return res(
ctx.status(200),
ctx.json(
roleReads === 1
? roleWithTransactionGroups
: {
...roleWithTransactionGroups,
data: {
...roleWithTransactionGroups.data,
transactionGroups: [
{
objectGroup: {
resource: { kind: 'role', type: 'role' },
selectors: ['*'],
},
relation: 'update',
},
],
},
},
),
);
}),
rest.put(`${rolesApiBase}/:id`, async (req, res, ctx) => {
updatedBodies.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
const user = userEvent.setup();
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
renderJsonView(client);
const editor = await screen.findByTestId('monaco-editor');
await user.type(editor, '[[]', {
initialSelectionStart: 0,
initialSelectionEnd: (editor as HTMLTextAreaElement).value.length,
});
await act(async () => {
await client.invalidateQueries();
});
await waitFor(() => {
expect(roleReads).toBeGreaterThan(1);
});
await user.click(screen.getByTestId('save-button'));
await waitFor(() => {
expect(updatedBodies).toHaveLength(1);
});
expect(updatedBodies[0]).toMatchObject({ transactionGroups: [] });
});
});
});

View File

@@ -86,9 +86,6 @@ export function useCreateEditRolePageActions(
const { mutateAsync: updateRole, isLoading: isUpdating } =
useUpdateRolePermissions();
const isSaving = isCreating || isUpdating;
// Editors read their initial value once, so stay loading until the fetched
// role has been copied into local state.
const isSeedingFromRole = !!rolePermissionsData && !isInitialized;
useEffect(() => {
if (rolePermissionsData && !isInitialized) {
@@ -232,7 +229,7 @@ export function useCreateEditRolePageActions(
setEditorMode: handleModeChange,
resources: localResources,
setResources: handleResourcesChange,
isLoading: isLoadingPermissions || isSeedingFromRole,
isLoading: isLoadingPermissions,
isSaving,
hasUnsavedChanges,
handleSave,

View File

@@ -29,7 +29,7 @@
align-items: center;
justify-content: space-between;
gap: var(--spacing-6);
font-size: var(--label-base-500-font-size);
font-size: var(--font-size-sm);
font-weight: 500;
}
@@ -37,7 +37,7 @@
.subtitle {
padding-left: calc(12px + var(--spacing-3));
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -58,7 +58,7 @@
.code {
flex-shrink: 0;
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -100,7 +100,7 @@
align-items: center;
gap: var(--spacing-2);
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
letter-spacing: -0.01em;
font-variant-numeric: tabular-nums;
}

View File

@@ -36,7 +36,7 @@
.sizerValue {
font-size: 12px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}

View File

@@ -46,7 +46,7 @@
}
.tooltipName {
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
word-break: break-word;
}

View File

@@ -37,7 +37,7 @@
.value {
font-size: 12px;
line-height: 16px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
color: var(--l1-foreground);
text-align: right;
white-space: nowrap;

View File

@@ -190,8 +190,6 @@ describe('TraceDetailsHeader – trace metadata row', () => {
totalSpansCount: 42,
totalErrorSpansCount: 0,
ai: {
modelCallCount: 2,
toolCallCount: 1,
tokens: {
input: 12040,
output: 3110,
@@ -406,8 +404,6 @@ describe('TraceDetailsHeader – tabs', () => {
data: {
...SUMMARY,
ai: {
modelCallCount: 1,
toolCallCount: 0,
tokens: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
},
},

View File

@@ -27,8 +27,6 @@ const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
'trace-ai': {
...BASE_SUMMARY,
ai: {
modelCallCount: 2,
toolCallCount: 1,
tokens: {
input: 1_200,
output: 300,
@@ -44,8 +42,6 @@ const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
endTimestampMillis: 1_500,
totalSpansCount: 4,
ai: {
modelCallCount: 1,
toolCallCount: 0,
tokens: { input: 80, output: 20, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
totalCost: 0.0004,
},

View File

@@ -504,12 +504,7 @@ const traceAiSummary = (
const sum = (key: string): number =>
aiSpans.reduce((total, span) => total + numberAttribute(span, key), 0);
const countWith = (key: string): number =>
aiSpans.filter(({ template }) => key in template.attributes).length;
return {
modelCallCount: countWith('gen_ai.request.model'),
toolCallCount: countWith('gen_ai.tool.name'),
tokens: {
input: sum('gen_ai.usage.input_tokens'),
output: sum('gen_ai.usage.output_tokens'),

View File

@@ -188,6 +188,15 @@ export default defineConfig(({ mode }): UserConfig => {
sourcemap: true,
outDir: 'build',
cssMinify: 'esbuild',
// The Go server caches /assets/ as immutable, so every file there must carry a content hash.
assetsDir: 'assets',
rolldownOptions: {
output: {
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
},
},
},
server: {
open: true,

View File

@@ -16,7 +16,7 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
ID: "GetTraceSummary",
Tags: []string{"tracedetail"},
Summary: "Get summary for a trace",
Description: "Returns the totals of a trace and no spans: its time range, root span, span and error counts, and whether any spans are missing. AI traces also include model and tool call counts, and token and cost totals. For the spans to look at, use the trace highlights.",
Description: "Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.",
Response: new(spantypes.GettableTraceSummary),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
@@ -102,118 +102,5 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/highlights", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetTraceHighlights),
handler.OpenAPIDef{
ID: "GetTraceHighlights",
Tags: []string{"tracedetail"},
Summary: "Get highlights of a trace",
Description: "Returns the spans to look at, for a trace of any size: per-service totals and the first spans of each view of the span list. views names the lists to return; without it all of them are returned. Read more of a list from the span list with the view of the same name. The totals of the trace come from the trace summary.",
RequestQuery: new(spantypes.GetTraceHighlightsParams),
Response: new(spantypes.TraceHighlights),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/spans", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.ListTraceSpans),
handler.OpenAPIDef{
ID: "ListTraceSpans",
Tags: []string{"tracedetail"},
Summary: "List spans of a trace",
Description: "Returns a page of the spans of a trace, in tree order from the top: a span is followed by the spans below it. view keeps only the spans of one kind, query narrows them, and selectFields names the attributes to fill. Values are returned whole.",
RequestQuery: new(spantypes.ListTraceSpansParams),
Response: new(spantypes.SpanList),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetTraceSpan),
handler.OpenAPIDef{
ID: "GetTraceSpan",
Tags: []string{"tracedetail"},
Summary: "Get span of a trace",
Description: "Returns one span with every attribute, resource attribute and event. Values are returned whole. It returns only the stored span: its tree stats come with it in any span list, and the spans around it come from the children, descendants and ancestors routes.",
Response: new(spantypes.Span),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/children", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.ListTraceSpanChildren),
handler.OpenAPIDef{
ID: "ListTraceSpanChildren",
Tags: []string{"tracedetail"},
Summary: "List children of a span",
Description: "Returns a page of the direct children of a span, one level below it and nothing deeper, in start order. It takes the same parameters as the span list. The list is empty for a span without children.",
RequestQuery: new(spantypes.ListTraceSpansParams),
Response: new(spantypes.SpanList),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/descendants", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.ListTraceSpanDescendants),
handler.OpenAPIDef{
ID: "ListTraceSpanDescendants",
Tags: []string{"tracedetail"},
Summary: "List descendants of a span",
Description: "Returns a page of the spans below a span, at any depth, in tree order. It takes the same parameters as the span list, so view=error_origins returns the errors that started below the span.",
RequestQuery: new(spantypes.ListTraceSpansParams),
Response: new(spantypes.SpanList),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/ancestors", handler.New(
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.ListTraceSpanAncestors),
handler.OpenAPIDef{
ID: "ListTraceSpanAncestors",
Tags: []string{"tracedetail"},
Summary: "List ancestors of a span",
Description: "Returns a page of the spans above a span: the chain of parents from the span up to its root, the parent first, and nothing from other branches. The span itself is not included. It takes the same parameters as the span list. The list is empty for a root, and stops where a parent was never received.",
RequestQuery: new(spantypes.ListTraceSpansParams),
Response: new(spantypes.SpanList),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
Stability: handler.StabilityDevelopment,
},
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
return nil
}

View File

@@ -71,20 +71,6 @@ type KafkaConfig struct {
// ShutdownTimeout bounds draining buffered events on stop; events still undelivered when it expires are dropped.
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
TLS TLSConfig `mapstructure:"tls"`
}
type TLSConfig struct {
Enabled bool `mapstructure:"enabled"`
// CAFile is the PEM bundle that verifies the server certificate. Empty uses the system roots.
CAFile string `mapstructure:"ca_file"`
// CertFile and KeyFile are the client certificate, presented when the server requires client auth.
CertFile string `mapstructure:"cert_file"`
KeyFile string `mapstructure:"key_file"`
}
// RetryConfig configures exponential backoff for the OTLP HTTP exporter.
@@ -182,10 +168,6 @@ func (c Config) Validate() error {
if c.Kafka.ShutdownTimeout <= 0 {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "auditor::kafka::shutdown_timeout must be greater than 0")
}
if c.Kafka.TLS.Enabled && (c.Kafka.TLS.CertFile == "") != (c.Kafka.TLS.KeyFile == "") {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file must be set together")
}
}
return nil

View File

@@ -3,7 +3,6 @@ package impltracedetail
import (
"net/http"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/http/binding"
"github.com/SigNoz/signoz/pkg/http/render"
"github.com/SigNoz/signoz/pkg/modules/tracedetail"
@@ -128,46 +127,3 @@ func (h *handler) GetThread(rw http.ResponseWriter, r *http.Request) {
render.Success(rw, http.StatusOK, result)
}
func (h *handler) GetTraceHighlights(rw http.ResponseWriter, r *http.Request) {
params := new(spantypes.GetTraceHighlightsParams)
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
render.Error(rw, err)
return
}
query, err := spantypes.NewTraceHighlightsQuery(params)
if err != nil {
render.Error(rw, err)
return
}
result, err := h.module.GetTraceHighlights(r.Context(), mux.Vars(r)["traceID"], query)
if err != nil {
render.Error(rw, err)
return
}
render.Success(rw, http.StatusOK, result)
}
// These routes are registered for their place in the API spec; the implementation follows.
func (h *handler) ListTraceSpans(rw http.ResponseWriter, _ *http.Request) {
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span list is not implemented yet"))
}
func (h *handler) GetTraceSpan(rw http.ResponseWriter, _ *http.Request) {
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span is not implemented yet"))
}
func (h *handler) ListTraceSpanChildren(rw http.ResponseWriter, _ *http.Request) {
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span children is not implemented yet"))
}
func (h *handler) ListTraceSpanDescendants(rw http.ResponseWriter, _ *http.Request) {
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span descendants is not implemented yet"))
}
func (h *handler) ListTraceSpanAncestors(rw http.ResponseWriter, _ *http.Request) {
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span ancestors is not implemented yet"))
}

View File

@@ -292,21 +292,3 @@ func (m *module) getWindowedFlamegraph(ctx context.Context, traceID, selectedSpa
enrichedSpans := flamegraphTrace.EnrichSelectedSpans(selectedSpans, fullSpans, selectFields)
return spantypes.NewGettableFlamegraphTrace(enrichedSpans, start, end, true), nil
}
func (m *module) GetTraceHighlights(ctx context.Context, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error) {
bounds, err := m.store.GetTraceBounds(ctx, traceID)
if err != nil {
return nil, err
}
skeleton, err := m.store.GetTraceSkeleton(ctx, traceID, bounds)
if err != nil {
return nil, err
}
pages := spantypes.NewHighlightPages(skeleton, query)
rows, err := m.store.GetTraceSpanHeadersByIDs(ctx, traceID, bounds, pages.SpanIDs())
if err != nil {
return nil, err
}
return spantypes.NewTraceHighlights(pages, rows), nil
}

View File

@@ -24,21 +24,6 @@ import (
const colServiceName = `resource_string_service$$$$name` // $ gets escaped so $$$$ converts to $$.
// The collector marks an exception event with isError when it writes the span.
const colHasExceptionEvent = `(NOT has_error AND arrayExists(e -> position(e, '"isError":true') > 0, events)) AS has_exception_event`
// The collector writes a span link as a FOLLOWS_FROM reference; the parent is a CHILD_OF one.
const colHasLink = `(position(links, '"refType":"FOLLOWS_FROM"') > 0) AS has_link`
var genAIUsageValues = []struct{ key, alias string }{
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
}
// storableSpanColumns are the columns a waterfall span scans. A row's legacy maps are blanked when its
// JSON holds the attributes.
var storableSpanColumns = []string{
@@ -162,8 +147,6 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
"argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point",
"argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code",
"countIf(is_gen_ai) AS gen_ai_span_count",
"countIf(is_model_call) AS model_call_count",
"countIf(is_tool_call) AS tool_call_count",
"toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens",
"toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens",
"toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens",
@@ -177,7 +160,7 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
var stats spantypes.TraceStats
err = s.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.ModelCallCount, &stats.ToolCallCount,
&stats.RootServiceName, &stats.RootEntryPoint, &stats.RootSpanStatusCode, &stats.GenAISpanCount,
&stats.Tokens.Input, &stats.Tokens.Output, &stats.Tokens.CacheRead, &stats.Tokens.CacheWrite, &stats.Tokens.Reasoning,
&stats.TotalCost,
)
@@ -189,8 +172,17 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
// genAISpanColumns returns the gen_ai columns aggregated per span, resolved across attribute evolutions.
func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
values := []struct{ key, alias string }{
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
}
names := slices.Clone(aiobservabilitytypes.GenAISpanGateKeys)
for _, value := range genAIUsageValues {
for _, value := range values {
names = append(names, value.key)
}
keys, err := s.genAIFieldKeys(ctx, orgID, names)
@@ -203,17 +195,9 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
if err != nil {
return nil, err
}
isModelCall, err := s.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)
if err != nil {
return nil, err
}
columns := []string{isGenAI + " AS is_gen_ai", isModelCall + " AS is_model_call", isToolCall + " AS is_tool_call"}
columns := []string{isGenAI + " AS is_gen_ai"}
for _, value := range genAIUsageValues {
for _, value := range values {
// 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)
@@ -539,93 +523,3 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
}
return sb.Or(conds...), nil
}
func (s *traceStore) GetTraceSkeleton(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select(
"DISTINCT ON (span_id) span_id", "parent_span_id", "timestamp", "duration_nano", "has_error",
"name", colServiceName, "kind_string", "response_status_code", colHasExceptionEvent, colHasLink,
)
sb.SelectMore(genAIUsageJSONColumns()...)
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
sb.Where(
sb.E("trace_id", traceID),
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
sb.LE("ts_bucket_start", bounds.End.Unix()),
)
sb.OrderByAsc("timestamp")
sb.OrderByAsc("name")
sb.OrderByAsc("span_id")
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := s.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace skeleton")
}
defer rows.Close()
builder := spantypes.NewTraceSkeletonBuilder(traceID, int(bounds.NumSpans))
var span spantypes.SkeletonSpan
// Scanning into one reused list of fields, not ScanStruct, keeps the per-row cost to the strings.
fields := []any{
&span.SpanID, &span.ParentSpanID, &span.StartTime, &span.DurationNano, &span.HasError,
&span.Name, &span.ServiceName, &span.KindString, &span.ResponseStatusCode, &span.HasExceptionEvent, &span.HasLink,
&span.AIUsage.InputTokens, &span.AIUsage.OutputTokens, &span.AIUsage.CacheReadTokens,
&span.AIUsage.CacheWriteTokens, &span.AIUsage.ReasoningTokens, &span.AIUsage.Cost,
}
spanCount := 0
for rows.Next() {
// The builder keeps the usage values of a row, so every row gets its own.
span.AIUsage = spantypes.AISpanUsage{}
if err := rows.Scan(fields...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error scanning trace skeleton")
}
builder.Add(&span)
spanCount++
}
if err := rows.Err(); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error reading trace skeleton")
}
if spanCount == 0 {
return nil, spantypes.ErrTraceNotFound
}
return builder.Build(), nil
}
func (s *traceStore) GetTraceSpanHeadersByIDs(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, spanIDs []string) ([]spantypes.StorableSpan, error) {
if len(spanIDs) == 0 {
return []spantypes.StorableSpan{}, nil
}
ids := make([]any, len(spanIDs))
for i, id := range spanIDs {
ids[i] = id
}
sb := sqlbuilder.NewSelectBuilder()
sb.Select("DISTINCT ON (span_id) span_id", "parent_span_id", "status_code_string", "status_message", "links as references")
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
sb.Where(
sb.E("trace_id", traceID),
sb.In("span_id", ids...),
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
sb.LE("ts_bucket_start", bounds.End.Unix()),
)
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.StorableSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace span headers")
}
return spans, nil
}
// genAIUsageJSONColumns reads the token and cost usage of a span from the JSON attributes column
// only: a span written before that column carries none of it.
func genAIUsageJSONColumns() []string {
columns := make([]string, 0, len(genAIUsageValues))
for _, value := range genAIUsageValues {
path := fmt.Sprintf("%s.%s", tracestelemetryschema.SpanAttributesColumn, clickhousesql.Identifier(value.key))
expr, _ := tracestelemetryschema.AttributeJSONValueExpr(path, telemetrytypes.FieldDataTypeNumber)
columns = append(columns, sqlbuilder.Escape(expr+" AS "+value.alias))
}
return columns
}

View File

@@ -91,17 +91,17 @@ func TestGetTraceStats(t *testing.T) {
}{
{
name: "LegacyMaps",
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, countIf(is_model_call) AS model_call_count, countIf(is_tool_call) AS tool_call_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (mapContains(attributes_string, 'gen_ai.request.model') OR mapContains(attributes_string, 'gen_ai.tool.name') OR mapContains(attributes_string, 'gen_ai.agent.name')) AS is_gen_ai, (mapContains(attributes_string, 'gen_ai.request.model')) AS is_model_call, (mapContains(attributes_string, 'gen_ai.tool.name')) AS is_tool_call, multiIf(mapContains(attributes_number, 'gen_ai.usage.input_tokens'), toFloat64(attributes_number['gen_ai.usage.input_tokens']), NULL) AS input_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.output_tokens'), toFloat64(attributes_number['gen_ai.usage.output_tokens']), NULL) AS output_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_read.input_tokens']), NULL) AS cache_read_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_creation.input_tokens']), NULL) AS cache_write_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), toFloat64(attributes_number['gen_ai.usage.reasoning.output_tokens']), NULL) AS reasoning_tokens_value, multiIf(mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), toFloat64(attributes_number['signoz.gen_ai.usage.tokens.cost']), NULL) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (mapContains(attributes_string, 'gen_ai.request.model') OR mapContains(attributes_string, 'gen_ai.tool.name') OR mapContains(attributes_string, 'gen_ai.agent.name')) AS is_gen_ai, multiIf(mapContains(attributes_number, 'gen_ai.usage.input_tokens'), toFloat64(attributes_number['gen_ai.usage.input_tokens']), NULL) AS input_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.output_tokens'), toFloat64(attributes_number['gen_ai.usage.output_tokens']), NULL) AS output_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_read.input_tokens']), NULL) AS cache_read_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_creation.input_tokens']), NULL) AS cache_write_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), toFloat64(attributes_number['gen_ai.usage.reasoning.output_tokens']), NULL) AS reasoning_tokens_value, multiIf(mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), toFloat64(attributes_number['signoz.gen_ai.usage.tokens.cost']), NULL) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
},
{
name: "JSONEvolutionInsideTrace_ReadsBothColumns",
jsonRelease: &jsonInsideTrace,
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, countIf(is_model_call) AS model_call_count, countIf(is_tool_call) AS tool_call_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (multiIf(attributes.`gen_ai.request.model` IS NOT NULL, attributes.`gen_ai.request.model`::String, mapContains(attributes_string, 'gen_ai.request.model'), attributes_string['gen_ai.request.model'], NULL) IS NOT NULL OR multiIf(attributes.`gen_ai.tool.name` IS NOT NULL, attributes.`gen_ai.tool.name`::String, mapContains(attributes_string, 'gen_ai.tool.name'), attributes_string['gen_ai.tool.name'], NULL) IS NOT NULL OR multiIf(attributes.`gen_ai.agent.name` IS NOT NULL, attributes.`gen_ai.agent.name`::String, mapContains(attributes_string, 'gen_ai.agent.name'), attributes_string['gen_ai.agent.name'], NULL) IS NOT NULL) AS is_gen_ai, (multiIf(attributes.`gen_ai.request.model` IS NOT NULL, attributes.`gen_ai.request.model`::String, mapContains(attributes_string, 'gen_ai.request.model'), attributes_string['gen_ai.request.model'], NULL) IS NOT NULL) AS is_model_call, (multiIf(attributes.`gen_ai.tool.name` IS NOT NULL, attributes.`gen_ai.tool.name`::String, mapContains(attributes_string, 'gen_ai.tool.name'), attributes_string['gen_ai.tool.name'], NULL) IS NOT NULL) AS is_tool_call, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.input_tokens'), attributes_number['gen_ai.usage.input_tokens'], NULL)) AS input_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.output_tokens'), attributes_number['gen_ai.usage.output_tokens'], NULL)) AS output_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), attributes_number['gen_ai.usage.cache_read.input_tokens'], NULL)) AS cache_read_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), attributes_number['gen_ai.usage.cache_creation.input_tokens'], NULL)) AS cache_write_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), attributes_number['gen_ai.usage.reasoning.output_tokens'], NULL)) AS reasoning_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) IS NOT NULL, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String), mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), attributes_number['signoz.gen_ai.usage.tokens.cost'], NULL)) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (multiIf(attributes.`gen_ai.request.model` IS NOT NULL, attributes.`gen_ai.request.model`::String, mapContains(attributes_string, 'gen_ai.request.model'), attributes_string['gen_ai.request.model'], NULL) IS NOT NULL OR multiIf(attributes.`gen_ai.tool.name` IS NOT NULL, attributes.`gen_ai.tool.name`::String, mapContains(attributes_string, 'gen_ai.tool.name'), attributes_string['gen_ai.tool.name'], NULL) IS NOT NULL OR multiIf(attributes.`gen_ai.agent.name` IS NOT NULL, attributes.`gen_ai.agent.name`::String, mapContains(attributes_string, 'gen_ai.agent.name'), attributes_string['gen_ai.agent.name'], NULL) IS NOT NULL) AS is_gen_ai, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.input_tokens'), attributes_number['gen_ai.usage.input_tokens'], NULL)) AS input_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.output_tokens'), attributes_number['gen_ai.usage.output_tokens'], NULL)) AS output_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), attributes_number['gen_ai.usage.cache_read.input_tokens'], NULL)) AS cache_read_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), attributes_number['gen_ai.usage.cache_creation.input_tokens'], NULL)) AS cache_write_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), attributes_number['gen_ai.usage.reasoning.output_tokens'], NULL)) AS reasoning_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) IS NOT NULL, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String), mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), attributes_number['signoz.gen_ai.usage.tokens.cost'], NULL)) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
},
{
name: "JSONEvolutionBeforeTrace_ReadsJSONOnly",
jsonRelease: &jsonBeforeTrace,
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, countIf(is_model_call) AS model_call_count, countIf(is_tool_call) AS tool_call_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (attributes.`gen_ai.request.model` IS NOT NULL OR attributes.`gen_ai.tool.name` IS NOT NULL OR attributes.`gen_ai.agent.name` IS NOT NULL) AS is_gen_ai, (attributes.`gen_ai.request.model` IS NOT NULL) AS is_model_call, (attributes.`gen_ai.tool.name` IS NOT NULL) AS is_tool_call, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
expectedSQL: "SELECT toUInt64(min(span_start_ns)) AS start_ns, toUInt64(max(span_end_ns)) AS end_ns, count() AS total_spans, countIf(has_error) AS total_error_spans, countIf(has_missing_parent) > 0 AS has_missing_spans, argMinIf(root_service, (span_start_ns, root_name), is_root) AS root_service_name, argMinIf(root_name, (span_start_ns, root_name), is_root) AS root_entry_point, argMinIf(root_status_code, (span_start_ns, root_name), is_root) AS root_span_status_code, countIf(is_gen_ai) AS gen_ai_span_count, toUInt64(coalesce(sum(input_tokens_value), 0)) AS input_tokens, toUInt64(coalesce(sum(output_tokens_value), 0)) AS output_tokens, toUInt64(coalesce(sum(cache_read_tokens_value), 0)) AS cache_read_tokens, toUInt64(coalesce(sum(cache_write_tokens_value), 0)) AS cache_write_tokens, toUInt64(coalesce(sum(reasoning_tokens_value), 0)) AS reasoning_tokens, sum(total_cost_value) AS total_cost FROM (SELECT toUnixTimestamp64Nano(timestamp) AS span_start_ns, span_start_ns + duration_nano AS span_end_ns, span_id, has_error, (parent_span_id <> '' AND parent_span_id GLOBAL NOT IN (SELECT span_id FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ?)) AS has_missing_parent, (parent_span_id = '' OR has_missing_parent) AS is_root, if(parent_span_id = '', name, 'Missing Span') AS root_name, if(parent_span_id = '', resource_string_service$$name, '') AS root_service, if(parent_span_id = '', response_status_code, '') AS root_status_code, (attributes.`gen_ai.request.model` IS NOT NULL OR attributes.`gen_ai.tool.name` IS NOT NULL OR attributes.`gen_ai.agent.name` IS NOT NULL) AS is_gen_ai, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? LIMIT 1 BY span_id) AS spans",
},
}
@@ -253,23 +253,3 @@ func TestGetThreadSpans(t *testing.T) {
})
}
}
func TestGetTraceSkeleton(t *testing.T) {
expectedSQL := "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC"
s := newTestStore(sqlmock.QueryMatcherEqual)
s.Mock().ExpectQuery(expectedSQL).WithArgs(testTraceID, testStart.Unix()-1800, testEnd.Unix()).WillReturnRows(cmock.NewRows(nil, nil))
_, _ = s.Store().GetTraceSkeleton(context.Background(), testTraceID, testBounds)
assert.NoError(t, s.Mock().ExpectationsWereMet())
}
func TestGetTraceSpanHeadersByIDs(t *testing.T) {
expectedSQL := "SELECT DISTINCT ON (span_id) span_id, parent_span_id, status_code_string, status_message, links as references FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND span_id IN (?, ?) AND ts_bucket_start >= ? AND ts_bucket_start <= ?"
s := newTestStore(sqlmock.QueryMatcherEqual)
s.Mock().ExpectSelect(expectedSQL).WillReturnRows(cmock.NewRows(nil, nil))
_, _ = s.Store().GetTraceSpanHeadersByIDs(context.Background(), testTraceID, testBounds, []string{"span-a", "span-b"})
assert.NoError(t, s.Mock().ExpectationsWereMet())
}

View File

@@ -16,12 +16,6 @@ type Handler interface {
GetTraceAggregations(http.ResponseWriter, *http.Request)
GetFlamegraph(http.ResponseWriter, *http.Request)
GetThread(http.ResponseWriter, *http.Request)
GetTraceHighlights(http.ResponseWriter, *http.Request)
ListTraceSpans(http.ResponseWriter, *http.Request)
GetTraceSpan(http.ResponseWriter, *http.Request)
ListTraceSpanChildren(http.ResponseWriter, *http.Request)
ListTraceSpanDescendants(http.ResponseWriter, *http.Request)
ListTraceSpanAncestors(http.ResponseWriter, *http.Request)
}
// Module defines the business logic for trace detail operations.
@@ -31,5 +25,4 @@ type Module interface {
GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)
GetFlamegraph(ctx context.Context, traceID string, selectedSpanID string, selectFields []telemetrytypes.TelemetryFieldKey) (*spantypes.GettableFlamegraphTrace, error)
GetThread(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.ThreadQuery) (*spantypes.GettableTraceThread, error)
GetTraceHighlights(ctx context.Context, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error)
}

View File

@@ -30,10 +30,6 @@ func (h *provider) BeforeQuery(ctx context.Context, _ *telemetrystore.QueryEvent
settings["log_comment"] = ctxtypes.CommentFromContext(ctx).String()
// The result model has no Variant type: mismatched types must fail with the
// no-common-type error rather than become a Variant (the 26.8 default).
settings["use_variant_as_common_type"] = 0
if ctx.Value("enforce_max_result_rows") != nil {
settings["max_result_rows"] = h.settings.MaxResultRows
}

View File

@@ -1,98 +0,0 @@
package spantypes
const (
SpanListViewErrorOrigins SpanListView = "error_origins"
SpanListViewUnmarkedFailures SpanListView = "unmarked_failures"
SpanListViewTimeSpent SpanListView = "time_spent"
SpanListViewAIUsage SpanListView = "ai_usage"
SpanListViewLinks SpanListView = "links"
)
const (
UnmarkedFailureHTTP4xx UnmarkedFailureReason = "http_4xx"
UnmarkedFailureHTTP5xx UnmarkedFailureReason = "http_5xx"
UnmarkedFailureGRPCStatus UnmarkedFailureReason = "grpc_status"
UnmarkedFailureExceptionEvent UnmarkedFailureReason = "exception_event"
)
// SpanListView keeps the spans of one kind out of the spans a route covers, in that kind's order.
// It is a plain string so that a list of views binds from a repeated query parameter.
type SpanListView string
func (SpanListView) Enum() []any {
return []any{SpanListViewErrorOrigins, SpanListViewUnmarkedFailures, SpanListViewTimeSpent, SpanListViewAIUsage, SpanListViewLinks}
}
// UnmarkedFailureReason says why a span without the error flag counts as a failure. It is a plain
// string so that omitempty leaves it out: the response encoder does not omit a zero struct.
type UnmarkedFailureReason string
func (UnmarkedFailureReason) Enum() []any {
return []any{UnmarkedFailureHTTP4xx, UnmarkedFailureHTTP5xx, UnmarkedFailureGRPCStatus, UnmarkedFailureExceptionEvent}
}
// ListTraceSpansParams is shared by every route that returns a list of spans: the route decides
// which spans it covers, and these narrow and page them.
type ListTraceSpansParams struct {
View SpanListView `query:"view" description:"A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time."`
Query string `query:"query" description:"Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error."`
SelectFields []string `query:"selectFields" description:"Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings."`
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."`
}
// Span is a stored span. Its keys are the stored field names, so each is also a key a query filter
// accepts. Attributes, Resource and Events hold everything when one span is read, and only the
// selected fields in a list.
type Span struct {
SpanID string `json:"span_id" required:"true"`
TraceID string `json:"trace_id" required:"true"`
ParentSpanID string `json:"parent_span_id" required:"true" description:"ID of the parent span. Empty for a root."`
Name string `json:"name" required:"true"`
KindString string `json:"kind_string" required:"true" description:"Span kind, for example Server, Client or Internal."`
Timestamp uint64 `json:"timestamp" required:"true" description:"Start time, in nanoseconds since the Unix epoch."`
DurationNano uint64 `json:"duration_nano" required:"true" description:"Duration, in nanoseconds."`
HasError bool `json:"has_error" required:"true" description:"Whether the span is marked as an error."`
StatusCodeString string `json:"status_code_string" required:"true" description:"OpenTelemetry status code of the span."`
StatusMessage string `json:"status_message" required:"true" description:"Status message, usually the error text. Empty when the span has none."`
ResponseStatusCode string `json:"response_status_code" required:"true" description:"HTTP or gRPC status code of the response, for example 404. Empty when the span has none."`
Resource map[string]string `json:"resource" required:"true" nullable:"false" description:"Resource attributes. Always includes service.name. A span read by ID has all of them; a span in a list also has the selected ones."`
Attributes map[string]any `json:"attributes" required:"true" nullable:"false" description:"Span attributes. A span read by ID has all of them; a span in a list has only the selected ones."`
Events []Event `json:"events" required:"true" nullable:"false" description:"Span events. A span read by ID has all of them; a span in a list has none."`
References []OtelSpanRef `json:"references" required:"true" nullable:"false" description:"References to other spans: the parent as CHILD_OF, and each span link as FOLLOWS_FROM."`
}
type SameNameSiblingStats struct {
SpanCount uint64 `json:"spanCount" required:"true" description:"Number of spans in the group, this span included."`
OwnTimeNano uint64 `json:"ownTimeNano" required:"true" description:"Total own time of the group, in nanoseconds."`
ErrorSpanCount uint64 `json:"errorSpanCount" required:"true" description:"Number of spans in the group that are marked as errors."`
}
// SpanTreeStats holds what the shape of the trace says about one span. It is computed, never stored.
type SpanTreeStats struct {
Level uint32 `json:"level" required:"true" description:"Depth in the trace: 0 for a root, 1 for its children, and so on."`
ChildCount uint32 `json:"childCount" required:"true" description:"Number of direct children."`
SubtreeSpanCount uint32 `json:"subtreeSpanCount" required:"true" description:"Number of spans below this one, at any depth."`
OwnTimeNano uint64 `json:"ownTimeNano" required:"true" description:"Time spent in the span itself, in nanoseconds: its duration minus the time its children cover."`
ErrorAncestorCount uint32 `json:"errorAncestorCount" required:"true" description:"Number of ancestors in a row, starting at the parent, that are marked as errors. On an error span it shows how far up the error spread."`
SameNameSiblings *SameNameSiblingStats `json:"sameNameSiblings,omitempty" description:"Totals for the spans that share this span's name and parent, this span included. Omitted when no other span does."`
}
type SpanTextMatch struct {
Field string `json:"field" required:"true" description:"Where the word was found: name, status_message, attributes.<name>, resource.<name> or events[<index>]."`
Snippet string `json:"snippet" required:"true" description:"The word with some of the text around it."`
}
// SpanItem is an item of every span list: a span, with what the trace says about it.
type SpanItem struct {
Span Span `json:"span" required:"true"`
TreeStats SpanTreeStats `json:"treeStats" required:"true" description:"Numbers computed from the span's place in the trace."`
UnmarkedFailureReason UnmarkedFailureReason `json:"unmarkedFailureReason,omitempty" description:"Why the span counts as failed although it is not marked as an error. Omitted for every other span."`
Matches []SpanTextMatch `json:"matches,omitempty" nullable:"false" description:"Where the words of the query were found, up to three places. A list does not return all attributes or any events, so this is how to see why a span matched. Omitted when the query has no words."`
}
type SpanList struct {
Total uint64 `json:"total" required:"true" description:"Number of spans that match the request, across all pages."`
Items []SpanItem `json:"items" required:"true" nullable:"false" description:"The spans of this page."`
Warnings []string `json:"warnings,omitempty" nullable:"false" description:"Reasons the result may be incomplete, for example a query key that is not known or a selected field that no returned span has. Omitted when there are none."`
}

View File

@@ -40,10 +40,6 @@ type TraceStore interface {
GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, page ThreadPage) ([]StorableSpan, error)
GetThreadCursor(ctx context.Context, traceID string, bounds *TraceBounds, spanID string) (*ThreadCursor, error)
GetTraceSkeleton(ctx context.Context, traceID string, bounds *TraceBounds) (*TraceSkeleton, error)
// GetTraceSpanHeadersByIDs reads only the parent id, status and references of the spans.
GetTraceSpanHeadersByIDs(ctx context.Context, traceID string, bounds *TraceBounds, spanIDs []string) ([]StorableSpan, 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

@@ -1,111 +0,0 @@
package spantypes
import (
"slices"
)
const highlightsDefaultLimit = 10
type GetTraceHighlightsParams struct {
Views []SpanListView `query:"views" description:"The lists to return, each named by its view. Default: all of them."`
Limit int `query:"limit" description:"Number of spans in each list. Default: 10. Maximum: 1000."`
}
type TraceServiceStats struct {
ServiceName string `json:"serviceName" required:"true"`
SpanCount uint64 `json:"spanCount" required:"true" description:"Number of spans of the service."`
ErrorSpanCount uint64 `json:"errorSpanCount" required:"true" description:"Number of spans of the service that are marked as errors."`
OwnTimeNano uint64 `json:"ownTimeNano" required:"true" description:"Total own time of the service's spans, in nanoseconds."`
}
// TraceHighlights shows where to look in a trace. Each list is the first page of the span list with
// the view it is named after, and is left out when that view was not asked for.
type TraceHighlights struct {
Services []TraceServiceStats `json:"services" required:"true" nullable:"false" description:"Totals for each service of the trace, highest own time first."`
ErrorOrigins *SpanList `json:"errorOrigins,omitempty" description:"The spans where an error started. First page of the error_origins view of the span list."`
UnmarkedFailures *SpanList `json:"unmarkedFailures,omitempty" description:"Spans that failed without being marked as errors. First page of the unmarked_failures view of the span list."`
TimeSpent *SpanList `json:"timeSpent,omitempty" description:"Where the time went, same-name siblings counted as one. First page of the time_spent view of the span list."`
AIUsage *SpanList `json:"aiUsage,omitempty" description:"The spans with the highest gen_ai cost or token usage. First page of the ai_usage view of the span list. Empty for a trace where no span carries that usage."`
Links *SpanList `json:"links,omitempty" description:"Spans that link to other spans. First page of the links view of the span list."`
}
type TraceHighlightsQuery struct {
Views []SpanListView
Limit int
}
// HighlightPages holds the spans picked for each requested list, before their stored data is read.
type HighlightPages struct {
skeleton *TraceSkeleton
pages []*spanPage
}
func NewTraceHighlightsQuery(params *GetTraceHighlightsParams) (*TraceHighlightsQuery, error) {
limit, err := pageLimit("limit", params.Limit, highlightsDefaultLimit)
if err != nil {
return nil, err
}
query := &TraceHighlightsQuery{Limit: limit}
for _, view := range params.Views {
if err := validateSpanListView(view); err != nil {
return nil, err
}
if !slices.Contains(query.Views, view) {
query.Views = append(query.Views, view)
}
}
if len(query.Views) == 0 {
query.Views = spanListViews()
}
return query, nil
}
// NewHighlightPages picks the first page of each requested view from the tree.
func NewHighlightPages(skeleton *TraceSkeleton, query *TraceHighlightsQuery) *HighlightPages {
pages := &HighlightPages{skeleton: skeleton}
for _, view := range query.Views {
pages.pages = append(pages.pages, skeleton.firstPage(view, query.Limit))
}
return pages
}
// SpanIDs lists the picked spans, each once: the spans to read from the store.
func (pages *HighlightPages) SpanIDs() []string {
seen := make(map[int32]struct{})
spanIDs := make([]string, 0)
for _, page := range pages.pages {
for _, i := range page.positions {
if _, ok := seen[i]; !ok {
seen[i] = struct{}{}
spanIDs = append(spanIDs, pages.skeleton.spanID(i))
}
}
}
return spanIDs
}
// NewTraceHighlights builds the highlights. rows holds the stored data of the picked spans; a span
// without a row keeps what the skeleton knows.
func NewTraceHighlights(pages *HighlightPages, rows []StorableSpan) *TraceHighlights {
byID := make(map[string]*StorableSpan, len(rows))
for i := range rows {
byID[rows[i].SpanID] = &rows[i]
}
highlights := &TraceHighlights{Services: pages.skeleton.serviceStats()}
for _, page := range pages.pages {
list := pages.skeleton.newSpanList(page, byID)
switch page.view {
case SpanListViewErrorOrigins:
highlights.ErrorOrigins = &list
case SpanListViewUnmarkedFailures:
highlights.UnmarkedFailures = &list
case SpanListViewTimeSpent:
highlights.TimeSpent = &list
case SpanListViewAIUsage:
highlights.AIUsage = &list
case SpanListViewLinks:
highlights.Links = &list
}
}
return highlights
}

View File

@@ -1,403 +0,0 @@
package spantypes
import (
"cmp"
"slices"
"strconv"
"strings"
"time"
)
const noParent int32 = -1
// SkeletonSpan is one row of the query a TraceSkeleton is built from.
type SkeletonSpan struct {
SpanID string
ParentSpanID string
StartTime time.Time
DurationNano uint64
HasError bool
Name string
ServiceName string
KindString string
ResponseStatusCode string
HasExceptionEvent bool
HasLink bool
// AIUsage is kept when it has a value, pointers included: every row needs its own.
AIUsage AISpanUsage
}
// AISpanUsage is the gen_ai token and cost usage of one span; a nil value is absent on the span.
type AISpanUsage struct {
InputTokens *float64
OutputTokens *float64
CacheReadTokens *float64
CacheWriteTokens *float64
ReasoningTokens *float64
Cost *float64
}
// TraceSkeleton is the tree of a trace. A span is known by its position, its index in start time
// order, and every slice below holds one value per span at that position. It is read-only once built.
type TraceSkeleton struct {
traceID string
// spanIDs holds every span id back to back; span i is spanIDs[idOffsets[i]:idOffsets[i+1]].
spanIDs string
idOffsets []uint32
// parents holds the position of each span's parent, or noParent for a root.
parents []int32
startNano []int64
durationNano []uint64
hasError []bool
hasExceptionEvent []bool
hasLink []bool
// Each distinct string is stored once in stringTable; these hold its index there.
names []uint32
services []uint32
kinds []uint32
statusCodes []uint32
stringTable []string
// aiUsage holds the usage of the spans that carry any, by span position.
aiUsage map[int32]AISpanUsage
// The children of span i are childList[childStart[i]:childStart[i+1]], in start time order.
childStart []int32
childList []int32
roots []int32
// treeOrder lists the spans as a waterfall shows them: a span, then everything below it.
treeOrder []int32
level []uint32
// descendantCount is the number of spans below each span, at any depth.
descendantCount []uint32
ownTime []uint64
// groupOf is the index in groups of the group a span belongs to.
groupOf []int32
groups []siblingGroup
}
// TraceSkeletonBuilder collects the rows of a trace. They must be added in start time order.
type TraceSkeletonBuilder struct {
skeleton *TraceSkeleton
ids []byte
parentIDs []string
stringIndex map[string]uint32
}
func NewTraceSkeletonBuilder(traceID string, sizeHint int) *TraceSkeletonBuilder {
return &TraceSkeletonBuilder{
skeleton: &TraceSkeleton{
traceID: traceID,
idOffsets: make([]uint32, 1, sizeHint+1),
parents: make([]int32, 0, sizeHint),
startNano: make([]int64, 0, sizeHint),
durationNano: make([]uint64, 0, sizeHint),
hasError: make([]bool, 0, sizeHint),
hasExceptionEvent: make([]bool, 0, sizeHint),
hasLink: make([]bool, 0, sizeHint),
names: make([]uint32, 0, sizeHint),
services: make([]uint32, 0, sizeHint),
kinds: make([]uint32, 0, sizeHint),
statusCodes: make([]uint32, 0, sizeHint),
aiUsage: make(map[int32]AISpanUsage),
},
ids: make([]byte, 0, sizeHint*16),
parentIDs: make([]string, 0, sizeHint),
stringIndex: make(map[string]uint32),
}
}
func (builder *TraceSkeletonBuilder) Add(span *SkeletonSpan) {
skeleton := builder.skeleton
if span.AIUsage.hasValue() {
skeleton.aiUsage[int32(len(builder.parentIDs))] = span.AIUsage
}
builder.ids = append(builder.ids, span.SpanID...)
skeleton.idOffsets = append(skeleton.idOffsets, uint32(len(builder.ids)))
builder.parentIDs = append(builder.parentIDs, span.ParentSpanID)
skeleton.startNano = append(skeleton.startNano, span.StartTime.UnixNano())
skeleton.durationNano = append(skeleton.durationNano, span.DurationNano)
skeleton.hasError = append(skeleton.hasError, span.HasError)
skeleton.hasExceptionEvent = append(skeleton.hasExceptionEvent, span.HasExceptionEvent)
skeleton.hasLink = append(skeleton.hasLink, span.HasLink)
skeleton.names = append(skeleton.names, builder.intern(span.Name))
skeleton.services = append(skeleton.services, builder.intern(span.ServiceName))
skeleton.kinds = append(skeleton.kinds, builder.intern(span.KindString))
skeleton.statusCodes = append(skeleton.statusCodes, builder.intern(span.ResponseStatusCode))
}
// Build turns the added rows into the tree. The builder cannot be reused.
func (builder *TraceSkeletonBuilder) Build() *TraceSkeleton {
skeleton := builder.skeleton
skeleton.spanIDs = string(builder.ids)
n := len(builder.parentIDs)
// A span whose parent is not in the trace, or is the span itself, becomes a root.
positions := make(map[string]int32, n)
for i := range n {
positions[skeleton.spanID(int32(i))] = int32(i)
}
for i, parentID := range builder.parentIDs {
parent, ok := positions[parentID]
if !ok || parent == int32(i) {
parent = noParent
}
skeleton.parents = append(skeleton.parents, parent)
}
builder.parentIDs, builder.stringIndex, builder.ids = nil, nil, nil
skeleton.linkChildren()
if skeleton.walkFromRoots() < n {
skeleton.cutParentLoops()
skeleton.linkChildren()
skeleton.walkFromRoots()
}
// Walking the tree order backwards reaches every span after all the spans below it.
skeleton.descendantCount = make([]uint32, n)
for k := n - 1; k >= 0; k-- {
i := skeleton.treeOrder[k]
if parent := skeleton.parents[i]; parent != noParent {
skeleton.descendantCount[parent] += skeleton.descendantCount[i] + 1
}
}
skeleton.ownTime = make([]uint64, n)
for i := range n {
skeleton.ownTime[i] = skeleton.durationNano[i] - skeleton.timeCoveredByChildren(int32(i))
}
skeleton.groupSameNameSiblings()
return skeleton
}
func (skeleton *TraceSkeleton) len() int {
return len(skeleton.parents)
}
func (skeleton *TraceSkeleton) spanID(i int32) string {
return skeleton.spanIDs[skeleton.idOffsets[i]:skeleton.idOffsets[i+1]]
}
func (skeleton *TraceSkeleton) children(i int32) []int32 {
return skeleton.childList[skeleton.childStart[i]:skeleton.childStart[i+1]]
}
// unmarkedFailureReason is set for a span that failed without the error flag. The response status
// column holds an HTTP status or a gRPC status.
func (skeleton *TraceSkeleton) unmarkedFailureReason(i int32) UnmarkedFailureReason {
if skeleton.hasError[i] {
return ""
}
if code, err := strconv.Atoi(skeleton.stringTable[skeleton.statusCodes[i]]); err == nil {
switch {
case code >= 400 && code < 500:
return UnmarkedFailureHTTP4xx
case code >= 500 && code < 600:
return UnmarkedFailureHTTP5xx
case code >= 1 && code <= 16:
return UnmarkedFailureGRPCStatus
}
}
if skeleton.hasExceptionEvent[i] {
return UnmarkedFailureExceptionEvent
}
return ""
}
func (skeleton *TraceSkeleton) treeStats(i int32) SpanTreeStats {
stats := SpanTreeStats{
Level: skeleton.level[i],
ChildCount: uint32(len(skeleton.children(i))),
SubtreeSpanCount: skeleton.descendantCount[i],
OwnTimeNano: skeleton.ownTime[i],
}
for p := skeleton.parents[i]; p != noParent && skeleton.hasError[p]; p = skeleton.parents[p] {
stats.ErrorAncestorCount++
}
if group := skeleton.groups[skeleton.groupOf[i]]; group.spanCount > 1 {
stats.SameNameSiblings = &SameNameSiblingStats{SpanCount: group.spanCount, OwnTimeNano: group.ownTime, ErrorSpanCount: group.errCount}
}
return stats
}
// serviceStats totals the spans of each service, the service with the most own time first.
func (skeleton *TraceSkeleton) serviceStats() []TraceServiceStats {
byService := make(map[uint32]*TraceServiceStats)
for i := range int32(skeleton.len()) {
service, ok := byService[skeleton.services[i]]
if !ok {
service = &TraceServiceStats{ServiceName: skeleton.stringTable[skeleton.services[i]]}
byService[skeleton.services[i]] = service
}
service.SpanCount++
service.OwnTimeNano += skeleton.ownTime[i]
if skeleton.hasError[i] {
service.ErrorSpanCount++
}
}
services := make([]TraceServiceStats, 0, len(byService))
for _, service := range byService {
services = append(services, *service)
}
slices.SortFunc(services, func(a, b TraceServiceStats) int {
return cmp.Or(cmp.Compare(b.OwnTimeNano, a.OwnTimeNano), strings.Compare(a.ServiceName, b.ServiceName))
})
return services
}
// siblingGroup totals the spans that share a name and a parent; a root is a group of its own.
type siblingGroup struct {
// longest is the position of the span with the highest duration in the group.
longest int32
spanCount uint64
ownTime uint64
errCount uint64
}
func (usage AISpanUsage) hasValue() bool {
return usage.InputTokens != nil || usage.OutputTokens != nil || usage.CacheReadTokens != nil ||
usage.CacheWriteTokens != nil || usage.ReasoningTokens != nil || usage.Cost != nil
}
// intern returns the index of value in the string table, adding it on first sight.
func (builder *TraceSkeletonBuilder) intern(value string) uint32 {
if idx, ok := builder.stringIndex[value]; ok {
return idx
}
idx := uint32(len(builder.skeleton.stringTable))
builder.skeleton.stringTable = append(builder.skeleton.stringTable, value)
builder.stringIndex[value] = idx
return idx
}
// linkChildren fills roots, childStart and childList from parents: it counts the children of
// every span, turns the counts into start offsets, then places each child.
func (skeleton *TraceSkeleton) linkChildren() {
n := skeleton.len()
skeleton.childStart = make([]int32, n+1)
skeleton.roots = skeleton.roots[:0]
for i := range n {
if parent := skeleton.parents[i]; parent != noParent {
skeleton.childStart[parent+1]++
} else {
skeleton.roots = append(skeleton.roots, int32(i))
}
}
for i := range n {
skeleton.childStart[i+1] += skeleton.childStart[i]
}
skeleton.childList = make([]int32, skeleton.childStart[n])
next := slices.Clone(skeleton.childStart[:n])
for i := range n {
if parent := skeleton.parents[i]; parent != noParent {
skeleton.childList[next[parent]] = int32(i)
next[parent]++
}
}
}
// walkFromRoots fills treeOrder and level, and returns the number of spans it reached.
func (skeleton *TraceSkeleton) walkFromRoots() int {
n := skeleton.len()
skeleton.treeOrder = make([]int32, 0, n)
skeleton.level = make([]uint32, n)
// Pushed in reverse, the earliest root and the earliest child are popped first.
stack := make([]int32, 0, 64)
for r := len(skeleton.roots) - 1; r >= 0; r-- {
stack = append(stack, skeleton.roots[r])
}
for len(stack) > 0 {
i := stack[len(stack)-1]
stack = stack[:len(stack)-1]
skeleton.treeOrder = append(skeleton.treeOrder, i)
children := skeleton.children(i)
for c := len(children) - 1; c >= 0; c-- {
skeleton.level[children[c]] = skeleton.level[i] + 1
stack = append(stack, children[c])
}
}
return len(skeleton.treeOrder)
}
// cutParentLoops handles spans no root reaches: they sit on a loop of parents (a under b, b under
// a) or below one. The earliest unreached span of each loop becomes a root.
func (skeleton *TraceSkeleton) cutParentLoops() {
reached := make([]bool, skeleton.len())
for _, i := range skeleton.treeOrder {
reached[i] = true
}
for i := range int32(skeleton.len()) {
if reached[i] {
continue
}
skeleton.parents[i] = noParent
stack := []int32{i}
for len(stack) > 0 {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if !reached[top] {
reached[top] = true
stack = append(stack, skeleton.children(top)...)
}
}
}
}
// timeCoveredByChildren is the time of span i during which a child was running. Overlapping
// children count once, and child time outside the span does not count.
func (skeleton *TraceSkeleton) timeCoveredByChildren(i int32) uint64 {
start := skeleton.startNano[i]
end := start + int64(skeleton.durationNano[i])
covered, cursor := int64(0), start
for _, child := range skeleton.children(i) {
childStart := max(skeleton.startNano[child], cursor)
childEnd := min(skeleton.startNano[child]+int64(skeleton.durationNano[child]), end)
if childEnd <= childStart {
continue
}
covered += childEnd - childStart
cursor = childEnd
}
return uint64(covered)
}
// groupSameNameSiblings fills groups and groupOf: one group per name among the children of a span.
func (skeleton *TraceSkeleton) groupSameNameSiblings() {
n := skeleton.len()
skeleton.groupOf = make([]int32, n)
skeleton.groups = make([]siblingGroup, 0, n)
addGroup := func(members []int32) {
group := siblingGroup{longest: members[0]}
for _, i := range members {
skeleton.groupOf[i] = int32(len(skeleton.groups))
group.spanCount++
group.ownTime += skeleton.ownTime[i]
if skeleton.hasError[i] {
group.errCount++
}
if skeleton.durationNano[i] > skeleton.durationNano[group.longest] {
group.longest = i
}
}
skeleton.groups = append(skeleton.groups, group)
}
for r := range skeleton.roots {
addGroup(skeleton.roots[r : r+1])
}
var siblings []int32
for parent := range int32(n) {
// Sorting by name puts same-name siblings side by side; the stable sort keeps their time order.
siblings = append(siblings[:0], skeleton.children(parent)...)
slices.SortStableFunc(siblings, func(a, b int32) int { return int(skeleton.names[a]) - int(skeleton.names[b]) })
for first := 0; first < len(siblings); {
end := first + 1
for end < len(siblings) && skeleton.names[siblings[end]] == skeleton.names[siblings[first]] {
end++
}
addGroup(siblings[first:end])
first = end
}
}
}

View File

@@ -1,291 +0,0 @@
package spantypes
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type skeletonSpec struct {
id, parent, name, service string
startMs, durationMs int64
hasError, hasException bool
hasLink bool
usage *AISpanUsage
statusCode string
}
// buildSkeleton adds the spans in the given order, which stands for the store's start time order.
func buildSkeleton(specs ...skeletonSpec) *TraceSkeleton {
builder := NewTraceSkeletonBuilder("trace", len(specs))
for _, spec := range specs {
span := &SkeletonSpan{
SpanID: spec.id,
ParentSpanID: spec.parent,
StartTime: time.Unix(100, 0).Add(time.Duration(spec.startMs) * time.Millisecond),
DurationNano: uint64(spec.durationMs) * uint64(time.Millisecond),
HasError: spec.hasError,
Name: spec.name,
ServiceName: spec.service,
KindString: "Internal",
ResponseStatusCode: spec.statusCode,
HasExceptionEvent: spec.hasException,
HasLink: spec.hasLink,
}
if spec.usage != nil {
span.AIUsage = *spec.usage
}
builder.Add(span)
}
return builder.Build()
}
func spanIDsOf(skeleton *TraceSkeleton, positions []int32) []string {
spanIDs := make([]string, 0, len(positions))
for _, i := range positions {
spanIDs = append(spanIDs, skeleton.spanID(i))
}
return spanIDs
}
func positionOf(t *testing.T, skeleton *TraceSkeleton, spanID string) int32 {
t.Helper()
for i := range int32(skeleton.len()) {
if skeleton.spanID(i) == spanID {
return i
}
}
require.FailNow(t, "span not in skeleton", spanID)
return noParent
}
func TestTraceSkeletonOwnTime(t *testing.T) {
testCases := []struct {
name string
specs []skeletonSpec
expected int64
}{
{
// time (ms) 0 10 30 50 80 100
// root |-------------------------------------------------| 100 ms
// a |---------| 20 ms
// b |--------------| 30 ms
name: "SequentialChildren_SubtractsEach",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 100},
{id: "a", parent: "root", startMs: 10, durationMs: 20},
{id: "b", parent: "root", startMs: 50, durationMs: 30},
},
expected: 50,
},
{
// Calls fanned out at once, such as parallel queries. Together they cover 10 to 60.
// time (ms) 0 10 20 30 40 50 60 100
// root |-------------------------------------------------| 100 ms
// a |-------------------| 40 ms
// b |-------------------| 40 ms
// c |----| 10 ms
name: "ParallelChildren_CountsOverlapOnce",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 100},
{id: "a", parent: "root", startMs: 10, durationMs: 40},
{id: "b", parent: "root", startMs: 20, durationMs: 40},
{id: "c", parent: "root", startMs: 30, durationMs: 10},
},
expected: 50,
},
{
// Work the parent starts and does not wait for, such as a background job.
// time (ms) 0 80 100
// root |-------------------------------------------------| 100 ms
// a |--------------> 500 ms, 20 of them inside root
name: "ChildOutlivesParent_ClipsToParentEnd",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 100},
{id: "a", parent: "root", startMs: 80, durationMs: 500},
},
expected: 80,
},
{
// Clock skew: the child's host clock runs behind the parent's.
// time (ms) 0 10 30 110
// early |--------------| 30 ms, 20 of them inside root
// root |-------------------------------------------------| 100 ms
name: "ChildStartsBeforeParent_ClipsToParentStart",
specs: []skeletonSpec{
{id: "early", parent: "root", startMs: 0, durationMs: 30},
{id: "root", startMs: 10, durationMs: 100},
},
expected: 80,
},
{
// Clock skew again, with a child that also runs past the parent's end.
// time (ms) 0 10 110
// early |-----------------------------------------------------------> 500 ms
// root |-------------------------------------------------| 100 ms
name: "ChildCoversParent_LeavesZero",
specs: []skeletonSpec{
{id: "early", parent: "root", startMs: 0, durationMs: 500},
{id: "root", startMs: 10, durationMs: 100},
},
expected: 0,
},
{
// Only direct children count: a1 is taken from the time of a, not of root.
// time (ms) 0 10 30 90 100
// root |-------------------------------------------------| 100 ms
// a |---------| 20 ms
// a1 |------------------------------------| 75 ms, child of a
name: "Grandchild_NotSubtracted",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 100},
{id: "a", parent: "root", startMs: 10, durationMs: 20},
{id: "a1", parent: "a", startMs: 15, durationMs: 75},
},
expected: 80,
},
{
name: "NoChildren_EqualsDuration",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 70},
},
expected: 70,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
skeleton := buildSkeleton(testCase.specs...)
assert.Equal(t, uint64(testCase.expected)*uint64(time.Millisecond), skeleton.ownTime[positionOf(t, skeleton, "root")])
})
}
}
func TestTraceSkeletonTree(t *testing.T) {
// root 0 to 100
// a 10 to 40
// a1 15 to 20, error
// b 50 to 60
// orphan 60 to 70; its parent is not in the trace, so it is a second root
skeleton := buildSkeleton(
skeletonSpec{id: "root", name: "GET /", service: "web", startMs: 0, durationMs: 100},
skeletonSpec{id: "a", parent: "root", name: "a", service: "web", startMs: 10, durationMs: 30},
skeletonSpec{id: "a1", parent: "a", name: "a1", service: "db", startMs: 15, durationMs: 5, hasError: true},
skeletonSpec{id: "b", parent: "root", name: "b", service: "web", startMs: 50, durationMs: 10},
skeletonSpec{id: "orphan", parent: "gone", name: "orphan", service: "worker", startMs: 60, durationMs: 10},
)
assert.Equal(t, []string{"root", "a", "a1", "b", "orphan"}, spanIDsOf(skeleton, skeleton.treeOrder))
assert.Equal(t, []string{"root", "orphan"}, spanIDsOf(skeleton, skeleton.roots))
// root: two children, three spans below it, and 100 less the 30 of a and the 10 of b.
assert.Equal(t, SpanTreeStats{Level: 0, ChildCount: 2, SubtreeSpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "root")))
assert.Equal(t, SpanTreeStats{Level: 2, OwnTimeNano: uint64(5 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "a1")))
assert.Equal(t, SpanTreeStats{Level: 0, OwnTimeNano: uint64(10 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "orphan")))
}
func TestTraceSkeletonTreeStats(t *testing.T) {
// root error
// handler error
// q1 SELECT, 10 ms
// q2 SELECT, 30 ms, error
// cache
// evict error
// q3 SELECT, 20 ms
skeleton := buildSkeleton(
skeletonSpec{id: "root", name: "GET /", startMs: 0, durationMs: 100, hasError: true},
skeletonSpec{id: "handler", parent: "root", name: "handler", startMs: 0, durationMs: 90, hasError: true},
skeletonSpec{id: "q1", parent: "handler", name: "SELECT", startMs: 0, durationMs: 10},
skeletonSpec{id: "q2", parent: "handler", name: "SELECT", startMs: 10, durationMs: 30, hasError: true},
skeletonSpec{id: "cache", parent: "handler", name: "GET cache", startMs: 40, durationMs: 5},
skeletonSpec{id: "evict", parent: "cache", name: "evict", startMs: 41, durationMs: 2, hasError: true},
skeletonSpec{id: "q3", parent: "handler", name: "SELECT", startMs: 50, durationMs: 20},
)
// q2 has two error spans above it, and shares its name with q1 and q3.
stats := skeleton.treeStats(positionOf(t, skeleton, "q2"))
assert.Equal(t, uint32(2), stats.ErrorAncestorCount)
require.NotNil(t, stats.SameNameSiblings)
assert.Equal(t, SameNameSiblingStats{SpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond), ErrorSpanCount: 1}, *stats.SameNameSiblings)
cache := skeleton.treeStats(positionOf(t, skeleton, "cache"))
assert.Nil(t, cache.SameNameSiblings)
assert.Equal(t, uint32(2), cache.ErrorAncestorCount)
// The count stops at the first ancestor that is not an error: cache, the parent of evict.
assert.Equal(t, uint32(0), skeleton.treeStats(positionOf(t, skeleton, "evict")).ErrorAncestorCount)
}
func TestTraceSkeletonUnmarkedFailureReason(t *testing.T) {
testCases := []struct {
name string
spec skeletonSpec
expected UnmarkedFailureReason
}{
{name: "HTTP400_LowestClientError", spec: skeletonSpec{statusCode: "400"}, expected: UnmarkedFailureHTTP4xx},
{name: "HTTP499_HighestClientError", spec: skeletonSpec{statusCode: "499"}, expected: UnmarkedFailureHTTP4xx},
{name: "HTTP200_NotAFailure", spec: skeletonSpec{statusCode: "200"}},
// Instrumentation should flag a 5xx as an error; proxies and hand-written spans often do not.
{name: "HTTP500_LowestServerError", spec: skeletonSpec{statusCode: "500"}, expected: UnmarkedFailureHTTP5xx},
{name: "HTTP599_HighestServerError", spec: skeletonSpec{statusCode: "599"}, expected: UnmarkedFailureHTTP5xx},
{name: "HTTP600_NotAFailure", spec: skeletonSpec{statusCode: "600"}},
{name: "GRPC1_LowestFailure", spec: skeletonSpec{statusCode: "1"}, expected: UnmarkedFailureGRPCStatus},
{name: "GRPC16_HighestFailure", spec: skeletonSpec{statusCode: "16"}, expected: UnmarkedFailureGRPCStatus},
{name: "GRPC0_OK", spec: skeletonSpec{statusCode: "0"}},
{name: "ExceptionEvent_WithoutStatusCode", spec: skeletonSpec{hasException: true}, expected: UnmarkedFailureExceptionEvent},
{name: "ExceptionEvent_WithSuccessStatusCode", spec: skeletonSpec{statusCode: "200", hasException: true}, expected: UnmarkedFailureExceptionEvent},
{name: "StatusCodeAndExceptionEvent_ReportsStatusCode", spec: skeletonSpec{statusCode: "404", hasException: true}, expected: UnmarkedFailureHTTP4xx},
{name: "ErrorFlag_NeverUnmarked", spec: skeletonSpec{statusCode: "404", hasException: true, hasError: true}},
{name: "NoSignal_NotAFailure", spec: skeletonSpec{}},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
testCase.spec.id = "span"
skeleton := buildSkeleton(testCase.spec)
assert.Equal(t, testCase.expected, skeleton.unmarkedFailureReason(0))
})
}
}
// No valid trace has a parent loop; it comes from instrumentation that reuses span ids. Every span
// must still be listed once.
func TestTraceSkeletonParentLoop(t *testing.T) {
testCases := []struct {
name string
specs []skeletonSpec
expectedRoots []string
expectedTreeOrder []string
}{
{
// x is the earliest span of the loop, so it becomes a root; y and under-y stay below it.
name: "TwoSpansPointAtEachOther",
specs: []skeletonSpec{
{id: "root", startMs: 0, durationMs: 10},
{id: "x", parent: "y", startMs: 1, durationMs: 5},
{id: "y", parent: "x", startMs: 2, durationMs: 5},
{id: "under-y", parent: "y", startMs: 3, durationMs: 1},
},
expectedRoots: []string{"root", "x"},
expectedTreeOrder: []string{"root", "x", "y", "under-y"},
},
{
name: "SpanIsItsOwnParent",
specs: []skeletonSpec{
{id: "self", parent: "self", startMs: 0, durationMs: 10},
{id: "child", parent: "self", startMs: 1, durationMs: 5},
},
expectedRoots: []string{"self"},
expectedTreeOrder: []string{"self", "child"},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
skeleton := buildSkeleton(testCase.specs...)
assert.Equal(t, testCase.expectedRoots, spanIDsOf(skeleton, skeleton.roots))
assert.Equal(t, testCase.expectedTreeOrder, spanIDsOf(skeleton, skeleton.treeOrder))
})
}
}

View File

@@ -1,189 +0,0 @@
package spantypes
import (
"cmp"
"maps"
"slices"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
)
const spanListMaxLimit = 1000
var (
ErrCodeTraceSpansInvalidLimit = errors.MustNewCode("trace_spans_invalid_limit")
ErrCodeTraceSpansInvalidView = errors.MustNewCode("trace_spans_invalid_view")
)
// spanPage is one page of a view by span position, before the stored data of its spans is read.
type spanPage struct {
view SpanListView
total uint64
positions []int32
}
// spanListViews lists every view, in the order they are documented.
func spanListViews() []SpanListView {
views := make([]SpanListView, 0)
for _, view := range SpanListView("").Enum() {
views = append(views, view.(SpanListView))
}
return views
}
func validateSpanListView(view SpanListView) error {
if !slices.Contains(spanListViews(), view) {
return errors.NewInvalidInputf(ErrCodeTraceSpansInvalidView, "invalid view %q, expected one of error_origins, unmarked_failures, time_spent, ai_usage, links", string(view))
}
return nil
}
func pageLimit(name string, value, fallback int) (int, error) {
switch {
case value < 0 || value > spanListMaxLimit:
return 0, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidLimit, "%s must be between 1 and %d, got %d", name, spanListMaxLimit, value)
case value == 0:
return fallback, nil
}
return value, nil
}
// firstPage returns the first limit spans of a view, with the size of the whole view as its total.
func (skeleton *TraceSkeleton) firstPage(view SpanListView, limit int) *spanPage {
positions := skeleton.viewPositions(view)
return &spanPage{view: view, total: uint64(len(positions)), positions: positions[:min(limit, len(positions))]}
}
// viewPositions lists the spans of a view in the order of the view.
func (skeleton *TraceSkeleton) viewPositions(view SpanListView) []int32 {
switch view {
case SpanListViewErrorOrigins:
return skeleton.spansWhere(skeleton.errorStartsAt)
case SpanListViewUnmarkedFailures:
return skeleton.spansWhere(func(i int32) bool { return skeleton.unmarkedFailureReason(i) != "" })
case SpanListViewLinks:
return skeleton.spansWhere(func(i int32) bool { return skeleton.hasLink[i] })
case SpanListViewTimeSpent:
return skeleton.timeSpentSpans()
case SpanListViewAIUsage:
return skeleton.aiUsageSpans()
}
return skeleton.treeOrder
}
// errorStartsAt reports whether span i is an error span with no error span among its children.
func (skeleton *TraceSkeleton) errorStartsAt(i int32) bool {
return skeleton.hasError[i] && !slices.ContainsFunc(skeleton.children(i), func(child int32) bool { return skeleton.hasError[child] })
}
// spansWhere lists the spans that match, in start time order.
func (skeleton *TraceSkeleton) spansWhere(match func(i int32) bool) []int32 {
spans := make([]int32, 0)
for i := range int32(skeleton.len()) {
if match(i) {
spans = append(spans, i)
}
}
return spans
}
// timeSpentSpans lists the longest span of each sibling group, the group with the most own time
// first. Equal groups fall back to span order, so that every page cuts the same ranking.
func (skeleton *TraceSkeleton) timeSpentSpans() []int32 {
ranked := slices.Clone(skeleton.groups)
slices.SortFunc(ranked, func(a, b siblingGroup) int {
return cmp.Or(cmp.Compare(b.ownTime, a.ownTime), cmp.Compare(a.longest, b.longest))
})
spans := make([]int32, len(ranked))
for k := range ranked {
spans[k] = ranked[k].longest
}
return spans
}
// aiUsageSpans lists the spans that carry gen_ai usage by cost, or by tokens when no span
// carries a cost; equal spans fall back to span order.
func (skeleton *TraceSkeleton) aiUsageSpans() []int32 {
hasCost := false
for _, usage := range skeleton.aiUsage {
hasCost = hasCost || usage.Cost != nil
}
weight := func(i int32) float64 {
usage := skeleton.aiUsage[i]
if hasCost {
return floatValue(usage.Cost)
}
return floatValue(usage.InputTokens) + floatValue(usage.OutputTokens)
}
spans := slices.Collect(maps.Keys(skeleton.aiUsage))
slices.SortFunc(spans, func(a, b int32) int {
return cmp.Or(cmp.Compare(weight(b), weight(a)), cmp.Compare(a, b))
})
return spans
}
// newSpanList builds the items of a page. rows holds the stored data of its spans by span id.
func (skeleton *TraceSkeleton) newSpanList(page *spanPage, rows map[string]*StorableSpan) SpanList {
list := SpanList{Total: page.total, Items: make([]SpanItem, 0, len(page.positions))}
for _, i := range page.positions {
item := SpanItem{Span: skeleton.span(i, rows[skeleton.spanID(i)]), TreeStats: skeleton.treeStats(i), UnmarkedFailureReason: skeleton.unmarkedFailureReason(i)}
if page.view == SpanListViewAIUsage {
skeleton.setUsageAttributes(&item.Span, i)
}
list.Items = append(list.Items, item)
}
return list
}
// span returns span i with service.name as its only resource attribute. row adds what only the
// store holds: the status, the references, and the parent id of a span whose parent is missing.
func (skeleton *TraceSkeleton) span(i int32, row *StorableSpan) Span {
span := Span{
SpanID: skeleton.spanID(i),
TraceID: skeleton.traceID,
Name: skeleton.stringTable[skeleton.names[i]],
KindString: skeleton.stringTable[skeleton.kinds[i]],
Timestamp: uint64(skeleton.startNano[i]),
DurationNano: skeleton.durationNano[i],
HasError: skeleton.hasError[i],
ResponseStatusCode: skeleton.stringTable[skeleton.statusCodes[i]],
Resource: map[string]string{"service.name": skeleton.stringTable[skeleton.services[i]]},
Attributes: map[string]any{},
Events: []Event{},
References: []OtelSpanRef{},
}
if parent := skeleton.parents[i]; parent != noParent {
span.ParentSpanID = skeleton.spanID(parent)
}
if row != nil {
span.ParentSpanID = row.ParentSpanID
span.StatusCodeString = row.StatusCodeString
span.StatusMessage = row.StatusMessage
span.References = append(span.References, row.UnmarshalledRefs()...)
}
return span
}
func (skeleton *TraceSkeleton) setUsageAttributes(span *Span, i int32) {
usage := skeleton.aiUsage[i]
for key, value := range map[string]*float64{
aiobservabilitytypes.GenAIUsageInputTokens: usage.InputTokens,
aiobservabilitytypes.GenAIUsageOutputTokens: usage.OutputTokens,
aiobservabilitytypes.GenAIUsageCacheReadInputTokens: usage.CacheReadTokens,
aiobservabilitytypes.GenAIUsageCacheCreationInputTokens: usage.CacheWriteTokens,
aiobservabilitytypes.GenAIUsageReasoningOutputTokens: usage.ReasoningTokens,
aiobservabilitytypes.SignozGenAITotalCost: usage.Cost,
} {
if value != nil {
span.Attributes[key] = *value
}
}
}
func floatValue(value *float64) float64 {
if value == nil {
return 0
}
return *value
}

View File

@@ -1,78 +0,0 @@
package spantypes
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// checkoutSkeleton is one request with a failing payment call, a group of same-name queries and
// an orphan. usage sets the gen_ai usage of the named spans.
func checkoutSkeleton(usage map[string]*AISpanUsage) *TraceSkeleton {
return buildSkeleton(
skeletonSpec{id: "root", name: "POST /checkout", service: "web", startMs: 0, durationMs: 100, hasError: true},
skeletonSpec{id: "pay", parent: "root", name: "charge", service: "payment", startMs: 0, durationMs: 40, hasError: true, hasLink: true},
skeletonSpec{id: "grpc", parent: "pay", name: "Charge", service: "payment", startMs: 5, durationMs: 5, statusCode: "14", usage: usage["grpc"]},
skeletonSpec{id: "caught", parent: "pay", name: "retry", service: "payment", startMs: 10, durationMs: 5, hasException: true},
skeletonSpec{id: "q1", parent: "root", name: "SELECT", service: "db", startMs: 40, durationMs: 10, usage: usage["q1"]},
skeletonSpec{id: "q2", parent: "root", name: "SELECT", service: "db", startMs: 50, durationMs: 25, hasLink: true, usage: usage["q2"]},
skeletonSpec{id: "auth", parent: "root", name: "GET /auth", service: "auth", startMs: 75, durationMs: 5, statusCode: "404", usage: usage["auth"]},
skeletonSpec{id: "orphan", parent: "gone", name: "flush", service: "worker", startMs: 90, durationMs: 60},
)
}
func TestTraceSkeletonFirstPage_Ranking(t *testing.T) {
value := func(v float64) *float64 { return &v }
testCases := []struct {
name string
view SpanListView
usage map[string]*AISpanUsage
expected []string
}{
{
// own time: orphan 60, the two SELECTs 35 together, pay 30, root 20, then the 5s in start order.
name: "TimeSpent_GroupsSameNameSiblings",
view: SpanListViewTimeSpent,
expected: []string{"orphan", "q2", "pay", "root", "grpc", "caught", "auth"},
},
{
// grpc has tokens and no cost, so it ranks last.
name: "AIUsage_ByCost",
view: SpanListViewAIUsage,
usage: map[string]*AISpanUsage{"q1": {Cost: value(0.01)}, "auth": {Cost: value(0.5)}, "grpc": {InputTokens: value(900)}},
expected: []string{"auth", "q1", "grpc"},
},
{
// auth carries no token or cost value, so it is not listed.
name: "AIUsage_ByTokensWhenNoSpanHasACost",
view: SpanListViewAIUsage,
usage: map[string]*AISpanUsage{"q1": {InputTokens: value(10), OutputTokens: value(5)}, "q2": {InputTokens: value(100)}, "auth": {}},
expected: []string{"q2", "q1"},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
skeleton := checkoutSkeleton(testCase.usage)
page := skeleton.firstPage(testCase.view, 50)
assert.Equal(t, testCase.expected, spanIDsOf(skeleton, page.positions))
assert.Equal(t, uint64(len(testCase.expected)), page.total)
})
}
}
func TestNewSpanList_OnlyAIUsageCarriesUsageAttributes(t *testing.T) {
value := func(v float64) *float64 { return &v }
skeleton := checkoutSkeleton(map[string]*AISpanUsage{"q1": {InputTokens: value(120), OutputTokens: value(30), Cost: value(0.02)}})
usage := skeleton.newSpanList(skeleton.firstPage(SpanListViewAIUsage, 50), nil)
require.Len(t, usage.Items, 1)
assert.Equal(t, map[string]any{"gen_ai.usage.input_tokens": 120.0, "gen_ai.usage.output_tokens": 30.0, "signoz.gen_ai.usage.tokens.cost": 0.02}, usage.Items[0].Span.Attributes)
// The same span in any other list carries no attributes.
for _, item := range skeleton.newSpanList(skeleton.firstPage("", 50), nil).Items {
assert.Empty(t, item.Span.Attributes, item.Span.SpanID)
}
}

View File

@@ -11,8 +11,6 @@ type TraceStats struct {
TotalErrorSpans uint64
HasMissingSpans bool
GenAISpanCount uint64
ModelCallCount uint64
ToolCallCount uint64
Tokens TraceAITokens
TotalCost *float64
}
@@ -33,9 +31,7 @@ type GettableTraceSummary struct {
// TraceAISummary is present when any span carries a gen_ai gate key.
type TraceAISummary struct {
ModelCallCount uint64 `json:"modelCallCount" required:"true" description:"Number of model call spans: spans with gen_ai.request.model."`
ToolCallCount uint64 `json:"toolCallCount" required:"true" description:"Number of tool call spans: spans with gen_ai.tool.name."`
Tokens TraceAITokens `json:"tokens" required:"true"`
Tokens TraceAITokens `json:"tokens" required:"true"`
// TotalCost is omitted when no span carries a cost attribute.
TotalCost *float64 `json:"totalCost,omitempty" nullable:"false"`
}
@@ -60,7 +56,7 @@ func NewGettableTraceSummary(stats *TraceStats) *GettableTraceSummary {
HasMissingSpans: stats.HasMissingSpans,
}
if stats.GenAISpanCount > 0 {
summary.AI = &TraceAISummary{ModelCallCount: stats.ModelCallCount, ToolCallCount: stats.ToolCallCount, Tokens: stats.Tokens, TotalCost: stats.TotalCost}
summary.AI = &TraceAISummary{Tokens: stats.Tokens, TotalCost: stats.TotalCost}
}
return summary
}

View File

@@ -6,7 +6,9 @@ import (
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
@@ -16,6 +18,11 @@ import (
"github.com/gorilla/mux"
)
const (
assetsPathPrefix = "/assets/"
immutableCacheControl = "public, max-age=31536000, immutable"
)
type provider struct {
config web.Config
indexContents []byte
@@ -78,10 +85,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Join internally call path.Clean to prevent directory traversal
path := filepath.Join(provider.config.Directory, req.URL.Path)
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
// check whether a file exists or is a directory at the given path
fi, err := os.Stat(path)
fi, err := os.Stat(filePath)
if err != nil {
// if the file doesn't exist, serve index.html
if os.IsNotExist(err) {
@@ -101,6 +108,12 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
return
}
// files under /assets/ are content-hashed, so their URL changes with their content.
// A non-canonical URL can name a file outside /assets/ or get a redirect.
if req.URL.Path == path.Clean(req.URL.Path) && strings.HasPrefix(req.URL.Path, assetsPathPrefix) {
rw.Header().Set("Cache-Control", immutableCacheControl)
}
// otherwise, use http.FileServer to serve the static file
provider.fileHandler.ServeHTTP(rw, req)
}

View File

@@ -6,6 +6,7 @@ import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
@@ -251,3 +252,87 @@ func TestServeStaticFilesUnchanged(t *testing.T) {
assert.Equal(t, string(expected), httpGet(t, base+"/assets/style.css"))
}
func TestServeCacheControl(t *testing.T) {
t.Parallel()
directory := t.TempDir()
files := map[string]string{
"index.html": "<html>index</html>",
"assets/x.js": "console.log('x')",
"assets/nested/y.css": "body{}",
"assets-legacy/z.js": "console.log('z')",
"favicon.ico": "icon",
"css/uPlot.min.css": ".uplot{}",
"locales/en/main.json": "{}",
}
for name, content := range files {
require.NoError(t, os.MkdirAll(filepath.Join(directory, filepath.Dir(name)), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(directory, name), []byte(content), 0o644))
}
testCases := []struct {
name string
basePath string
path string
expectedStatus int
expectedBody string
expectedCC string
}{
{name: "ExistingAsset_Immutable", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public, max-age=31536000, immutable"},
{name: "ExistingNestedAsset_Immutable", path: "/assets/nested/y.css", expectedBody: files["assets/nested/y.css"], expectedCC: "public, max-age=31536000, immutable"},
{name: "MissingAsset_ServesIndex_NoCache", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsDirectory_ServesIndex_NoCache", path: "/assets/nested/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "Root_ServesIndex_NoCache", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "UnknownRoute_ServesIndex_NoCache", path: "/does-not-exist", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetFile_NoCache", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetNestedFile_NoCache", path: "/css/uPlot.min.css", expectedBody: files["css/uPlot.min.css"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "LocaleFile_NoCache", path: "/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsPrefixLookalike_NoCache", path: "/assets-legacy/z.js", expectedBody: files["assets-legacy/z.js"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_ExistingAsset_Immutable", basePath: "/signoz", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public, max-age=31536000, immutable"},
{name: "BasePath_MissingAsset_ServesIndex_NoCache", basePath: "/signoz", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_NonAssetFile_NoCache", basePath: "/signoz", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetTrailingSlash_Redirects_NoCache", path: "/assets/x.js/", expectedStatus: http.StatusMovedPermanently, expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "EncodedDotDotOutOfAssets_NoCache", path: "/assets/%2e%2e/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_Root_ServesIndex_NoCache", basePath: "/signoz", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
routerWeb, err := New(
context.Background(),
factorytest.NewSettings(),
web.Config{Index: "index.html", Directory: directory},
global.Config{ExternalURL: &url.URL{Path: testCase.basePath}},
)
require.NoError(t, err)
router := mux.NewRouter().UseEncodedPath()
require.NoError(t, routerWeb.AddToRouter(router))
var handler http.Handler = router
if testCase.basePath != "" {
handler = http.StripPrefix(testCase.basePath, router)
}
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := client.Get(server.URL + testCase.basePath + testCase.path)
require.NoError(t, err)
defer func() { _ = res.Body.Close() }()
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
expectedStatus := testCase.expectedStatus
if expectedStatus == 0 {
expectedStatus = http.StatusOK
}
assert.Equal(t, expectedStatus, res.StatusCode)
assert.Equal(t, testCase.expectedCC, res.Header.Get("Cache-Control"))
assert.Equal(t, testCase.expectedBody, string(body))
})
}
}

View File

@@ -116,6 +116,6 @@ def pytest_addoption(parser: pytest.Parser):
parser.addoption(
"--signoz-otel-collector-version",
action="store",
default="v0.144.17",
default="v0.144.16-rc.1",
help="signoz-otel-collector version, used to run clickhouse migrations",
)

View File

@@ -184,19 +184,16 @@ class TracesEvent(ABC):
name: str
time_unix_nano: np.uint64
attribute_map: dict[str, str]
is_error: bool
def __init__(
self,
name: str,
timestamp: datetime.datetime,
attribute_map: dict[str, str] = {},
is_error: bool = False,
) -> None:
self.name = name
self.time_unix_nano = np.uint64(int(timestamp.timestamp() * 1e9))
self.attribute_map = attribute_map
self.is_error = is_error
def np_arr(self) -> np.array:
return np.array([self.name, self.time_unix_nano, json.dumps(self.attribute_map)])
@@ -601,15 +598,13 @@ class Traces(ABC):
)
# DB shape per event: {"name", "timeUnixNano", "attributeMap"}. Must match
# what the consume-layer parser in pkg/types/spantypes expects.
# The collector writes isError only when it is set.
self._events_db = [
json.dumps(
{
"name": event.name,
"timeUnixNano": int(event.time_unix_nano),
"attributeMap": dict(event.attribute_map),
}
| ({"isError": True} if event.is_error else {}),
},
separators=(",", ":"),
)
for event in events

View File

@@ -144,13 +144,14 @@ def test_timestamp_counting_aggregations_are_numeric(
assert raw > 0, f"{expression} returned {raw!r}, expected a positive rate"
# KNOWN GAP, pinned deliberately: ClickHouse rejects sum over DateTime64, and rate_*
# KNOWN GAP, pinned deliberately: ClickHouse rejects sum/avg over DateTime64, and rate_*
# additionally divides a time by an interval; both surface as the generic 500. They returned
# a meaningless seconds number before #5824. Flip to BAD_REQUEST once validated up front.
@pytest.mark.parametrize(
"expression",
[
"sum(timestamp)",
"avg(timestamp)",
"rate_sum(timestamp)",
"rate_avg(timestamp)",
"rate_min(timestamp)",

View File

@@ -119,8 +119,6 @@ def test_summary_ai_trace(
assert summary["totalErrorSpansCount"] == 1
assert summary["hasMissingSpans"] is False
assert summary["ai"]["modelCallCount"] == 2
assert summary["ai"]["toolCallCount"] == 1
assert summary["ai"]["tokens"] == {"input": 150, "output": 25, "cacheRead": 7, "cacheWrite": 0, "reasoning": 0}
assert summary["ai"]["totalCost"] == pytest.approx(0.01)
@@ -197,8 +195,6 @@ def test_summary_ai_trace_across_json_rollout(
assert summary["totalSpansCount"] == 3
assert summary["rootServiceEntryPoint"] == "long agent run"
assert summary["rootSpanStatusCode"] == "200"
assert summary["ai"]["modelCallCount"] == 2
assert summary["ai"]["toolCallCount"] == 0
assert summary["ai"]["tokens"] == {"input": 150, "output": 25, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0}
assert summary["ai"]["totalCost"] == pytest.approx(0.03)

View File

@@ -1,197 +0,0 @@
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
import pytest
import requests
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.querier import get_attribute_backend_now
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
SPAN_LISTS = ("errorOrigins", "unmarkedFailures", "timeSpent", "aiUsage", "links")
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
def test_trace_highlights(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_traces: Callable[[list[Traces]], None],
attribute_backend: str,
) -> None:
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
trace_id = TraceIdGenerator.trace_id()
other_trace_id = TraceIdGenerator.trace_id()
names = ("root", "place_order", "charge_card", "inventory_http", "inventory_grpc", "render", "notify", "consume", "model", "tool")
ids = {name: TraceIdGenerator.span_id() for name in names}
gateway, orders, agent = (f"td-highlights-{service}-{attribute_backend}" for service in ("gateway", "orders", "agent"))
start = now - timedelta(seconds=10)
def span(key: str, parent: str, name: str, service: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
return Traces(
timestamp=start + timedelta(milliseconds=offset_ms),
duration=timedelta(milliseconds=duration_ms),
trace_id=trace_id,
span_id=ids[key],
parent_span_id=ids[parent] if parent else "",
name=name,
resources={"service.name": service, "k8s.pod.name": f"{service}-0"},
attribute_write_mode=write_mode,
**kwargs,
)
insert_traces(
[
span("root", "", "POST /checkout", gateway, 0, 1000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.response.status_code": 500}),
# the error is carried up from charge_card through place_order to the root
span("place_order", "root", "place_order", orders, 10, 600, status_code=TracesStatusCode.STATUS_CODE_ERROR),
span("charge_card", "place_order", "charge_card", orders, 20, 300, kind=TracesKind.SPAN_KIND_CLIENT, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="card declined", attributes={"payment.provider": "worldpay"}),
# four failures that do not carry the error flag
span("inventory_http", "place_order", "GET /inventory", orders, 330, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 404}),
span("inventory_grpc", "place_order", "inventory.Check", orders, 380, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"rpc.grpc.status_code": 5}),
span("render", "root", "render_receipt", gateway, 700, 50, events=[TracesEvent("exception", now, {"exception.message": "template missing, fell back"}, is_error=True)]),
span("notify", "root", "POST /notify", gateway, 752, 5, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 503}),
# a link out to another trace
span("consume", "root", "consume order.created", orders, 760, 20, kind=TracesKind.SPAN_KIND_CONSUMER, links=[TracesLink(trace_id=other_trace_id, span_id="aaaaaaaaaaaaaaaa", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)]),
span("model", "root", "chat gpt-4o-mini", agent, 800, 100, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"gen_ai.request.model": "gpt-4o-mini", "gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": 0.01}),
span("tool", "root", "execute_tool", agent, 910, 30, attributes={"gen_ai.tool.name": "get_weather"}),
]
)
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights"), headers=headers, timeout=10)
assert response.status_code == HTTPStatus.OK, response.text
highlights = response.json()["data"]
# own time is the duration minus what the children cover
assert [(service["serviceName"], service["spanCount"], service["errorSpanCount"], service["ownTimeNano"]) for service in highlights["services"]] == [
(orders, 5, 2, 620_000_000),
(gateway, 3, 1, 250_000_000),
(agent, 2, 0, 130_000_000),
]
# one entry for the error, at the span that threw it
errors = highlights["errorOrigins"]
assert errors["total"] == 1
error = errors["items"][0]
assert error["span"] == {
"span_id": ids["charge_card"],
"trace_id": trace_id,
"parent_span_id": ids["place_order"],
"name": "charge_card",
"kind_string": "Client",
"timestamp": int(start.timestamp()) * 1_000_000_000 + 20_000_000,
"duration_nano": 300_000_000,
"has_error": True,
"status_code_string": "STATUS_CODE_ERROR",
"status_message": "card declined",
"response_status_code": "",
"resource": {"service.name": orders},
"attributes": {},
"events": [],
"references": [{"traceId": trace_id, "spanId": ids["place_order"], "refType": "CHILD_OF"}],
}
assert error["treeStats"] == {"level": 2, "childCount": 0, "subtreeSpanCount": 0, "ownTimeNano": 300_000_000, "errorAncestorCount": 2}
assert "unmarkedFailureReason" not in error
assert "matches" not in error
unmarked = highlights["unmarkedFailures"]
assert unmarked["total"] == 4
assert [(item["span"]["span_id"], item["unmarkedFailureReason"]) for item in unmarked["items"]] == [(ids["inventory_http"], "http_4xx"), (ids["inventory_grpc"], "grpc_status"), (ids["render"], "exception_event"), (ids["notify"], "http_5xx")]
assert unmarked["items"][0]["span"]["response_status_code"] == "404"
links = highlights["links"]
assert links["total"] == 1
assert links["items"][0]["span"]["span_id"] == ids["consume"]
assert {"traceId": other_trace_id, "spanId": "aaaaaaaaaaaaaaaa", "refType": "FOLLOWS_FROM"} in links["items"][0]["span"]["references"]
# the aiUsage list reads the usage of its spans from the JSON attributes only; no other list carries attributes
ai_usage = highlights["aiUsage"]
if attribute_backend == "json":
# the tool span carries no token or cost value, so it is not listed
assert ai_usage["total"] == 1
assert ai_usage["items"][0]["span"]["span_id"] == ids["model"]
assert ai_usage["items"][0]["span"]["attributes"] == {"gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": pytest.approx(0.01)}
else:
assert ai_usage == {"total": 0, "items": []}
# every span is its own entry here, most own time first
time_spent = highlights["timeSpent"]
assert time_spent["total"] == 10
assert [item["span"]["span_id"] for item in time_spent["items"][:3]] == [ids["charge_card"], ids["place_order"], ids["root"]]
assert time_spent["items"][0]["treeStats"]["ownTimeNano"] == 300_000_000
assert "sameNameSiblings" not in time_spent["items"][0]["treeStats"]
assert time_spent["items"][1]["treeStats"] == {"level": 1, "childCount": 3, "subtreeSpanCount": 3, "ownTimeNano": 220_000_000, "errorAncestorCount": 1}
# the totals of the trace are not here: they come from the summary route
assert set(highlights) == {"services", *SPAN_LISTS}
for name in SPAN_LISTS:
for item in highlights[name]["items"]:
assert item["span"]["events"] == [], name
assert list(item["span"]["resource"]) == ["service.name"], name
def test_trace_highlights_limits(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_traces: Callable[[list[Traces]], None],
) -> None:
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
trace_id = TraceIdGenerator.trace_id()
root_id = TraceIdGenerator.span_id()
resources = {"service.name": "td-highlights-limits"}
start = now - timedelta(seconds=30)
spans = [Traces(timestamp=start, duration=timedelta(seconds=20), trace_id=trace_id, span_id=root_id, name="POST /import", kind=TracesKind.SPAN_KIND_SERVER, resources=resources)]
for i in range(150):
failed = {"status_code": TracesStatusCode.STATUS_CODE_ERROR, "status_message": f"failure {i:03d}"} if i < 12 else {}
spans.append(Traces(timestamp=start + timedelta(seconds=1, milliseconds=i * 10), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), parent_span_id=root_id, name="write_item", resources=resources, **failed))
insert_traces(spans)
url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights")
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
response = requests.get(url, headers=headers, timeout=10)
assert response.status_code == HTTPStatus.OK, response.text
highlights = response.json()["data"]
# the default: 10 spans of a list, with the total behind it
assert highlights["errorOrigins"]["total"] == 12
assert [item["span"]["status_message"] for item in highlights["errorOrigins"]["items"]] == [f"failure {i:03d}" for i in range(10)]
assert highlights["aiUsage"] == {"total": 0, "items": []}
# the 150 same-name children are one entry of the timeSpent list, shown by one of them
time_spent = highlights["timeSpent"]
assert time_spent["total"] == 2
group = next(item for item in time_spent["items"] if item["span"]["name"] == "write_item")
assert group["treeStats"]["sameNameSiblings"] == {"spanCount": 150, "ownTimeNano": 150 * 5_000_000, "errorSpanCount": 12}
assert group["span"]["parent_span_id"] == root_id
root = next(item for item in time_spent["items"] if item["span"]["span_id"] == root_id)
assert root["treeStats"]["childCount"] == 150
assert root["treeStats"]["subtreeSpanCount"] == 150
sized = requests.get(url, params={"limit": 3}, headers=headers, timeout=10).json()["data"]
assert len(sized["errorOrigins"]["items"]) == 3
assert sized["errorOrigins"]["total"] == 12
# the highest value accepted returns everything
largest = requests.get(url, params={"limit": 1000}, headers=headers, timeout=10)
assert largest.status_code == HTTPStatus.OK, largest.text
assert len(largest.json()["data"]["errorOrigins"]["items"]) == 12
# views names the lists to return; the others are left out
picked = requests.get(url, params={"views": ["error_origins", "time_spent"]}, headers=headers, timeout=10)
assert picked.status_code == HTTPStatus.OK, picked.text
assert set(picked.json()["data"]) == {"services", "errorOrigins", "timeSpent"}
assert picked.json()["data"]["errorOrigins"]["total"] == 12
assert picked.json()["data"]["timeSpent"]["total"] == 2
for params in ({"limit": 1001}, {"limit": -1}, {"views": "fastest"}, {"views": "all"}):
response = requests.get(url, params=params, headers=headers, timeout=10)
assert response.status_code == HTTPStatus.BAD_REQUEST, f"{params}: {response.text}"
unknown = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/highlights"), headers=headers, timeout=10)
assert unknown.status_code == HTTPStatus.NOT_FOUND, unknown.text