mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-02 05:00:41 +00:00
Compare commits
35 Commits
split/4-e2
...
issue_nerv
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
687ce8c5d6 | ||
|
|
a8d30be82e | ||
|
|
e65bbd281f | ||
|
|
19a737ee41 | ||
|
|
c6e9f8d7fa | ||
|
|
0e000f6a00 | ||
|
|
2fe90d84c4 | ||
|
|
a527841297 | ||
|
|
659d3fc204 | ||
|
|
dc57e60a73 | ||
|
|
30f6175903 | ||
|
|
98dee29f1f | ||
|
|
080291be69 | ||
|
|
bcb6e708ab | ||
|
|
af7d1d31fd | ||
|
|
1d0b83cb6d | ||
|
|
ca4f2f5236 | ||
|
|
9777092344 | ||
|
|
de7a4c084c | ||
|
|
eaf4cb9a81 | ||
|
|
0acf668098 | ||
|
|
122a28eecc | ||
|
|
319149f3f9 | ||
|
|
3ad9300dd3 | ||
|
|
de2f960771 | ||
|
|
9e5e145b46 | ||
|
|
e892107960 | ||
|
|
273ec41fb3 | ||
|
|
b81bbea9f1 | ||
|
|
8954823bf9 | ||
|
|
08cca0f59b | ||
|
|
690a2af781 | ||
|
|
82c8c1c43d | ||
|
|
75686f4004 | ||
|
|
2df97d39e2 |
26
.claude/rules/ai-terms.md
Normal file
26
.claude/rules/ai-terms.md
Normal file
@@ -0,0 +1,26 @@
|
||||
---
|
||||
paths:
|
||||
- "pkg/types/aiobservabilitytypes/**"
|
||||
- "pkg/telemetryschema/aitelemetryschema/**"
|
||||
- "pkg/statementbuilder/aistatementbuilder/**"
|
||||
- "pkg/types/llmpricingruletypes/**"
|
||||
- "pkg/modules/llmpricingrule/**"
|
||||
- "pkg/modules/spanmapper/**"
|
||||
- "pkg/modules/tracedetail/**"
|
||||
- "pkg/types/spantypes/**"
|
||||
- "frontend/src/container/LLMObservability/**"
|
||||
- "frontend/src/pages/LLMObservability/**"
|
||||
- "frontend/src/pages/TraceDetailsV3/**"
|
||||
- "tests/integration/tests/querierai/**"
|
||||
- "tests/integration/tests/tracedetail/**"
|
||||
- "tests/e2e/tests/llm-o11y/**"
|
||||
---
|
||||
|
||||
# AI observability glossary
|
||||
|
||||
The names for AI observability concepts, so code and instructions use them without redefining them: in field names, descriptions, column aliases, UI text and tests. They match the AI explorer's per-trace fields, `TraceAggregateFields` in `pkg/telemetryschema/aitelemetryschema/const.go`.
|
||||
|
||||
- **LLM call**: a span with `gen_ai.request.model`. Its count is `llm_call_count`, or `llmCallCount` in a camelCase response.
|
||||
- **Tool call**: a span with `gen_ai.tool.name`. Its count is `tool_call_count`, or `toolCallCount`.
|
||||
- **gen_ai span**: a span with any of `GenAISpanGateKeys`: an LLM call, a tool call or an agent span.
|
||||
- **Review check.** "model call", `modelCall` or `model_call` in a name, a description or UI text is a finding: it is an LLM call.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -89,6 +89,15 @@ func (ah *APIHandler) getFeatureFlags(w http.ResponseWriter, r *http.Request) {
|
||||
Route: "",
|
||||
})
|
||||
|
||||
useNotificationTemplate := ah.Signoz.Flagger.BooleanOrEmpty(ctx, flagger.FeatureUseNotificationTemplate, evalCtx)
|
||||
featureSet = append(featureSet, &licensetypes.Feature{
|
||||
Name: valuer.NewString(flagger.FeatureUseNotificationTemplate.String()),
|
||||
Active: useNotificationTemplate,
|
||||
Usage: 0,
|
||||
UsageLimit: -1,
|
||||
Route: "",
|
||||
})
|
||||
|
||||
ah.Respond(w, featureSet)
|
||||
}
|
||||
|
||||
|
||||
@@ -298,6 +298,8 @@
|
||||
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
|
||||
"signoz/no-builder-ai-query-access": "error",
|
||||
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
|
||||
"signoz/no-monaco-stripped-features": "error",
|
||||
// Bans Monaco features the production build strips, and monaco-editor value imports outside src/lib/monaco/setup.ts (allowlisted in overrides below)
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
{
|
||||
@@ -644,6 +646,13 @@
|
||||
"rules": {
|
||||
"signoz/no-builder-ai-query-access": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
// setup.ts owns the monaco-editor imports that pick the languages and workers
|
||||
"files": ["src/lib/monaco/setup.ts"],
|
||||
"rules": {
|
||||
"signoz/no-monaco-stripped-features": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
132
frontend/plugins/__tests__/no-monaco-stripped-features.test.mjs
Normal file
132
frontend/plugins/__tests__/no-monaco-stripped-features.test.mjs
Normal file
@@ -0,0 +1,132 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const IMPORT = 'Import Monaco from lib/monaco/setup';
|
||||
const STRIPPED = 'which the production build strips';
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-monaco-stripped-features',
|
||||
valid: [
|
||||
{
|
||||
name: 'setup import',
|
||||
code: "import { monaco } from 'lib/monaco/setup';",
|
||||
},
|
||||
{
|
||||
name: 'type-only import',
|
||||
code: "import type { editor } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'inline type specifiers only',
|
||||
code: "import { type editor, type languages } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'type-only re-export',
|
||||
code: "export type { editor } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'inline type re-export specifiers only',
|
||||
code: "export { type editor, type languages } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'react wrapper',
|
||||
code: "import Editor from '@monaco-editor/react';",
|
||||
},
|
||||
{
|
||||
name: 'kept provider',
|
||||
code: "monaco.languages.registerCompletionItemProvider('json', {});",
|
||||
},
|
||||
{
|
||||
name: 'stripped option turned off',
|
||||
code:
|
||||
"const o = { experimentalGpuAcceleration: 'off', minimap: { showMarkSectionHeaders: false } };",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'package entry import',
|
||||
code: "import * as monaco from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT, line: 1, column: 25 }],
|
||||
},
|
||||
{
|
||||
name: 'deep import',
|
||||
code:
|
||||
"import 'monaco-editor/esm/vs/basic-languages/python/python.contribution.js';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'mixed value and type specifiers',
|
||||
code: "import { editor, type languages } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'dynamic import',
|
||||
code: "const m = await import('monaco-editor');",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'require',
|
||||
code: "const m = require('monaco-editor');",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 're-export',
|
||||
code: "export { editor } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'mixed value and type re-export specifiers',
|
||||
code: "export { editor, type languages } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'export all',
|
||||
code: "export * from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider on monaco.languages',
|
||||
code: "monaco.languages.registerInlayHintsProvider('sql', {});",
|
||||
errors: [
|
||||
{
|
||||
message: 'needs the Monaco `inlayHints` contribution',
|
||||
line: 1,
|
||||
column: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider on a destructured languages',
|
||||
code: "languages.registerSignatureHelpProvider('sql', {});",
|
||||
errors: [{ message: '`parameterHints`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider called bare',
|
||||
code: "registerRenameProvider('json', {});",
|
||||
errors: [{ message: '`rename`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider through a string key',
|
||||
code: "monaco.languages['registerRenameProvider']('json', {});",
|
||||
errors: [{ message: '`rename`' }],
|
||||
},
|
||||
{
|
||||
name: 'semantic tokens provider',
|
||||
code: "monaco.languages.registerDocumentSemanticTokensProvider('json', {});",
|
||||
errors: [{ message: '`semanticTokens`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped option turned on',
|
||||
code: "const o = { experimentalGpuAcceleration: 'on' };",
|
||||
errors: [{ message: '`gpu`', line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'stripped option with a variable value',
|
||||
code: 'const o = { minimap: { showRegionSectionHeaders: enabled } };',
|
||||
errors: [{ message: STRIPPED }],
|
||||
},
|
||||
{
|
||||
name: 'quoted option key',
|
||||
code: "const o = { 'showMarkSectionHeaders': true };",
|
||||
errors: [{ message: '`sectionHeaders`' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
147
frontend/plugins/rules/no-monaco-stripped-features.mjs
Normal file
147
frontend/plugins/rules/no-monaco-stripped-features.mjs
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Rule: no-monaco-stripped-features
|
||||
*
|
||||
* The production build drops the Monaco contributions listed in
|
||||
* plugins/rules/shared/monaco-stripped-features.mjs. Dev and Storybook still carry them,
|
||||
* so a provider or option for one of them works there and silently does nothing
|
||||
* in production. This rule reports them, plus value imports of `monaco-editor`
|
||||
* outside src/lib/monaco/setup.ts: the package entry registers every language and
|
||||
* worker.
|
||||
*
|
||||
* src/lib/monaco/setup.ts is allowlisted via overrides in .oxlintrc.json.
|
||||
*/
|
||||
|
||||
import { MONACO_STRIPPED_FEATURES } from './shared/monaco-stripped-features.mjs';
|
||||
|
||||
const featureByProvider = new Map();
|
||||
const featureByOption = new Map();
|
||||
for (const [feature, { providers = [], options = [] }] of Object.entries(
|
||||
MONACO_STRIPPED_FEATURES,
|
||||
)) {
|
||||
providers.forEach((name) => featureByProvider.set(name, feature));
|
||||
options.forEach((name) => featureByOption.set(name, feature));
|
||||
}
|
||||
|
||||
function isMonacoSource(value) {
|
||||
return value === 'monaco-editor' || value.startsWith('monaco-editor/');
|
||||
}
|
||||
|
||||
function isTypeOnlyImport(node) {
|
||||
return (
|
||||
node.importKind === 'type' ||
|
||||
(node.specifiers.length > 0 &&
|
||||
node.specifiers.every((s) => s.importKind === 'type'))
|
||||
);
|
||||
}
|
||||
|
||||
function isTypeOnlyExport(node) {
|
||||
return (
|
||||
node.exportKind === 'type' ||
|
||||
(node.specifiers.length > 0 &&
|
||||
node.specifiers.every((s) => s.exportKind === 'type'))
|
||||
);
|
||||
}
|
||||
|
||||
function propertyName(node) {
|
||||
if (node.type === 'Identifier') {
|
||||
return node.name;
|
||||
}
|
||||
if (node.type === 'Literal' && typeof node.value === 'string') {
|
||||
return node.value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isDisabledValue(node) {
|
||||
return (
|
||||
node.type === 'Literal' && (node.value === false || node.value === 'off')
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description:
|
||||
'Disallow Monaco features the production build strips, and value imports of monaco-editor outside src/lib/monaco/setup.ts',
|
||||
category: 'Monaco',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
provider:
|
||||
'{{name}} needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
|
||||
option:
|
||||
'`{{name}}` needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
|
||||
import:
|
||||
'Import Monaco from lib/monaco/setup, not monaco-editor: the package entry registers every language and worker. Type-only imports are fine.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const reportSource = (source) => {
|
||||
if (
|
||||
source?.type === 'Literal' &&
|
||||
typeof source.value === 'string' &&
|
||||
isMonacoSource(source.value)
|
||||
) {
|
||||
context.report({ node: source, messageId: 'import' });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
if (!isTypeOnlyImport(node)) {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
ImportExpression: (node) => reportSource(node.source),
|
||||
ExportAllDeclaration(node) {
|
||||
if (node.exportKind !== 'type') {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
ExportNamedDeclaration(node) {
|
||||
if (!isTypeOnlyExport(node)) {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
CallExpression(node) {
|
||||
const { callee } = node;
|
||||
if (callee.type === 'Identifier' && callee.name === 'require') {
|
||||
reportSource(node.arguments[0]);
|
||||
return;
|
||||
}
|
||||
const name =
|
||||
callee.type === 'MemberExpression'
|
||||
? propertyName(callee.property)
|
||||
: callee.type === 'Identifier'
|
||||
? callee.name
|
||||
: null;
|
||||
if (name !== null && featureByProvider.has(name)) {
|
||||
context.report({
|
||||
node: callee,
|
||||
messageId: 'provider',
|
||||
data: { name, feature: featureByProvider.get(name) },
|
||||
});
|
||||
}
|
||||
},
|
||||
Property(node) {
|
||||
if (node.computed) {
|
||||
return;
|
||||
}
|
||||
const name = propertyName(node.key);
|
||||
if (
|
||||
name !== null &&
|
||||
featureByOption.has(name) &&
|
||||
!isDisabledValue(node.value)
|
||||
) {
|
||||
context.report({
|
||||
node: node.key,
|
||||
messageId: 'option',
|
||||
data: { name, feature: featureByOption.get(name) },
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
29
frontend/plugins/rules/shared/monaco-stripped-features.mjs
Normal file
29
frontend/plugins/rules/shared/monaco-stripped-features.mjs
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Monaco editor contributions the production build drops (vite.config.ts marks
|
||||
* them side-effect free), with the API that would need them at runtime.
|
||||
* `signoz/no-monaco-stripped-features` reports those APIs, since the build
|
||||
* leaves them without an error and without an effect.
|
||||
*
|
||||
* To use one, delete its entry here.
|
||||
*/
|
||||
export const MONACO_STRIPPED_FEATURES = {
|
||||
codelens: { providers: ['registerCodeLensProvider'] },
|
||||
dropOrPasteInto: {},
|
||||
gpu: { options: ['experimentalGpuAcceleration'] },
|
||||
inlayHints: { providers: ['registerInlayHintsProvider'] },
|
||||
inlineCompletions: { providers: ['registerInlineCompletionsProvider'] },
|
||||
linkedEditing: { providers: ['registerLinkedEditingRangeProvider'] },
|
||||
parameterHints: { providers: ['registerSignatureHelpProvider'] },
|
||||
rename: {
|
||||
providers: ['registerRenameProvider', 'registerNewSymbolNameProvider'],
|
||||
},
|
||||
sectionHeaders: {
|
||||
options: ['showRegionSectionHeaders', 'showMarkSectionHeaders'],
|
||||
},
|
||||
semanticTokens: {
|
||||
providers: [
|
||||
'registerDocumentSemanticTokensProvider',
|
||||
'registerDocumentRangeSemanticTokensProvider',
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -21,6 +21,7 @@ import noTextCss from './rules/no-text-css.mjs';
|
||||
import requireDisableReason from './rules/require-disable-reason.mjs';
|
||||
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
|
||||
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
|
||||
import noMonacoStrippedFeatures from './rules/no-monaco-stripped-features.mjs';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -43,5 +44,6 @@ export default {
|
||||
'require-disable-reason': requireDisableReason,
|
||||
'no-dom-node-access': noDomNodeAccess,
|
||||
'no-builder-ai-query-access': noBuilderAiQueryAccess,
|
||||
'no-monaco-stripped-features': noMonacoStrippedFeatures,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14206,7 +14206,19 @@ export interface SpantypesTraceAITokensDTO {
|
||||
}
|
||||
|
||||
export interface SpantypesTraceAISummaryDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Spans with gen_ai.request.model.
|
||||
*/
|
||||
llmCallCount: number;
|
||||
tokens: SpantypesTraceAITokensDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Spans with gen_ai.tool.name.
|
||||
*/
|
||||
toolCallCount: number;
|
||||
/**
|
||||
* @type number
|
||||
*/
|
||||
@@ -14634,6 +14646,254 @@ export interface SpantypesPostableWaterfallDTO {
|
||||
uncollapsedSpans?: string[] | null;
|
||||
}
|
||||
|
||||
export interface SpantypesSameNameSiblingStatsDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
errorSpanCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description This span included.
|
||||
*/
|
||||
spanCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
export type SpantypesSpanDTOAttributes = { [key: string]: unknown };
|
||||
|
||||
/**
|
||||
* Always has service.name. All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
export type SpantypesSpanDTOResource = { [key: string]: string };
|
||||
|
||||
export interface SpantypesSpanDTO {
|
||||
/**
|
||||
* @type object
|
||||
* @description All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
attributes: SpantypesSpanDTOAttributes;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
duration_nano: number;
|
||||
/**
|
||||
* @type array
|
||||
* @description All of them for a span read by ID; none in a list.
|
||||
*/
|
||||
events: SpantypesEventDTO[];
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
has_error: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description For example Server, Client or Internal.
|
||||
*/
|
||||
kind_string: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Empty for a root.
|
||||
*/
|
||||
parent_span_id: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description The parent as CHILD_OF, and each span link as FOLLOWS_FROM.
|
||||
*/
|
||||
references: SpantypesOtelSpanRefDTO[];
|
||||
/**
|
||||
* @type object
|
||||
* @description Always has service.name. All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
resource: SpantypesSpanDTOResource;
|
||||
/**
|
||||
* @type string
|
||||
* @description HTTP or gRPC status code, for example 404.
|
||||
*/
|
||||
response_status_code: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
span_id: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status_code_string: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Usually the error text.
|
||||
*/
|
||||
status_message: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Start time, in Unix milliseconds.
|
||||
*/
|
||||
time_unix: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
trace_id: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTextMatchDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description name, status_message, attributes.<name>, resource.<name> or events[<index>].
|
||||
*/
|
||||
field: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description About 40 characters on each side of the word.
|
||||
*/
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTreeStatsDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
childCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Ancestors marked as errors in an unbroken run up from the parent: how far an error spread.
|
||||
*/
|
||||
errorAncestorCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description 0 for a root.
|
||||
*/
|
||||
level: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Duration minus the time its children cover.
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @description Totals for the spans with this span's name and parent. Omitted when it has none.
|
||||
*/
|
||||
sameNameSiblings?: SpantypesSameNameSiblingStatsDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Spans below this one, at any depth.
|
||||
*/
|
||||
subtreeSpanCount: number;
|
||||
}
|
||||
|
||||
export enum SpantypesUnmarkedFailureKindDTO {
|
||||
http_4xx = 'http_4xx',
|
||||
http_5xx = 'http_5xx',
|
||||
grpc_status = 'grpc_status',
|
||||
exception_event = 'exception_event',
|
||||
}
|
||||
export interface SpantypesSpanItemDTO {
|
||||
/**
|
||||
* @type array
|
||||
* @description Where the query's words were found, up to three places. Omitted when the query has no words.
|
||||
*/
|
||||
matches?: SpantypesSpanTextMatchDTO[];
|
||||
span: SpantypesSpanDTO;
|
||||
treeStats: SpantypesSpanTreeStatsDTO;
|
||||
/**
|
||||
* @description Why the span is an unmarked failure. Omitted for other spans.
|
||||
*/
|
||||
unmarkedFailureKind?: SpantypesUnmarkedFailureKindDTO;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanListDTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
items: SpantypesSpanItemDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Matching spans across all pages.
|
||||
*/
|
||||
total: number;
|
||||
/**
|
||||
* @type array
|
||||
* @description Why the result may be incomplete, for example an unknown query key or a selected field no returned span has.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
errorSpanCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Sum of the own time of the service's spans.
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
serviceName: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
spanCount: number;
|
||||
}
|
||||
|
||||
export interface SpantypesTraceHighlightsDTO {
|
||||
/**
|
||||
* @description First page of the ai_usage view.
|
||||
*/
|
||||
aiUsage?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description First page of the error_origins view.
|
||||
*/
|
||||
errorOrigins?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description First page of the links view.
|
||||
*/
|
||||
links?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @description Highest own time first.
|
||||
*/
|
||||
services: SpantypesTraceServiceStatsDTO[];
|
||||
/**
|
||||
* @description First page of the time_spent view.
|
||||
*/
|
||||
timeSpent?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description First page of the unmarked_failures view.
|
||||
*/
|
||||
unmarkedFailures?: SpantypesSpanListDTO;
|
||||
}
|
||||
|
||||
export interface SpantypesUpdatableSpanMapperDTO {
|
||||
config?: SpantypesSpanMapperConfigDTO;
|
||||
/**
|
||||
@@ -16099,6 +16359,197 @@ export type GetTraceAggregations200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetTraceHighlightsPathParameters = {
|
||||
traceID: string;
|
||||
};
|
||||
export type GetTraceHighlightsParams = {
|
||||
/**
|
||||
* @type array
|
||||
* @description The lists to return. Default: all.
|
||||
*/
|
||||
views?: SpantypesSpanListViewDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description 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 Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only.
|
||||
*/
|
||||
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 Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only.
|
||||
*/
|
||||
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 Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only.
|
||||
*/
|
||||
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 Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only.
|
||||
*/
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -22,6 +22,11 @@ import type {
|
||||
GetFlamegraphPathParameters,
|
||||
GetTraceAggregations200,
|
||||
GetTraceAggregationsPathParameters,
|
||||
GetTraceHighlights200,
|
||||
GetTraceHighlightsParams,
|
||||
GetTraceHighlightsPathParameters,
|
||||
GetTraceSpan200,
|
||||
GetTraceSpanPathParameters,
|
||||
GetTraceSummary200,
|
||||
GetTraceSummaryPathParameters,
|
||||
GetTraceThread200,
|
||||
@@ -29,6 +34,18 @@ import type {
|
||||
GetTraceThreadPathParameters,
|
||||
GetWaterfallV4200,
|
||||
GetWaterfallV4PathParameters,
|
||||
ListTraceSpanAncestors200,
|
||||
ListTraceSpanAncestorsParams,
|
||||
ListTraceSpanAncestorsPathParameters,
|
||||
ListTraceSpanChildren200,
|
||||
ListTraceSpanChildrenParams,
|
||||
ListTraceSpanChildrenPathParameters,
|
||||
ListTraceSpanDescendants200,
|
||||
ListTraceSpanDescendantsParams,
|
||||
ListTraceSpanDescendantsPathParameters,
|
||||
ListTraceSpans200,
|
||||
ListTraceSpansParams,
|
||||
ListTraceSpansPathParameters,
|
||||
RenderErrorResponseDTO,
|
||||
SpantypesPostableFlamegraphDTO,
|
||||
SpantypesPostableTraceAggregationsDTO,
|
||||
@@ -159,7 +176,710 @@ export const useGetTraceAggregations = <
|
||||
return useMutation(getGetTraceAggregationsMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
* @summary Get summary for a trace
|
||||
*/
|
||||
export const getTraceSummary = (
|
||||
@@ -261,7 +981,7 @@ export const invalidateGetTraceSummary = async (
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.
|
||||
* Returns the gen_ai spans of a trace, LLM calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.
|
||||
* @summary Get thread view for a trace
|
||||
*/
|
||||
export const getTraceThread = (
|
||||
|
||||
@@ -9,4 +9,5 @@ export enum FeatureKeys {
|
||||
ANOMALY_DETECTION = 'anomaly_detection',
|
||||
USE_JSON_BODY = 'use_json_body',
|
||||
ENABLE_METRICS_REDUCTION = 'enable_metrics_reduction',
|
||||
USE_NOTIFICATION_TEMPLATE = 'use_notification_template',
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import { FORMULA, MetricsType, WidgetKeys } from '../constant';
|
||||
import { DatabaseCallProps, DatabaseCallsRPSProps } from '../types';
|
||||
@@ -55,8 +55,8 @@ export const databaseCallsRPS = ({
|
||||
const legends = [legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -113,12 +113,12 @@ export const databaseCallsAvgDuration = ({
|
||||
const legendFormulas = ['Average Duration'];
|
||||
const expressions = [FORMULA.DATABASE_CALLS_AVG_DURATION];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import { FORMULA, MetricsType, WidgetKeys } from '../constant';
|
||||
import {
|
||||
@@ -88,12 +88,12 @@ export const externalCallErrorPercent = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsB];
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const legends = [legend, legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
@@ -149,12 +149,12 @@ export const externalCallDuration = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsA];
|
||||
const legends = [legend, legend];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
@@ -202,8 +202,8 @@ export const externalCallRpsByAddress = ({
|
||||
const legends = [legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -252,12 +252,12 @@ export const externalCallDurationByAddress = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsA];
|
||||
const legends = [legend, legend];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
alphabet,
|
||||
initialFormulaBuilderFormValues,
|
||||
@@ -7,7 +11,6 @@ import {
|
||||
import getStep from 'lib/getStep';
|
||||
import store from 'store';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { SpaceAggregation, TimeAggregation } from 'types/api/v5/queryRange';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
@@ -34,8 +37,8 @@ const getAggregations = ({
|
||||
dataSource: DataSource;
|
||||
key: string;
|
||||
aggregateOperator: string;
|
||||
timeAggregation: MetricAggregateOperator;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
timeAggregation: MetrictypesTimeAggregationDTO;
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}): IBuilderQuery['aggregations'] =>
|
||||
dataSource === DataSource.TRACES
|
||||
@@ -44,8 +47,8 @@ const getAggregations = ({
|
||||
{
|
||||
metricName: key,
|
||||
temporality: '',
|
||||
timeAggregation: timeAggregation as TimeAggregation,
|
||||
spaceAggregation: spaceAggregation as SpaceAggregation,
|
||||
timeAggregation,
|
||||
spaceAggregation,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
...(comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam,
|
||||
@@ -124,7 +127,6 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams = [],
|
||||
stepInterval,
|
||||
dataSource,
|
||||
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
|
||||
queryFormulas: expressions.map((expression, index) => ({
|
||||
@@ -156,7 +158,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
items: additionalItems[index],
|
||||
op: 'AND',
|
||||
},
|
||||
stepInterval: stepInterval ?? null,
|
||||
stepInterval: null,
|
||||
dataSource,
|
||||
})),
|
||||
queryTraceOperator: [],
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
FORMULA,
|
||||
@@ -26,11 +25,11 @@ import {
|
||||
LatencyProps,
|
||||
OperationPerSecProps,
|
||||
} from '../Tabs/types';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
import {
|
||||
getQueryBuilderQueries,
|
||||
getQueryBuilderQuerieswithFormula,
|
||||
} from './MetricsPageQueriesFactory';
|
||||
import { getLatencyAtOrBelowAggregation } from './utils';
|
||||
|
||||
export const latency = ({
|
||||
servicename,
|
||||
@@ -43,7 +42,7 @@ export const latency = ({
|
||||
const newAutoCompleteData: BaseAutocompleteData = {
|
||||
key: isSpanMetricEnable
|
||||
? signozLatencyBucketMetrics
|
||||
: WidgetKeys.SpanDurationNano,
|
||||
: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: isSpanMetricEnable ? '' : MetricsType.Tag,
|
||||
};
|
||||
@@ -83,14 +82,14 @@ export const latency = ({
|
||||
const queryNameAndExpression = QUERYNAME_AND_EXPRESSION;
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
@@ -109,33 +108,17 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold,
|
||||
delta,
|
||||
threshold,
|
||||
metricsBuckets,
|
||||
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
const countAtOrBelow = (
|
||||
ms: number,
|
||||
): {
|
||||
key: string;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
} => {
|
||||
const bucket = getNearestHighestBucketValue(ms, metricsBuckets);
|
||||
return bucket === '+Inf'
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetricAggregateOperator.SUM,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetricAggregateOperator.COUNT,
|
||||
param: { operator: '<=', threshold: Number(bucket) },
|
||||
};
|
||||
};
|
||||
const satisfied = countAtOrBelow(threashold * 1000);
|
||||
const tolerating = countAtOrBelow(threashold * 1000 * 4);
|
||||
const satisfied = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000,
|
||||
metricsBuckets,
|
||||
);
|
||||
const tolerating = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000 * 4,
|
||||
metricsBuckets,
|
||||
);
|
||||
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
@@ -213,63 +196,27 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.StatusCode,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['!='],
|
||||
value: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.OTelServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Operation,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const autocompleteData = [
|
||||
autoCompleteDataA,
|
||||
autoCompleteDataB,
|
||||
autoCompleteDataC,
|
||||
];
|
||||
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemC];
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemB];
|
||||
const legends = [GraphTitle.APDEX];
|
||||
const disabled = Array(3).fill(true);
|
||||
const expressions = delta
|
||||
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
|
||||
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
|
||||
const expressions = [FORMULA.APDEX];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
// v5 forces increase on histograms, so the total matches it
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
];
|
||||
|
||||
// a plain sum keeps the le label on B and C, and the formula then cannot join them
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
satisfied.spaceAggregation,
|
||||
tolerating.spaceAggregation,
|
||||
];
|
||||
@@ -336,8 +283,8 @@ export const operationPerSec = ({
|
||||
const legends = OPERATION_LEGENDS;
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -431,12 +378,12 @@ export const errorPercentage = ({
|
||||
const expressions = [FORMULA.ERROR_PERCENTAGE];
|
||||
const legendFormulas = [GraphTitle.ERROR_PERCENTAGE];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
GraphTitle,
|
||||
@@ -112,20 +112,20 @@ export const topOperationQueries = ({
|
||||
KeyOperationTableHeader.NUM_OF_CALLS,
|
||||
];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const expressions = ['D*100/E'];
|
||||
const legendFormulas = [GraphTitle.ERROR_PERCENTAGE];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { QueryBuilderFormula, QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
@@ -102,8 +102,7 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
threshold: 0.5,
|
||||
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
|
||||
}),
|
||||
);
|
||||
@@ -139,6 +138,11 @@ describe('service details queries on v5', () => {
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
queries
|
||||
.filter((query) => query.type === 'builder_formula')
|
||||
.map((query) => (query.spec as QueryBuilderFormula).expression),
|
||||
).toStrictEqual(['((B + C)/2)/A']);
|
||||
});
|
||||
|
||||
it('reads the count metric when the apdex threshold is past the largest bucket', () => {
|
||||
@@ -147,8 +151,7 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
threshold: 0.5,
|
||||
metricsBuckets: [100, 250, 500, 1000],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { MetrictypesSpaceAggregationDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { WidgetKeys } from '../constant';
|
||||
import { LatencyAtOrBelowAggregation } from '../Tabs/types';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
export const getLatencyAtOrBelowAggregation = (
|
||||
thresholdMs: number,
|
||||
buckets: number[],
|
||||
): LatencyAtOrBelowAggregation => {
|
||||
const bucket = getNearestHighestBucketValue(thresholdMs, buckets);
|
||||
return bucket === undefined
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.count,
|
||||
param: { operator: '<=', threshold: bucket },
|
||||
};
|
||||
};
|
||||
@@ -24,7 +24,6 @@ import { v4 as uuid } from 'uuid';
|
||||
import { ApDexMetricsProps } from './types';
|
||||
|
||||
function ApDexMetrics({
|
||||
delta,
|
||||
metricsBuckets,
|
||||
thresholdValue,
|
||||
onDragSelect,
|
||||
@@ -44,9 +43,8 @@ function ApDexMetrics({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold: thresholdValue || 0,
|
||||
delta: delta || false,
|
||||
metricsBuckets: metricsBuckets || [],
|
||||
threshold: thresholdValue || 0,
|
||||
metricsBuckets,
|
||||
}),
|
||||
clickhouse_sql: [],
|
||||
id: uuid(),
|
||||
@@ -75,7 +73,6 @@ function ApDexMetrics({
|
||||
id: SERVICE_CHART_ID.apdex,
|
||||
}),
|
||||
[
|
||||
delta,
|
||||
metricsBuckets,
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
@@ -92,10 +89,7 @@ function ApDexMetrics({
|
||||
}, [thresholdValue]);
|
||||
|
||||
const isQueryEnabled =
|
||||
topLevelOperationsRoute.length > 0 &&
|
||||
!!metricsBuckets &&
|
||||
metricsBuckets?.length > 0 &&
|
||||
delta !== undefined;
|
||||
topLevelOperationsRoute.length > 0 && metricsBuckets.length > 0;
|
||||
|
||||
return (
|
||||
<Graph
|
||||
@@ -110,9 +104,4 @@ function ApDexMetrics({
|
||||
);
|
||||
}
|
||||
|
||||
ApDexMetrics.defaultProps = {
|
||||
delta: undefined,
|
||||
le: undefined,
|
||||
};
|
||||
|
||||
export default ApDexMetrics;
|
||||
|
||||
@@ -31,7 +31,6 @@ function ApDexMetricsApplication({
|
||||
<ApDexMetrics
|
||||
topLevelOperationsRoute={topLevelOperationsRoute}
|
||||
handleGraphClick={handleGraphClick}
|
||||
delta={data?.data.delta}
|
||||
metricsBuckets={data?.data.le || []}
|
||||
onDragSelect={onDragSelect}
|
||||
tagFilterItems={tagFilterItems}
|
||||
|
||||
@@ -13,6 +13,5 @@ export interface ApDexDataSwitcherProps extends ApDexApplicationProps {
|
||||
}
|
||||
|
||||
export interface ApDexMetricsProps extends ApDexDataSwitcherProps {
|
||||
delta?: boolean;
|
||||
metricsBuckets?: number[];
|
||||
metricsBuckets: number[];
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { WidgetKeys } from '../constant';
|
||||
|
||||
export interface IServiceName {
|
||||
servicename: string;
|
||||
@@ -30,8 +36,8 @@ export interface BuilderQueriesProps {
|
||||
aggregateOperator?: string[];
|
||||
dataSource: DataSource;
|
||||
queryNameAndExpression?: string[];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
}
|
||||
|
||||
export interface BuilderQuerieswithFormulaProps {
|
||||
@@ -42,14 +48,12 @@ export interface BuilderQuerieswithFormulaProps {
|
||||
expressions: string[];
|
||||
legendFormulas: string[];
|
||||
additionalItems: TagFilterItem[][];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
comparisonSpaceAggregationParams?: (
|
||||
| MetrictypesComparisonSpaceAggregationParamDTO
|
||||
| undefined
|
||||
)[];
|
||||
// v5 picks its own step when none is sent; v4 needs one
|
||||
stepInterval?: number;
|
||||
dataSource: DataSource;
|
||||
}
|
||||
|
||||
@@ -70,7 +74,7 @@ export interface ApDexProps {
|
||||
servicename: IServiceName['servicename'];
|
||||
tagFilterItems: TagFilterItem[];
|
||||
topLevelOperationsRoute: string[];
|
||||
threashold: number;
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
export interface TableRendererProps {
|
||||
@@ -78,7 +82,12 @@ export interface TableRendererProps {
|
||||
renderFunction: (record: RowData) => ReactNode;
|
||||
}
|
||||
|
||||
export interface LatencyAtOrBelowAggregation {
|
||||
key: WidgetKeys;
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}
|
||||
|
||||
export interface ApDexMetricsQueryBuilderQueriesProps extends ApDexProps {
|
||||
delta: boolean;
|
||||
metricsBuckets: number[];
|
||||
}
|
||||
|
||||
@@ -30,23 +30,10 @@ export const SERVICE_DETAIL_DRILLDOWN_ENABLED = true;
|
||||
export enum FORMULA {
|
||||
ERROR_PERCENTAGE = 'A*100/B',
|
||||
DATABASE_CALLS_AVG_DURATION = 'A/B',
|
||||
// The apdex formula is (satisfied_count + 0.5 * tolerating_count + 0 * frustating_count) / total_count
|
||||
// The satisfied_count is B, tolerating_count is C, total_count is A
|
||||
// But why do we have (B+C)/2 instead of B + C/2?
|
||||
// The way we issue the query is latency <= threshold, which means we over count i.e
|
||||
// query B => durationNano <= 500ms
|
||||
// query C => durationNano <= 2000ms
|
||||
// Since <= 2000ms includes <= 500ms, we over count, to correct we subtract B/2
|
||||
// so the full expression would be (B + C/2) - B/2 = (B+C)/2
|
||||
// However, if you add a filter on durationNano > 500ms, (filterItemC in overviewQueries) the query would be
|
||||
// B + C/2
|
||||
APDEX_TRACES = '((B + C)/2)/A',
|
||||
// The delta span metrics store delta compared to previous reporting interval
|
||||
// but not the counts for the current interval. The bucket counts are cumulative
|
||||
APDEX_DELTA_SPAN_METRICS = '((B + C)/2)/A',
|
||||
// Cumulative span metrics store the counts for all buckets
|
||||
// so we need to subtract B/2 to correct the over counting
|
||||
APDEX_CUMULATIVE_SPAN_METRICS = '((B + C)/2)/A',
|
||||
// Apdex is (satisfied + tolerating / 2) / total, with satisfied B, tolerating C and total A.
|
||||
// C counts requests up to the bucket covering 4x the threshold, so it includes B:
|
||||
// B + (C - B) / 2 = (B + C) / 2
|
||||
APDEX = '((B + C)/2)/A',
|
||||
}
|
||||
|
||||
export const TOP_LEVEL_OPERATIONS = ['{{.top_level_operations}}'];
|
||||
@@ -80,17 +67,13 @@ export enum MetricsType {
|
||||
}
|
||||
|
||||
export enum WidgetKeys {
|
||||
Le = 'le',
|
||||
Name = 'name',
|
||||
HasError = 'hasError',
|
||||
Address = 'address',
|
||||
DurationNano = 'durationNano',
|
||||
SpanDurationNano = 'duration_nano',
|
||||
DurationNano = 'duration_nano',
|
||||
StatusCode = 'status.code',
|
||||
Operation = 'operation',
|
||||
OperationName = 'operationName',
|
||||
OTelServiceName = 'service.name',
|
||||
ServiceName = 'serviceName',
|
||||
SignozLatencyCount = 'signoz_latency.count',
|
||||
SignozDBLatencyCount = 'signoz_db_latency_count',
|
||||
DatabaseCallCount = 'signoz_database_call_count',
|
||||
|
||||
@@ -29,17 +29,24 @@ describe('Error Rate', () => {
|
||||
|
||||
describe('getNearestHighestBucketValue', () => {
|
||||
it('should return nearest higher bucket value', () => {
|
||||
expect(getNearestHighestBucketValue(50, [10, 20, 30, 40, 60, 70])).toBe('60');
|
||||
expect(getNearestHighestBucketValue(50, [10, 20, 30, 40, 60, 70])).toBe(60);
|
||||
});
|
||||
|
||||
it('should return +Inf for value higher than any bucket', () => {
|
||||
expect(getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70])).toBe(
|
||||
'+Inf',
|
||||
);
|
||||
it('should return undefined for value higher than any bucket', () => {
|
||||
expect(
|
||||
getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70]),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return the first bucket for value lower than all buckets', () => {
|
||||
expect(getNearestHighestBucketValue(5, [10, 20, 30, 40, 60, 70])).toBe('10');
|
||||
expect(getNearestHighestBucketValue(5, [10, 20, 30, 40, 60, 70])).toBe(10);
|
||||
});
|
||||
|
||||
it('should not reorder the buckets it is given', () => {
|
||||
const buckets = [60, 10, 30];
|
||||
|
||||
expect(getNearestHighestBucketValue(20, buckets)).toBe(30);
|
||||
expect(buckets).toStrictEqual([60, 10, 30]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -47,11 +47,9 @@ export const navigateToTrace = ({
|
||||
export const getNearestHighestBucketValue = (
|
||||
value: number,
|
||||
buckets: number[],
|
||||
): string => {
|
||||
// sort the buckets
|
||||
buckets.sort((a, b) => a - b);
|
||||
const nearestBucket = buckets.find((bucket) => bucket >= value);
|
||||
return nearestBucket?.toString() || '+Inf';
|
||||
): number | undefined => {
|
||||
// buckets are cached query data; never mutate
|
||||
return [...buckets].sort((a, b) => a - b).find((bucket) => bucket >= value);
|
||||
};
|
||||
|
||||
export const convertedTracesToDownloadData = (
|
||||
|
||||
@@ -3,8 +3,3 @@
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: var(--label-small-400-font-size);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -32,8 +32,3 @@
|
||||
gap: var(--spacing-6);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.titleText {
|
||||
color: inherit;
|
||||
font-size: var(--label-base-400-font-size);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
@@ -11,11 +15,7 @@ import {
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
export const serviceMetricsQuery = (
|
||||
topLevelOperation: [keyof ServiceDataProps, string[]],
|
||||
@@ -155,16 +155,16 @@ export const serviceMetricsQuery = (
|
||||
];
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
|
||||
const disabled = [false, true, true, false];
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import * as monaco from 'monaco-editor';
|
||||
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
|
||||
import * as jsonContribution from 'monaco-editor/esm/vs/language/json/monaco.contribution.js';
|
||||
import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js';
|
||||
import 'monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js';
|
||||
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
|
||||
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
|
||||
|
||||
@@ -11,10 +14,13 @@ self.MonacoEnvironment = {
|
||||
if (label === 'json') {
|
||||
return new JsonWorker(); // JSON language service
|
||||
}
|
||||
// SigNoz editors use JSON + a hand-registered ClickHouse tokenizer (no worker),
|
||||
// so the base editor worker covers everything else.
|
||||
return new EditorWorker(); // base worker — sql, yaml, plaintext etc.
|
||||
// SigNoz editors use JSON, SQL and YAML. Their tokenizers run on the main thread,
|
||||
// so the base editor worker covers the rest (word suggestions, links).
|
||||
return new EditorWorker(); // base worker: sql, yaml, plaintext etc.
|
||||
},
|
||||
};
|
||||
|
||||
// The `monaco-editor` entry exposes JSON this way; the role editor reads `languages.json`.
|
||||
Object.assign(monaco.languages, { json: jsonContribution });
|
||||
|
||||
export { monaco };
|
||||
|
||||
@@ -41,6 +41,12 @@ jest.mock('pages/AlertDetails', () => ({
|
||||
return <div>Alert Details Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('pages/ChannelsNew', () => ({
|
||||
__esModule: true,
|
||||
default: function MockChannelsNew(): JSX.Element {
|
||||
return <div>Channels New Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('../NotificationChannels/NotificationChannels', () => ({
|
||||
__esModule: true,
|
||||
default: function MockNotificationChannels(): JSX.Element {
|
||||
@@ -167,6 +173,41 @@ describe('AlertList', () => {
|
||||
`/alerts?tab=Configuration&subTab=${CHANNELS_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('navigates to the alert rules list when Alert Rules is clicked on a rule details page', async () => {
|
||||
mockQueryParams({ ruleId: 'rule-1' });
|
||||
mockLocation('/alerts/overview');
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(ALERT_RULES_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith('/alerts?tab=AlertRules');
|
||||
});
|
||||
|
||||
it('navigates to the channels list when Configuration is clicked on a channel page', async () => {
|
||||
mockQueryParams({});
|
||||
mockLocation('/alerts/channels/new');
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(CONFIGURATION_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${CHANNELS_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not navigate when the active list tab is clicked again', async () => {
|
||||
mockQueryParams({ tab: 'AlertRules' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(ALERT_RULES_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Configuration Tab with Secondary Sidebar', () => {
|
||||
|
||||
@@ -53,14 +53,16 @@ function AllAlertList(): JSX.Element {
|
||||
|
||||
const tab = urlQuery.get('tab');
|
||||
const subTab = urlQuery.get('subTab');
|
||||
const isAlertHistory = location.pathname === ROUTES.ALERT_HISTORY;
|
||||
const isAlertOverview = location.pathname === ROUTES.ALERT_OVERVIEW;
|
||||
const isRuleDetails =
|
||||
location.pathname === ROUTES.ALERT_HISTORY ||
|
||||
location.pathname === ROUTES.ALERT_OVERVIEW;
|
||||
const isChannelsNew = location.pathname === ROUTES.CHANNELS_NEW;
|
||||
const isChannelsEdit = location.pathname.startsWith('/alerts/channels/edit/');
|
||||
const isChannelDetails = isChannelsNew || isChannelsEdit;
|
||||
const isDetailsView = isRuleDetails || isChannelDetails;
|
||||
|
||||
const getActiveTab = useCallback((): string => {
|
||||
if (isAlertHistory || isAlertOverview) {
|
||||
if (isRuleDetails) {
|
||||
return AlertListTabs.ALERT_RULES;
|
||||
}
|
||||
if (isChannelDetails) {
|
||||
@@ -74,7 +76,7 @@ function AllAlertList(): JSX.Element {
|
||||
return AlertListTabs.CONFIGURATION;
|
||||
}
|
||||
return tab || AlertListTabs.ALERT_RULES;
|
||||
}, [isAlertHistory, isAlertOverview, isChannelDetails, tab]);
|
||||
}, [isRuleDetails, isChannelDetails, tab]);
|
||||
|
||||
const getActiveSubTab = useCallback((): AlertListSubTabs => {
|
||||
if (isChannelDetails) {
|
||||
@@ -114,6 +116,18 @@ function AllAlertList(): JSX.Element {
|
||||
[getActiveSubTab, safeNavigate],
|
||||
);
|
||||
|
||||
// A details page shows its parent tab as active, so a click on that tab must
|
||||
// still navigate back to the list; antd only fires onChange for a new key.
|
||||
const handleTopTabClick = useCallback(
|
||||
(clickedTab: string): void => {
|
||||
if (clickedTab === getActiveTab() && !isDetailsView) {
|
||||
return;
|
||||
}
|
||||
handleTopTabChange(clickedTab);
|
||||
},
|
||||
[getActiveTab, handleTopTabChange, isDetailsView],
|
||||
);
|
||||
|
||||
const handleSubTabChange = useCallback(
|
||||
(newSubTab: AlertListSubTabs): void => {
|
||||
const queryParams = new URLSearchParams();
|
||||
@@ -201,7 +215,7 @@ function AllAlertList(): JSX.Element {
|
||||
key: AlertListTabs.ALERT_RULES,
|
||||
children: (
|
||||
<div className="alert-rules-container">
|
||||
{isAlertHistory || isAlertOverview ? <AlertDetails /> : <AllAlertRules />}
|
||||
{isRuleDetails ? <AlertDetails /> : <AllAlertRules />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -222,12 +236,8 @@ function AllAlertList(): JSX.Element {
|
||||
destroyInactiveTabPane
|
||||
items={items}
|
||||
activeKey={getActiveTab()}
|
||||
onChange={handleTopTabChange}
|
||||
className={`alerts-container ${
|
||||
isAlertHistory || isAlertOverview || isChannelDetails
|
||||
? 'alert-details-tabs'
|
||||
: ''
|
||||
}`}
|
||||
onTabClick={handleTopTabClick}
|
||||
className={`alerts-container ${isDetailsView ? 'alert-details-tabs' : ''}`}
|
||||
tabBarExtraContent={
|
||||
<HeaderRightSection
|
||||
enableAnnouncements={false}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import * as monaco from 'monaco-editor';
|
||||
import { monaco } from 'lib/monaco/setup';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { renderAtRoute } from '@/storybook/renderAtRoute';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
@@ -196,6 +196,8 @@ describe('TraceDetailsHeader – trace metadata row', () => {
|
||||
totalSpansCount: 42,
|
||||
totalErrorSpansCount: 0,
|
||||
ai: {
|
||||
llmCallCount: 2,
|
||||
toolCallCount: 1,
|
||||
tokens: {
|
||||
input: 12040,
|
||||
output: 3110,
|
||||
@@ -408,6 +410,8 @@ describe('TraceDetailsHeader – tabs', () => {
|
||||
data: {
|
||||
...SUMMARY,
|
||||
ai: {
|
||||
llmCallCount: 1,
|
||||
toolCallCount: 0,
|
||||
tokens: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
|
||||
},
|
||||
},
|
||||
|
||||
@@ -27,6 +27,8 @@ const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
|
||||
'trace-ai': {
|
||||
...BASE_SUMMARY,
|
||||
ai: {
|
||||
llmCallCount: 2,
|
||||
toolCallCount: 1,
|
||||
tokens: {
|
||||
input: 1_200,
|
||||
output: 300,
|
||||
@@ -42,6 +44,8 @@ const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
|
||||
endTimestampMillis: 1_500,
|
||||
totalSpansCount: 4,
|
||||
ai: {
|
||||
llmCallCount: 1,
|
||||
toolCallCount: 0,
|
||||
tokens: { input: 80, output: 20, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
|
||||
totalCost: 0.0004,
|
||||
},
|
||||
|
||||
@@ -527,7 +527,12 @@ 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 {
|
||||
llmCallCount: 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'),
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { Plugin, TransformResult, UserConfig } from 'vite';
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import vitePluginChecker from 'vite-plugin-checker';
|
||||
import viteCompression from 'vite-plugin-compression';
|
||||
import { MONACO_STRIPPED_FEATURES } from './plugins/rules/shared/monaco-stripped-features.mjs';
|
||||
import type {
|
||||
Appcues,
|
||||
Posthog,
|
||||
@@ -74,6 +75,10 @@ function rawMarkdownPlugin(): Plugin {
|
||||
};
|
||||
}
|
||||
|
||||
// Monaco contributions that need a provider SigNoz never registers. monaco-editor
|
||||
// declares no `sideEffects`, so its bare imports keep all of them.
|
||||
const MONACO_STRIPPED_FEATURE_NAMES = Object.keys(MONACO_STRIPPED_FEATURES);
|
||||
|
||||
export default defineConfig(({ mode }): UserConfig => {
|
||||
const env = loadEnv(mode, process.cwd(), '') as ImportMetaEnv;
|
||||
// Base path for serving the app (e.g., '/signoz/'). Defaults to '/'.
|
||||
@@ -181,6 +186,16 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
outDir: 'build',
|
||||
cssMinify: 'esbuild',
|
||||
rolldownOptions: {
|
||||
treeshake: {
|
||||
moduleSideEffects: [
|
||||
{
|
||||
test: new RegExp(
|
||||
`monaco-editor/esm/vs/editor/contrib/(${MONACO_STRIPPED_FEATURE_NAMES.join('|')})/`,
|
||||
),
|
||||
sideEffects: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
output: {
|
||||
// Without this group Rolldown splits the entry's static graph into ~300
|
||||
// chunks, 324 requests on first load.
|
||||
|
||||
@@ -4,31 +4,34 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/http/handler"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/spantypes"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/summary", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetTraceSummary),
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetTraceSummary, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetTraceSummary",
|
||||
Tags: []string{"tracedetail"},
|
||||
Summary: "Get summary for a trace",
|
||||
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.",
|
||||
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.",
|
||||
Response: new(spantypes.GettableTraceSummary),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v4/traces/{traceID}/waterfall", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetWaterfallV4),
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetWaterfallV4, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetWaterfallV4",
|
||||
Tags: []string{"tracedetail"},
|
||||
@@ -40,14 +43,15 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/aggregations", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetTraceAggregations),
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetTraceAggregations, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetTraceAggregations",
|
||||
Tags: []string{"tracedetail"},
|
||||
@@ -59,14 +63,15 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v3/traces/{traceID}/flamegraph", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetFlamegraph),
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetFlamegraph, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetFlamegraph",
|
||||
Tags: []string{"tracedetail"},
|
||||
@@ -78,29 +83,159 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/thread", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.traceDetailHandler.GetThread),
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetThread, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetTraceThread",
|
||||
Tags: []string{"tracedetail"},
|
||||
Summary: "Get thread view for a trace",
|
||||
Description: "Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.",
|
||||
Description: "Returns the gen_ai spans of a trace, LLM calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.",
|
||||
RequestQuery: new(spantypes.GetTraceThreadParams),
|
||||
Response: new(spantypes.GettableTraceThread),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/highlights", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetTraceHighlights, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/spans", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.ListTraceSpans, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.GetTraceSpan, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/children", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.ListTraceSpanChildren, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/descendants", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.ListTraceSpanDescendants, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/traces/{traceID}/spans/{spanID}/ancestors", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.traceDetailHandler.ListTraceSpanAncestors, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
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: newScopedSecuritySchemes([]string{coretypes.ResourceTelemetryResourceTraces.Scope(coretypes.VerbRead)}),
|
||||
Stability: handler.StabilityDevelopment,
|
||||
},
|
||||
handler.WithResourceDefs(provider.traceReadResourceDef()),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (provider *provider) traceReadResourceDef() handler.TelemetryResourceDef {
|
||||
return handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: querybuilder.BuilderQueryWildcardResources(coretypes.ResourceTelemetryResourceTraces),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,16 @@ package flagger
|
||||
import "github.com/SigNoz/signoz/pkg/types/featuretypes"
|
||||
|
||||
var (
|
||||
FeatureUseSpanMetrics = featuretypes.MustNewName("use_span_metrics")
|
||||
FeatureKafkaSpanEval = featuretypes.MustNewName("kafka_span_eval")
|
||||
FeatureHideRootUser = featuretypes.MustNewName("hide_root_user")
|
||||
FeaturePutMetersInZeus = featuretypes.MustNewName("put_meters_in_zeus")
|
||||
FeatureUseMeterReporter = featuretypes.MustNewName("use_meter_reporter")
|
||||
FeatureUseJSONBody = featuretypes.MustNewName("use_json_body")
|
||||
FeatureEnableMetricsReduction = featuretypes.MustNewName("enable_metrics_reduction")
|
||||
FeatureResolveSemconvFamilies = featuretypes.MustNewName("resolve_semconv_families")
|
||||
FeatureUseTraceAttributesJSON = featuretypes.MustNewName("use_trace_attributes_json")
|
||||
FeatureUseSpanMetrics = featuretypes.MustNewName("use_span_metrics")
|
||||
FeatureKafkaSpanEval = featuretypes.MustNewName("kafka_span_eval")
|
||||
FeatureHideRootUser = featuretypes.MustNewName("hide_root_user")
|
||||
FeaturePutMetersInZeus = featuretypes.MustNewName("put_meters_in_zeus")
|
||||
FeatureUseMeterReporter = featuretypes.MustNewName("use_meter_reporter")
|
||||
FeatureUseJSONBody = featuretypes.MustNewName("use_json_body")
|
||||
FeatureEnableMetricsReduction = featuretypes.MustNewName("enable_metrics_reduction")
|
||||
FeatureResolveSemconvFamilies = featuretypes.MustNewName("resolve_semconv_families")
|
||||
FeatureUseTraceAttributesJSON = featuretypes.MustNewName("use_trace_attributes_json")
|
||||
FeatureUseNotificationTemplate = featuretypes.MustNewName("use_notification_template")
|
||||
)
|
||||
|
||||
func MustNewRegistry() featuretypes.Registry {
|
||||
@@ -88,6 +89,14 @@ func MustNewRegistry() featuretypes.Registry {
|
||||
DefaultVariant: featuretypes.MustNewName("disabled"),
|
||||
Variants: featuretypes.NewBooleanVariants(),
|
||||
},
|
||||
&featuretypes.Feature{
|
||||
Name: FeatureUseNotificationTemplate,
|
||||
Kind: featuretypes.KindBoolean,
|
||||
Stage: featuretypes.StageExperimental,
|
||||
Description: "Controls whether alert rules can use custom notification title and body templates",
|
||||
DefaultVariant: featuretypes.MustNewName("disabled"),
|
||||
Variants: featuretypes.NewBooleanVariants(),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -3,6 +3,7 @@ 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"
|
||||
@@ -127,3 +128,52 @@ 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) {
|
||||
claims, err := authtypes.ClaimsFromContext(r.Context())
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
params := new(spantypes.GetTraceHighlightsParams)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
query, err := spantypes.NewTraceHighlightsQuery(params)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.module.GetTraceHighlights(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], query)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// 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"))
|
||||
}
|
||||
|
||||
@@ -292,3 +292,15 @@ func (m *module) getWindowedFlamegraph(ctx context.Context, traceID, selectedSpa
|
||||
enrichedSpans := flamegraphTrace.EnrichSelectedSpans(selectedSpans, fullSpans, selectFields)
|
||||
return spantypes.NewGettableFlamegraphTrace(enrichedSpans, start, end, true), nil
|
||||
}
|
||||
|
||||
func (m *module) GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return spantypes.NewTraceHighlights(skeleton, query), nil
|
||||
}
|
||||
|
||||
@@ -24,6 +24,21 @@ 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{
|
||||
@@ -147,6 +162,8 @@ 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_llm_call) AS llm_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",
|
||||
@@ -160,7 +177,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.RootServiceName, &stats.RootEntryPoint, &stats.RootSpanStatusCode, &stats.GenAISpanCount, &stats.LLMCallCount, &stats.ToolCallCount,
|
||||
&stats.Tokens.Input, &stats.Tokens.Output, &stats.Tokens.CacheRead, &stats.Tokens.CacheWrite, &stats.Tokens.Reasoning,
|
||||
&stats.TotalCost,
|
||||
)
|
||||
@@ -172,17 +189,8 @@ 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 values {
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, names)
|
||||
@@ -195,9 +203,25 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := []string{isGenAI + " AS is_gen_ai"}
|
||||
isLLMCall, 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
|
||||
}
|
||||
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append([]string{isGenAI + " AS is_gen_ai", isLLMCall + " AS is_llm_call", isToolCall + " AS is_tool_call"}, usageColumns...), nil
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
// genAIUsageColumns returns the token and cost columns of a span, resolved across attribute evolutions.
|
||||
func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
|
||||
columns := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
// lookup by number, the type metadata stores numeric attributes under; float64 is only the output cast
|
||||
// fixed gen_ai keys that many traces lack, so a not-found warning means nothing here
|
||||
expr, _, err := querybuilder.ResolveColumn(ctx, q, s.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
|
||||
@@ -523,3 +547,74 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
|
||||
}
|
||||
return sb.Or(conds...), nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
|
||||
names := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
// Empty for the usual value, one reference to the parent, which the tree rebuilds from the two ids.
|
||||
otherReferences := fmt.Sprintf("multiIf(links = concat(%s, trace_id, %s, parent_span_id, %s), '', links = '', '[]', links) AS other_references",
|
||||
sb.Var(`[{"traceId":"`), sb.Var(`","spanId":"`), sb.Var(`","refType":"CHILD_OF"}]`))
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) span_id", "parent_span_id", "timestamp", "duration_nano", "has_error",
|
||||
"name", colServiceName, "kind_string", "response_status_code", "status_code_string", "status_message",
|
||||
colHasExceptionEvent, colHasLink, otherReferences,
|
||||
)
|
||||
sb.SelectMore(usageColumns...)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
sb.Where(
|
||||
sb.E("trace_id", traceID),
|
||||
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
|
||||
sb.LE("ts_bucket_start", bounds.End.Unix()),
|
||||
)
|
||||
sb.OrderByAsc("timestamp")
|
||||
sb.OrderByAsc("name")
|
||||
sb.OrderByAsc("span_id")
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
rows, err := 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
|
||||
// ScanStruct builds a new list of fields for every row; reusing one halves the time on a large trace.
|
||||
fields := []any{
|
||||
&span.SpanID, &span.ParentSpanID, &span.StartTime, &span.DurationNano, &span.HasError,
|
||||
&span.Name, &span.ServiceName, &span.KindString, &span.ResponseStatusCode, &span.StatusCodeString, &span.StatusMessage,
|
||||
&span.HasExceptionEvent, &span.HasLink, &span.OtherReferences,
|
||||
&span.AIUsage.InputTokens, &span.AIUsage.OutputTokens, &span.AIUsage.CacheReadTokens,
|
||||
&span.AIUsage.CacheWriteTokens, &span.AIUsage.ReasoningTokens, &span.AIUsage.Cost,
|
||||
}
|
||||
spanCount := 0
|
||||
for rows.Next() {
|
||||
// The builder keeps the usage values of a row, so every row gets its own.
|
||||
span.AIUsage = spantypes.AISpanUsage{}
|
||||
if err := rows.Scan(fields...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error scanning trace skeleton")
|
||||
}
|
||||
builder.Add(&span)
|
||||
spanCount++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error reading trace skeleton")
|
||||
}
|
||||
if spanCount == 0 {
|
||||
return nil, spantypes.ErrTraceNotFound
|
||||
}
|
||||
return builder.Build(), nil
|
||||
}
|
||||
|
||||
@@ -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, 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",
|
||||
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_llm_call) AS llm_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_llm_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",
|
||||
},
|
||||
{
|
||||
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, 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",
|
||||
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_llm_call) AS llm_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_llm_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",
|
||||
},
|
||||
{
|
||||
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, 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",
|
||||
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_llm_call) AS llm_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_llm_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",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -253,3 +253,39 @@ func TestGetThreadSpans(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTraceSkeleton(t *testing.T) {
|
||||
jsonInsideTrace := testStart.Add(500 * time.Second)
|
||||
jsonBeforeTrace := testStart.Add(-500 * time.Second)
|
||||
fl := flaggertest.WithBooleanFlags(t, map[string]bool{flagger.FeatureUseTraceAttributesJSON.String(): true})
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
jsonRelease *time.Time
|
||||
expectedSQL string
|
||||
}{
|
||||
{
|
||||
name: "LegacyMaps",
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, multiIf(mapContains(attributes_number, 'gen_ai.usage.input_tokens'), toFloat64(attributes_number['gen_ai.usage.input_tokens']), NULL) AS input_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.output_tokens'), toFloat64(attributes_number['gen_ai.usage.output_tokens']), NULL) AS output_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_read.input_tokens']), NULL) AS cache_read_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_creation.input_tokens']), NULL) AS cache_write_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), toFloat64(attributes_number['gen_ai.usage.reasoning.output_tokens']), NULL) AS reasoning_tokens_value, multiIf(mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), toFloat64(attributes_number['signoz.gen_ai.usage.tokens.cost']), NULL) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionInsideTrace_ReadsBothColumns",
|
||||
jsonRelease: &jsonInsideTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.input_tokens'), attributes_number['gen_ai.usage.input_tokens'], NULL)) AS input_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.output_tokens'), attributes_number['gen_ai.usage.output_tokens'], NULL)) AS output_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), attributes_number['gen_ai.usage.cache_read.input_tokens'], NULL)) AS cache_read_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), attributes_number['gen_ai.usage.cache_creation.input_tokens'], NULL)) AS cache_write_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), attributes_number['gen_ai.usage.reasoning.output_tokens'], NULL)) AS reasoning_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) IS NOT NULL, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String), mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), attributes_number['signoz.gen_ai.usage.tokens.cost'], NULL)) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionBeforeTrace_ReadsJSONOnly",
|
||||
jsonRelease: &jsonBeforeTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
s := newTestStoreWithMetadata(sqlmock.QueryMatcherEqual, genAIMetadataStore(testCase.jsonRelease), fl)
|
||||
s.Mock().ExpectQuery(testCase.expectedSQL).WithArgs(`[{"traceId":"`, `","spanId":"`, `","refType":"CHILD_OF"}]`, testTraceID, testStart.Unix()-1800, testEnd.Unix()).WillReturnRows(cmock.NewRows(nil, nil))
|
||||
_, _ = s.Store().GetTraceSkeleton(context.Background(), valuer.GenerateUUID(), testTraceID, testBounds)
|
||||
assert.NoError(t, s.Mock().ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ 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.
|
||||
@@ -25,4 +31,5 @@ type Module interface {
|
||||
GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)
|
||||
GetFlamegraph(ctx context.Context, traceID string, selectedSpanID string, selectFields []telemetrytypes.TelemetryFieldKey) (*spantypes.GettableFlamegraphTrace, error)
|
||||
GetThread(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.ThreadQuery) (*spantypes.GettableTraceThread, error)
|
||||
GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error)
|
||||
}
|
||||
|
||||
@@ -33,6 +33,13 @@ func (q *querier) QueryRangePreview(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// read off the whole request: previewing a query alone would lose the
|
||||
// formulas that read it
|
||||
unreadQueries, err := req.UnreadQueryNames()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
results := make(map[string]qbtypes.QueryPreview, len(req.CompositeQuery.Queries))
|
||||
|
||||
prepared := make(map[string]qbtypes.QueryPreview, len(req.CompositeQuery.Queries))
|
||||
@@ -78,7 +85,7 @@ func (q *querier) QueryRangePreview(
|
||||
skip[name] = true
|
||||
}
|
||||
}
|
||||
providers, buildErrs := q.buildPreviewProviders(orgID, req, dependencyQueries, missingMetricQuerySet, skip)
|
||||
providers, buildErrs := q.buildPreviewProviders(orgID, req, dependencyQueries, unreadQueries, missingMetricQuerySet, skip)
|
||||
|
||||
// Render each executing query's statement and collect the ClickHouse-bound
|
||||
// analysis work to run concurrently.
|
||||
@@ -101,6 +108,13 @@ func (q *querier) QueryRangePreview(
|
||||
continue
|
||||
}
|
||||
|
||||
if unreadQueries[name] {
|
||||
ps.Warnings = append(ps.Warnings, fmt.Sprintf(
|
||||
"query %q is disabled and no enabled formula reads it, so it does not run", name))
|
||||
results[name] = ps
|
||||
continue
|
||||
}
|
||||
|
||||
provider, ok := providers[name]
|
||||
if !ok {
|
||||
if !rendersStandaloneStatement(query.Type) {
|
||||
@@ -202,6 +216,7 @@ func (q *querier) buildPreviewProviders(
|
||||
orgID valuer.UUID,
|
||||
req *qbtypes.QueryRangeRequest,
|
||||
dependencyQueries map[string]bool,
|
||||
unreadQueries map[string]bool,
|
||||
missingMetricQuerySet map[string]bool,
|
||||
skip map[string]bool,
|
||||
) (providers map[string]qbtypes.Query, errs map[string]error) {
|
||||
@@ -238,7 +253,7 @@ func (q *querier) buildPreviewProviders(
|
||||
sub.CompositeQuery = qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{query}}
|
||||
}
|
||||
|
||||
built, _, bErr := q.buildQueries(orgID, &sub, deps, missingMetricQuerySet, event)
|
||||
built, _, bErr := q.buildQueries(orgID, &sub, deps, unreadQueries, missingMetricQuerySet, event)
|
||||
if bErr != nil {
|
||||
errs[name] = bErr
|
||||
continue
|
||||
|
||||
@@ -144,7 +144,12 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
|
||||
missingMetricQuerySet[name] = true
|
||||
}
|
||||
|
||||
queries, steps, err := q.buildQueries(orgID, req, dependencyQueries, missingMetricQuerySet, event)
|
||||
unreadQueries, err := req.UnreadQueryNames()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
queries, steps, err := q.buildQueries(orgID, req, dependencyQueries, unreadQueries, missingMetricQuerySet, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -191,6 +196,7 @@ func (q *querier) buildQueries(
|
||||
orgID valuer.UUID,
|
||||
req *qbtypes.QueryRangeRequest,
|
||||
dependencyQueries map[string]bool,
|
||||
unreadQueries map[string]bool,
|
||||
missingMetricQuerySet map[string]bool,
|
||||
event *qbtypes.QBEvent,
|
||||
) (map[string]qbtypes.Query, map[string]qbtypes.Step, error) {
|
||||
@@ -211,6 +217,10 @@ func (q *querier) buildQueries(
|
||||
continue
|
||||
}
|
||||
|
||||
if unreadQueries[queryName] {
|
||||
continue
|
||||
}
|
||||
|
||||
switch query.Type {
|
||||
case qbtypes.QueryTypeFormula:
|
||||
// the querier evaluates a formula after its queries run, so a bad
|
||||
|
||||
@@ -1085,6 +1085,15 @@ func (aH *APIHandler) getFeatureFlags(w http.ResponseWriter, r *http.Request) {
|
||||
Route: "",
|
||||
})
|
||||
|
||||
useNotificationTemplate := aH.Signoz.Flagger.BooleanOrEmpty(r.Context(), flagger.FeatureUseNotificationTemplate, evalCtx)
|
||||
featureSet = append(featureSet, &licensetypes.Feature{
|
||||
Name: valuer.NewString(flagger.FeatureUseNotificationTemplate.String()),
|
||||
Active: useNotificationTemplate,
|
||||
Usage: 0,
|
||||
UsageLimit: -1,
|
||||
Route: "",
|
||||
})
|
||||
|
||||
aH.Respond(w, featureSet)
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +144,11 @@ func getOperators(ops []pipelinetypes.PipelineOperator) ([]pipelinetypes.Pipelin
|
||||
}
|
||||
}
|
||||
} else if operator.Type == "move" || operator.Type == "copy" {
|
||||
if _, err := fieldNotNilCheck(operator.To); err != nil {
|
||||
return nil, errors.WrapInvalidInputf(
|
||||
err, CodeFieldNilCheckType, "invalid to field of %s op %s", operator.Type, operator.Name,
|
||||
)
|
||||
}
|
||||
fromNotNilCheck, err := fieldNotNilCheck(operator.From)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
@@ -476,7 +481,7 @@ func rSplitAfterN(str string, sep string, n int) []string {
|
||||
func reverseString(s string) string {
|
||||
r := []rune(s)
|
||||
for i := 0; i < len(r)/2; i++ {
|
||||
j := len(s) - 1 - i
|
||||
j := len(r) - 1 - i
|
||||
r[i], r[j] = r[j], r[i]
|
||||
}
|
||||
return string(r)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
signozstanzahelper "github.com/SigNoz/signoz-otel-collector/processor/signozlogspipelineprocessor/stanza/operator/helper"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/model"
|
||||
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/utils"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -211,6 +213,48 @@ func TestPreparePipelineProcessor(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOperatorsRejectsEmptyTo(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
opType string
|
||||
}{
|
||||
{name: "Move", opType: "move"},
|
||||
{name: "Copy", opType: "copy"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
_, err := getOperators([]pipelinetypes.PipelineOperator{{
|
||||
ID: testCase.opType,
|
||||
Type: testCase.opType,
|
||||
Name: testCase.opType,
|
||||
Enabled: true,
|
||||
From: "attributes.test",
|
||||
}})
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Asc(err, CodeFieldNilCheckType))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldNotNilCheck(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
fieldPath string
|
||||
expected string
|
||||
}{
|
||||
{name: "NonASCIIMembership", fieldPath: `attributes["名前"]`, expected: `attributes["名前"] != nil`},
|
||||
{name: "NonASCIINestedMembership", fieldPath: `attributes["a"]["名前"]`, expected: `attributes["a"] != nil && attributes["a"]["名前"] != nil`},
|
||||
{name: "NonASCIIDotted", fieldPath: `attributes.名前`, expected: `attributes?.名前 != nil`},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
check, err := fieldNotNilCheck(testCase.fieldPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, check)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoCollectorErrorsFromProcessorsForMismatchedLogs(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
|
||||
@@ -96,6 +96,77 @@ func HeatmapAggregationField(expression string) (telemetrytypes.TelemetryFieldKe
|
||||
return telemetrytypes.GetFieldKeyFromKeyText(keyText), true
|
||||
}
|
||||
|
||||
// FormulaInputNames resolves each variable of formula, such as a or A.0, to the
|
||||
// name of the query it reads, the way the formula evaluator does. Variables
|
||||
// naming no query are left out.
|
||||
func (r *QueryRangeRequest) FormulaInputNames(formula QueryBuilderFormula) ([]string, error) {
|
||||
variables, err := formula.ExtractReferencedQueryNames()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
queryNames := make([]string, 0, len(r.CompositeQuery.Queries))
|
||||
for i := range r.CompositeQuery.Queries {
|
||||
queryNames = append(queryNames, r.CompositeQuery.Queries[i].GetQueryName())
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, variable := range variables {
|
||||
ref, err := parseAggregationReference(variable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
index := slices.Index(queryNames, ref.QueryName)
|
||||
if index < 0 {
|
||||
index = slices.IndexFunc(queryNames, func(name string) bool { return strings.EqualFold(name, ref.QueryName) })
|
||||
}
|
||||
if index >= 0 && !slices.Contains(names, queryNames[index]) {
|
||||
names = append(names, queryNames[index])
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// EnabledFormulaInputNames names the queries read by an enabled formula.
|
||||
func (r *QueryRangeRequest) EnabledFormulaInputNames() (map[string]bool, error) {
|
||||
names := map[string]bool{}
|
||||
for _, envelope := range r.CompositeQuery.Queries {
|
||||
formula, ok := envelope.Spec.(QueryBuilderFormula)
|
||||
if !ok || formula.Disabled {
|
||||
continue
|
||||
}
|
||||
inputs, err := r.FormulaInputNames(formula)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, input := range inputs {
|
||||
names[input] = true
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// UnreadQueryNames names the queries a heatmap or distribution request does
|
||||
// not run. A heatmap draws only its enabled query, so a disabled one runs only
|
||||
// to feed an enabled formula.
|
||||
func (r *QueryRangeRequest) UnreadQueryNames() (map[string]bool, error) {
|
||||
names := map[string]bool{}
|
||||
if !r.RequestType.CountsIntoBuckets() {
|
||||
return names, nil
|
||||
}
|
||||
inputs, err := r.EnabledFormulaInputNames()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range r.CompositeQuery.Queries {
|
||||
query := &r.CompositeQuery.Queries[i]
|
||||
if query.Type != QueryTypeFormula && query.IsDisabled() && !inputs[query.GetQueryName()] {
|
||||
names[query.GetQueryName()] = true
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// HeatmapCountQuery splits a logs or traces heatmap query into the field its
|
||||
// aggregation buckets and a copy of query that counts events in its place,
|
||||
// which is what every cell holds.
|
||||
|
||||
@@ -94,3 +94,72 @@ func TestToDistributionDataPercentiles(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormulaInputNames(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
expression string
|
||||
expectedNames []string
|
||||
}{
|
||||
{name: "ExactNames", expression: "A + B", expectedNames: []string{"A", "B"}},
|
||||
{name: "LowercaseName_ResolvedToQuery", expression: "a * 2", expectedNames: []string{"A"}},
|
||||
{name: "IndexReference_ResolvedToQuery", expression: "[A.0] + B", expectedNames: []string{"A", "B"}},
|
||||
{name: "UnknownName_LeftOut", expression: "A + Z", expectedNames: []string{"A"}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
req := &QueryRangeRequest{CompositeQuery: CompositeQuery{Queries: []QueryEnvelope{
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "A"}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "B"}},
|
||||
}}}
|
||||
|
||||
names, err := req.FormulaInputNames(QueryBuilderFormula{Name: "F1", Expression: testCase.expression})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expectedNames, names)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnabledFormulaInputNames(t *testing.T) {
|
||||
req := &QueryRangeRequest{CompositeQuery: CompositeQuery{Queries: []QueryEnvelope{
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "A", Disabled: true}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "B", Disabled: true}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "C", Disabled: true}},
|
||||
{Type: QueryTypeFormula, Spec: QueryBuilderFormula{Name: "F1", Expression: "a + B"}},
|
||||
{Type: QueryTypeFormula, Spec: QueryBuilderFormula{Name: "F2", Expression: "C", Disabled: true}},
|
||||
}}}
|
||||
|
||||
names, err := req.EnabledFormulaInputNames()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]bool{"A": true, "B": true}, names)
|
||||
}
|
||||
|
||||
func TestUnreadQueryNames(t *testing.T) {
|
||||
queries := []QueryEnvelope{
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[MetricAggregation]{Name: "A", Disabled: true}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{Name: "B", Disabled: true}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[MetricAggregation]{Name: "C", Disabled: true}},
|
||||
{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[MetricAggregation]{Name: "D"}},
|
||||
{Type: QueryTypeFormula, Spec: QueryBuilderFormula{Name: "F1", Expression: "A * 2"}},
|
||||
{Type: QueryTypeFormula, Spec: QueryBuilderFormula{Name: "F2", Expression: "C", Disabled: true}},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
requestType RequestType
|
||||
expected map[string]bool
|
||||
}{
|
||||
{name: "Heatmap", requestType: RequestTypeHeatmap, expected: map[string]bool{"B": true, "C": true}},
|
||||
{name: "Distribution", requestType: RequestTypeDistribution, expected: map[string]bool{"B": true, "C": true}},
|
||||
{name: "TimeSeries_RunsEveryQuery", requestType: RequestTypeTimeSeries, expected: map[string]bool{}},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
req := &QueryRangeRequest{RequestType: testCase.requestType, CompositeQuery: CompositeQuery{Queries: queries}}
|
||||
names, err := req.UnreadQueryNames()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, names)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,6 +901,7 @@ func (r *QueryRangeRequest) validateBucketCounting() error {
|
||||
"fillGaps is not supported for %s requests: an absent column means collection stopped, which a zero-filled column would hide", r.RequestType.StringValue())
|
||||
}
|
||||
|
||||
eventQueries := r.eventQueryNames()
|
||||
enabled := 0
|
||||
for _, envelope := range r.CompositeQuery.Queries {
|
||||
if err := extractEnabledBucketOptions(envelope).validateBucketOptions(); err != nil {
|
||||
@@ -923,6 +924,13 @@ func (r *QueryRangeRequest) validateBucketCounting() error {
|
||||
if spec.Disabled {
|
||||
continue
|
||||
}
|
||||
inputs, err := r.FormulaInputNames(spec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateBucketCountingFormulaInputs(spec.Name, inputs, eventQueries); err != nil {
|
||||
return err
|
||||
}
|
||||
enabled++
|
||||
case ClickHouseQuery:
|
||||
if spec.Disabled {
|
||||
@@ -1057,9 +1065,36 @@ func validateBucketCountingQuery(requestType RequestType, functions []Function,
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateBucketCountingFormulaInputs refuses a formula reading a logs or
|
||||
// traces query: their heatmaps count events per bucket, which a formula has no
|
||||
// value per step to compute with.
|
||||
func validateBucketCountingFormulaInputs(formulaName string, inputs []string, eventQueries map[string]bool) error {
|
||||
for _, name := range inputs {
|
||||
if eventQueries[name] {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput,
|
||||
"formula %q reads logs or traces query %q, but logs and traces heatmaps do not support formulas", formulaName, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// eventQueryNames names the logs and traces queries of r.
|
||||
func (r *QueryRangeRequest) eventQueryNames() map[string]bool {
|
||||
names := map[string]bool{}
|
||||
for _, envelope := range r.CompositeQuery.Queries {
|
||||
switch spec := envelope.Spec.(type) {
|
||||
case QueryBuilderQuery[LogAggregation]:
|
||||
names[spec.Name] = true
|
||||
case QueryBuilderQuery[TraceAggregation]:
|
||||
names[spec.Name] = true
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// validateEventHeatmapQuery holds a logs or traces query to what a per-event
|
||||
// heatmap can draw. A disabled query feeds a formula rather than the chart, so
|
||||
// it aggregates as a time series.
|
||||
// heatmap can draw. A disabled query is not drawn, and with no formula to read
|
||||
// it, never runs.
|
||||
func validateEventHeatmapQuery(requestType RequestType, functions []Function, having *Having, expressions []string, disabled bool) error {
|
||||
if err := validateBucketCountingQuery(requestType, functions, having); err != nil {
|
||||
return err
|
||||
|
||||
@@ -1690,3 +1690,84 @@ func TestMetricAggregationValidateForTypeAndTemporality(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBucketCountingFormulaInputs(t *testing.T) {
|
||||
logsQuery := func(name string, expression string, disabled bool) QueryEnvelope {
|
||||
return QueryEnvelope{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[LogAggregation]{
|
||||
Name: name,
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Disabled: disabled,
|
||||
Aggregations: []LogAggregation{{Expression: expression}},
|
||||
}}
|
||||
}
|
||||
metricsQuery := func(name string, metricName string) QueryEnvelope {
|
||||
return QueryEnvelope{Type: QueryTypeBuilder, Spec: QueryBuilderQuery[MetricAggregation]{
|
||||
Name: name,
|
||||
Signal: telemetrytypes.SignalMetrics,
|
||||
Disabled: true,
|
||||
Aggregations: []MetricAggregation{{
|
||||
MetricName: metricName,
|
||||
Temporality: metrictypes.Delta,
|
||||
TimeAggregation: metrictypes.TimeAggregationRate,
|
||||
SpaceAggregation: metrictypes.SpaceAggregationSum,
|
||||
}},
|
||||
}}
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
queries []QueryEnvelope
|
||||
expression string
|
||||
formulaDisabled bool
|
||||
expectedErr string
|
||||
}{
|
||||
{
|
||||
name: "MetricsInputs_Valid",
|
||||
queries: []QueryEnvelope{metricsQuery("A", "http_requests_total"), metricsQuery("B", "http_errors_total")},
|
||||
expression: "B / A",
|
||||
},
|
||||
{
|
||||
name: "DisabledFormulaOverDrawnLogsQuery_Valid",
|
||||
queries: []QueryEnvelope{logsQuery("A", "attribute.quantity", false)},
|
||||
expression: "A * 2",
|
||||
formulaDisabled: true,
|
||||
},
|
||||
{
|
||||
name: "LogsBareField_Rejected",
|
||||
queries: []QueryEnvelope{logsQuery("A", "attribute.quantity", true), logsQuery("B", "attribute.code.lineno", true)},
|
||||
expression: "A + B",
|
||||
expectedErr: `formula "F1" reads logs or traces query "A", but logs and traces heatmaps do not support formulas`,
|
||||
},
|
||||
{
|
||||
name: "LogsAggregation_Rejected",
|
||||
queries: []QueryEnvelope{logsQuery("A", "avg(attribute.quantity)", true)},
|
||||
expression: "A * 2",
|
||||
expectedErr: `formula "F1" reads logs or traces query "A"`,
|
||||
},
|
||||
{
|
||||
name: "LowercaseReferenceToLogs_Rejected",
|
||||
queries: []QueryEnvelope{metricsQuery("A", "http_requests_total"), logsQuery("B", "count()", true)},
|
||||
expression: "A / b",
|
||||
expectedErr: `formula "F1" reads logs or traces query "B"`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
req := &QueryRangeRequest{
|
||||
RequestType: RequestTypeDistribution,
|
||||
CompositeQuery: CompositeQuery{Queries: append(testCase.queries,
|
||||
QueryEnvelope{Type: QueryTypeFormula, Spec: QueryBuilderFormula{Name: "F1", Expression: testCase.expression, Disabled: testCase.formulaDisabled}},
|
||||
)},
|
||||
}
|
||||
|
||||
err := req.validateBucketCounting()
|
||||
if testCase.expectedErr == "" {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), testCase.expectedErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
98
pkg/types/spantypes/span.go
Normal file
98
pkg/types/spantypes/span.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package spantypes
|
||||
|
||||
const (
|
||||
SpanListViewErrorOrigins SpanListView = "error_origins"
|
||||
SpanListViewUnmarkedFailures SpanListView = "unmarked_failures"
|
||||
SpanListViewTimeSpent SpanListView = "time_spent"
|
||||
SpanListViewAIUsage SpanListView = "ai_usage"
|
||||
SpanListViewLinks SpanListView = "links"
|
||||
)
|
||||
|
||||
const (
|
||||
UnmarkedFailureHTTP4xx UnmarkedFailureKind = "http_4xx"
|
||||
UnmarkedFailureHTTP5xx UnmarkedFailureKind = "http_5xx"
|
||||
UnmarkedFailureGRPCStatus UnmarkedFailureKind = "grpc_status"
|
||||
UnmarkedFailureExceptionEvent UnmarkedFailureKind = "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}
|
||||
}
|
||||
|
||||
// UnmarkedFailureKind says why a span without the error flag is in the unmarked_failures list. It is
|
||||
// a plain string so that omitempty leaves it out: the response encoder does not omit a zero struct.
|
||||
type UnmarkedFailureKind string
|
||||
|
||||
func (UnmarkedFailureKind) 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:"Keeps only the spans of one kind, judged on the whole trace, by start time unless stated. error_origins: error spans with no failing child. unmarked_failures: spans not marked as errors with a 4xx or 5xx response, a non-OK gRPC status or an exception event. time_spent: one span per same-name sibling group, by the group's own time. ai_usage: spans with gen_ai token or cost usage, with those attributes, by cost, else tokens. links: spans that link to other spans."`
|
||||
Query string `query:"query" description:"Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view."`
|
||||
SelectFields []string `query:"selectFields" description:"Attributes or resource attributes to add to each span, for example http.route or resource.k8s.pod.name. Default: service.name only."`
|
||||
Offset int `query:"offset" description:"Number of spans to skip. Default: 0."`
|
||||
Limit int `query:"limit" description:"Number of spans to return. Default: 50. Maximum: 1000."`
|
||||
}
|
||||
|
||||
// Span is a stored span. Apart from time_unix, 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:"Empty for a root."`
|
||||
Name string `json:"name" required:"true"`
|
||||
KindString string `json:"kind_string" required:"true" description:"For example Server, Client or Internal."`
|
||||
TimeUnix uint64 `json:"time_unix" required:"true" description:"Start time, in Unix milliseconds."`
|
||||
DurationNano uint64 `json:"duration_nano" required:"true"`
|
||||
HasError bool `json:"has_error" required:"true"`
|
||||
StatusCodeString string `json:"status_code_string" required:"true"`
|
||||
StatusMessage string `json:"status_message" required:"true" description:"Usually the error text."`
|
||||
ResponseStatusCode string `json:"response_status_code" required:"true" description:"HTTP or gRPC status code, for example 404."`
|
||||
Resource map[string]string `json:"resource" required:"true" nullable:"false" description:"Always has service.name. All of them for a span read by ID; the selected ones in a list."`
|
||||
Attributes map[string]any `json:"attributes" required:"true" nullable:"false" description:"All of them for a span read by ID; the selected ones in a list."`
|
||||
Events []Event `json:"events" required:"true" nullable:"false" description:"All of them for a span read by ID; none in a list."`
|
||||
References []OtelSpanRef `json:"references" required:"true" nullable:"false" description:"The parent as CHILD_OF, and each span link as FOLLOWS_FROM."`
|
||||
}
|
||||
|
||||
type SameNameSiblingStats struct {
|
||||
SpanCount uint64 `json:"spanCount" required:"true" description:"This span included."`
|
||||
OwnTimeNano uint64 `json:"ownTimeNano" required:"true"`
|
||||
ErrorSpanCount uint64 `json:"errorSpanCount" required:"true"`
|
||||
}
|
||||
|
||||
// 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:"0 for a root."`
|
||||
ChildCount uint32 `json:"childCount" required:"true"`
|
||||
SubtreeSpanCount uint32 `json:"subtreeSpanCount" required:"true" description:"Spans below this one, at any depth."`
|
||||
OwnTimeNano uint64 `json:"ownTimeNano" required:"true" description:"Duration minus the time its children cover."`
|
||||
ErrorAncestorCount uint32 `json:"errorAncestorCount" required:"true" description:"Ancestors marked as errors in an unbroken run up from the parent: how far an error spread."`
|
||||
SameNameSiblings *SameNameSiblingStats `json:"sameNameSiblings,omitempty" description:"Totals for the spans with this span's name and parent. Omitted when it has none."`
|
||||
}
|
||||
|
||||
type SpanTextMatch struct {
|
||||
Field string `json:"field" required:"true" description:"name, status_message, attributes.<name>, resource.<name> or events[<index>]."`
|
||||
Snippet string `json:"snippet" required:"true" description:"About 40 characters on each side of the word."`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
UnmarkedFailureKind UnmarkedFailureKind `json:"unmarkedFailureKind,omitempty" description:"Why the span is an unmarked failure. Omitted for other spans."`
|
||||
Matches []SpanTextMatch `json:"matches,omitempty" nullable:"false" description:"Where the query's words were found, up to three places. Omitted when the query has no words."`
|
||||
}
|
||||
|
||||
type SpanList struct {
|
||||
Total uint64 `json:"total" required:"true" description:"Matching spans across all pages."`
|
||||
Items []SpanItem `json:"items" required:"true" nullable:"false"`
|
||||
Warnings []string `json:"warnings,omitempty" nullable:"false" description:"Why the result may be incomplete, for example an unknown query key or a selected field no returned span has."`
|
||||
}
|
||||
@@ -40,6 +40,8 @@ type TraceStore interface {
|
||||
GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, page ThreadPage) ([]StorableSpan, error)
|
||||
GetThreadCursor(ctx context.Context, traceID string, bounds *TraceBounds, spanID string) (*ThreadCursor, error)
|
||||
|
||||
GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds) (*TraceSkeleton, error)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
78
pkg/types/spantypes/trace_highlights.go
Normal file
78
pkg/types/spantypes/trace_highlights.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"slices"
|
||||
)
|
||||
|
||||
const highlightsDefaultLimit = 10
|
||||
|
||||
type GetTraceHighlightsParams struct {
|
||||
Views []SpanListView `query:"views" description:"The lists to return. Default: all."`
|
||||
Limit int `query:"limit" description:"Spans in each list. Default: 10. Maximum: 1000."`
|
||||
}
|
||||
|
||||
type TraceServiceStats struct {
|
||||
ServiceName string `json:"serviceName" required:"true"`
|
||||
SpanCount uint64 `json:"spanCount" required:"true"`
|
||||
ErrorSpanCount uint64 `json:"errorSpanCount" required:"true"`
|
||||
OwnTimeNano uint64 `json:"ownTimeNano" required:"true" description:"Sum of the own time of the service's spans."`
|
||||
}
|
||||
|
||||
// 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:"Highest own time first."`
|
||||
ErrorOrigins *SpanList `json:"errorOrigins,omitempty" description:"First page of the error_origins view."`
|
||||
UnmarkedFailures *SpanList `json:"unmarkedFailures,omitempty" description:"First page of the unmarked_failures view."`
|
||||
TimeSpent *SpanList `json:"timeSpent,omitempty" description:"First page of the time_spent view."`
|
||||
AIUsage *SpanList `json:"aiUsage,omitempty" description:"First page of the ai_usage view."`
|
||||
Links *SpanList `json:"links,omitempty" description:"First page of the links view."`
|
||||
}
|
||||
|
||||
type TraceHighlightsQuery struct {
|
||||
Views []SpanListView
|
||||
Limit int
|
||||
}
|
||||
|
||||
func NewTraceHighlightsQuery(params *GetTraceHighlightsParams) (*TraceHighlightsQuery, error) {
|
||||
limit, err := pageLimit("limit", params.Limit, highlightsDefaultLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := &TraceHighlightsQuery{Limit: limit}
|
||||
for _, view := range params.Views {
|
||||
if err := validateSpanListView(view); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(query.Views, view) {
|
||||
query.Views = append(query.Views, view)
|
||||
}
|
||||
}
|
||||
if len(query.Views) == 0 {
|
||||
for _, view := range SpanListView("").Enum() {
|
||||
query.Views = append(query.Views, view.(SpanListView))
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
// NewTraceHighlights builds the first page of each requested view from the tree.
|
||||
func NewTraceHighlights(skeleton *TraceSkeleton, query *TraceHighlightsQuery) *TraceHighlights {
|
||||
highlights := &TraceHighlights{Services: skeleton.serviceStats()}
|
||||
for _, view := range query.Views {
|
||||
list := NewSpanList(skeleton.page(skeleton.treeOrder, view, 0, query.Limit))
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
highlights.ErrorOrigins = list
|
||||
case SpanListViewUnmarkedFailures:
|
||||
highlights.UnmarkedFailures = list
|
||||
case SpanListViewTimeSpent:
|
||||
highlights.TimeSpent = list
|
||||
case SpanListViewAIUsage:
|
||||
highlights.AIUsage = list
|
||||
case SpanListViewLinks:
|
||||
highlights.Links = list
|
||||
}
|
||||
}
|
||||
return highlights
|
||||
}
|
||||
436
pkg/types/spantypes/trace_skeleton.go
Normal file
436
pkg/types/spantypes/trace_skeleton.go
Normal file
@@ -0,0 +1,436 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
noParent int32 = -1
|
||||
|
||||
refTypeChildOf = "CHILD_OF"
|
||||
)
|
||||
|
||||
// SkeletonSpan is one row of the query a TraceSkeleton is built from.
|
||||
type SkeletonSpan struct {
|
||||
Span
|
||||
// StartTime keeps the nanoseconds own time is computed from; TimeUnix is in milliseconds.
|
||||
StartTime time.Time
|
||||
ServiceName string
|
||||
HasExceptionEvent bool
|
||||
HasLink bool
|
||||
// OtherReferences is empty for a span whose only reference is the one to its parent.
|
||||
OtherReferences string
|
||||
// AIUsage is kept when it has a value, pointers included: every row needs its own.
|
||||
AIUsage AISpanUsage
|
||||
}
|
||||
|
||||
// AISpanUsage is the gen_ai token and cost usage of one span; a nil value is absent on the span.
|
||||
type AISpanUsage struct {
|
||||
InputTokens *float64
|
||||
OutputTokens *float64
|
||||
CacheReadTokens *float64
|
||||
CacheWriteTokens *float64
|
||||
ReasoningTokens *float64
|
||||
Cost *float64
|
||||
}
|
||||
|
||||
// TraceSkeleton is the tree of a trace. A span is known by its position, its index in start time
|
||||
// order, and every slice below holds one value per span at that position. It is read-only once built.
|
||||
type TraceSkeleton struct {
|
||||
traceID string
|
||||
|
||||
// spanIDs holds every span id back to back; span i is spanIDs[idOffsets[i]:idOffsets[i+1]].
|
||||
spanIDs string
|
||||
idOffsets []uint32
|
||||
// parents holds the position of each span's parent, or noParent for a root.
|
||||
parents []int32
|
||||
startNano []int64
|
||||
durationNano []uint64
|
||||
hasError []bool
|
||||
hasExceptionEvent []bool
|
||||
hasLink []bool
|
||||
// Each distinct string is stored once in stringTable; these hold its index there.
|
||||
names []uint32
|
||||
services []uint32
|
||||
kinds []uint32
|
||||
responseStatusCodes []uint32
|
||||
statusCodeStrings []uint32
|
||||
statusMessages []uint32
|
||||
stringTable []string
|
||||
// references holds the stored references of a span that has more than the one to its parent.
|
||||
references map[int32]string
|
||||
// storedParentIDs holds the parent id of a root that has one: its parent is missing or on a loop.
|
||||
storedParentIDs map[int32]string
|
||||
// aiUsage holds the usage of the spans that carry any, by span position.
|
||||
aiUsage map[int32]AISpanUsage
|
||||
|
||||
// The children of span i are childList[childStart[i]:childStart[i+1]], in start time order.
|
||||
childStart []int32
|
||||
childList []int32
|
||||
roots []int32
|
||||
// treeOrder lists the spans as a waterfall shows them: a span, then everything below it.
|
||||
treeOrder []int32
|
||||
level []uint32
|
||||
// descendantCount is the number of spans below each span, at any depth.
|
||||
descendantCount []uint32
|
||||
ownTime []uint64
|
||||
// groupOf is the index in groups of the group a span belongs to.
|
||||
groupOf []int32
|
||||
groups []siblingGroup
|
||||
}
|
||||
|
||||
// TraceSkeletonBuilder collects the rows of a trace. They must be added in start time order.
|
||||
type TraceSkeletonBuilder struct {
|
||||
skeleton *TraceSkeleton
|
||||
ids []byte
|
||||
parentIDs []string
|
||||
stringIndex map[string]uint32
|
||||
}
|
||||
|
||||
func NewTraceSkeletonBuilder(traceID string, sizeHint int) *TraceSkeletonBuilder {
|
||||
return &TraceSkeletonBuilder{
|
||||
skeleton: &TraceSkeleton{
|
||||
traceID: traceID,
|
||||
idOffsets: make([]uint32, 1, sizeHint+1),
|
||||
parents: make([]int32, 0, sizeHint),
|
||||
startNano: make([]int64, 0, sizeHint),
|
||||
durationNano: make([]uint64, 0, sizeHint),
|
||||
hasError: make([]bool, 0, sizeHint),
|
||||
hasExceptionEvent: make([]bool, 0, sizeHint),
|
||||
hasLink: make([]bool, 0, sizeHint),
|
||||
names: make([]uint32, 0, sizeHint),
|
||||
services: make([]uint32, 0, sizeHint),
|
||||
kinds: make([]uint32, 0, sizeHint),
|
||||
responseStatusCodes: make([]uint32, 0, sizeHint),
|
||||
statusCodeStrings: make([]uint32, 0, sizeHint),
|
||||
statusMessages: make([]uint32, 0, sizeHint),
|
||||
references: make(map[int32]string),
|
||||
storedParentIDs: make(map[int32]string),
|
||||
aiUsage: make(map[int32]AISpanUsage),
|
||||
},
|
||||
ids: make([]byte, 0, sizeHint*16),
|
||||
parentIDs: make([]string, 0, sizeHint),
|
||||
stringIndex: make(map[string]uint32),
|
||||
}
|
||||
}
|
||||
|
||||
func (builder *TraceSkeletonBuilder) Add(span *SkeletonSpan) {
|
||||
skeleton := builder.skeleton
|
||||
if span.AIUsage.hasValue() {
|
||||
skeleton.aiUsage[int32(len(builder.parentIDs))] = span.AIUsage
|
||||
}
|
||||
if span.OtherReferences != "" {
|
||||
skeleton.references[int32(len(builder.parentIDs))] = span.OtherReferences
|
||||
}
|
||||
builder.ids = append(builder.ids, span.SpanID...)
|
||||
skeleton.idOffsets = append(skeleton.idOffsets, uint32(len(builder.ids)))
|
||||
builder.parentIDs = append(builder.parentIDs, span.ParentSpanID)
|
||||
skeleton.startNano = append(skeleton.startNano, span.StartTime.UnixNano())
|
||||
skeleton.durationNano = append(skeleton.durationNano, span.DurationNano)
|
||||
skeleton.hasError = append(skeleton.hasError, span.HasError)
|
||||
skeleton.hasExceptionEvent = append(skeleton.hasExceptionEvent, span.HasExceptionEvent)
|
||||
skeleton.hasLink = append(skeleton.hasLink, span.HasLink)
|
||||
skeleton.names = append(skeleton.names, builder.intern(span.Name))
|
||||
skeleton.services = append(skeleton.services, builder.intern(span.ServiceName))
|
||||
skeleton.kinds = append(skeleton.kinds, builder.intern(span.KindString))
|
||||
skeleton.responseStatusCodes = append(skeleton.responseStatusCodes, builder.intern(span.ResponseStatusCode))
|
||||
skeleton.statusCodeStrings = append(skeleton.statusCodeStrings, builder.intern(span.StatusCodeString))
|
||||
skeleton.statusMessages = append(skeleton.statusMessages, builder.intern(span.StatusMessage))
|
||||
}
|
||||
|
||||
// Build turns the added rows into the tree. The builder cannot be reused.
|
||||
func (builder *TraceSkeletonBuilder) Build() *TraceSkeleton {
|
||||
skeleton := builder.skeleton
|
||||
skeleton.spanIDs = string(builder.ids)
|
||||
n := len(builder.parentIDs)
|
||||
|
||||
// A span whose parent is not in the trace, or is the span itself, becomes a root.
|
||||
positions := make(map[string]int32, n)
|
||||
for i := range n {
|
||||
positions[skeleton.spanID(int32(i))] = int32(i)
|
||||
}
|
||||
for i, parentID := range builder.parentIDs {
|
||||
parent, ok := positions[parentID]
|
||||
if !ok || parent == int32(i) {
|
||||
parent = noParent
|
||||
if parentID != "" {
|
||||
skeleton.storedParentIDs[int32(i)] = parentID
|
||||
}
|
||||
}
|
||||
skeleton.parents = append(skeleton.parents, parent)
|
||||
}
|
||||
builder.parentIDs, builder.stringIndex, builder.ids = nil, nil, nil
|
||||
|
||||
skeleton.linkChildren()
|
||||
if skeleton.walkFromRoots() < n {
|
||||
skeleton.cutParentLoops()
|
||||
skeleton.linkChildren()
|
||||
skeleton.walkFromRoots()
|
||||
}
|
||||
|
||||
// Walking the tree order backwards reaches every span after all the spans below it.
|
||||
skeleton.descendantCount = make([]uint32, n)
|
||||
for k := n - 1; k >= 0; k-- {
|
||||
i := skeleton.treeOrder[k]
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.descendantCount[parent] += skeleton.descendantCount[i] + 1
|
||||
}
|
||||
}
|
||||
|
||||
skeleton.ownTime = make([]uint64, n)
|
||||
for i := range n {
|
||||
skeleton.ownTime[i] = skeleton.durationNano[i] - skeleton.timeCoveredByChildren(int32(i))
|
||||
}
|
||||
|
||||
skeleton.groupSameNameSiblings()
|
||||
return skeleton
|
||||
}
|
||||
|
||||
// siblingGroup totals the spans that share a name and a parent; a root is a group of its own.
|
||||
type siblingGroup struct {
|
||||
spanCount uint64
|
||||
ownTime uint64
|
||||
errCount uint64
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) len() int {
|
||||
return len(skeleton.parents)
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanID(i int32) string {
|
||||
return skeleton.spanIDs[skeleton.idOffsets[i]:skeleton.idOffsets[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) children(i int32) []int32 {
|
||||
return skeleton.childList[skeleton.childStart[i]:skeleton.childStart[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) parentSpanID(i int32) string {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
return skeleton.spanID(parent)
|
||||
}
|
||||
return skeleton.storedParentIDs[i]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanReferences(i int32) []OtelSpanRef {
|
||||
stored, ok := skeleton.references[i]
|
||||
if !ok {
|
||||
return []OtelSpanRef{{TraceId: skeleton.traceID, SpanId: skeleton.parentSpanID(i), RefType: refTypeChildOf}}
|
||||
}
|
||||
refs := []OtelSpanRef{}
|
||||
if err := json.Unmarshal([]byte(stored), &refs); err != nil {
|
||||
return []OtelSpanRef{} // skip malformed values
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
// unmarkedFailureKind is set for a span that reports a failure without the error flag. The response
|
||||
// status column holds an HTTP status or a gRPC status.
|
||||
func (skeleton *TraceSkeleton) unmarkedFailureKind(i int32) UnmarkedFailureKind {
|
||||
if skeleton.hasError[i] {
|
||||
return ""
|
||||
}
|
||||
if code, err := strconv.Atoi(skeleton.stringTable[skeleton.responseStatusCodes[i]]); err == nil {
|
||||
switch {
|
||||
case code >= 400 && code < 500:
|
||||
return UnmarkedFailureHTTP4xx
|
||||
case code >= 500 && code < 600:
|
||||
return UnmarkedFailureHTTP5xx
|
||||
case code >= 1 && code <= 16:
|
||||
return UnmarkedFailureGRPCStatus
|
||||
}
|
||||
}
|
||||
if skeleton.hasExceptionEvent[i] {
|
||||
return UnmarkedFailureExceptionEvent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) treeStats(i int32) SpanTreeStats {
|
||||
stats := SpanTreeStats{
|
||||
Level: skeleton.level[i],
|
||||
ChildCount: uint32(len(skeleton.children(i))),
|
||||
SubtreeSpanCount: skeleton.descendantCount[i],
|
||||
OwnTimeNano: skeleton.ownTime[i],
|
||||
}
|
||||
for p := skeleton.parents[i]; p != noParent && skeleton.hasError[p]; p = skeleton.parents[p] {
|
||||
stats.ErrorAncestorCount++
|
||||
}
|
||||
if group := skeleton.groups[skeleton.groupOf[i]]; group.spanCount > 1 {
|
||||
stats.SameNameSiblings = &SameNameSiblingStats{SpanCount: group.spanCount, OwnTimeNano: group.ownTime, ErrorSpanCount: group.errCount}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// serviceStats totals the spans of each service, the service with the most own time first.
|
||||
func (skeleton *TraceSkeleton) serviceStats() []TraceServiceStats {
|
||||
services := make([]TraceServiceStats, 0)
|
||||
positionOf := make(map[uint32]int)
|
||||
for i := range int32(skeleton.len()) {
|
||||
position, ok := positionOf[skeleton.services[i]]
|
||||
if !ok {
|
||||
position = len(services)
|
||||
positionOf[skeleton.services[i]] = position
|
||||
services = append(services, TraceServiceStats{ServiceName: skeleton.stringTable[skeleton.services[i]]})
|
||||
}
|
||||
services[position].SpanCount++
|
||||
services[position].OwnTimeNano += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
services[position].ErrorSpanCount++
|
||||
}
|
||||
}
|
||||
slices.SortFunc(services, func(a, b TraceServiceStats) int {
|
||||
return cmp.Or(cmp.Compare(b.OwnTimeNano, a.OwnTimeNano), strings.Compare(a.ServiceName, b.ServiceName))
|
||||
})
|
||||
return services
|
||||
}
|
||||
|
||||
func (usage AISpanUsage) hasValue() bool {
|
||||
return usage.InputTokens != nil || usage.OutputTokens != nil || usage.CacheReadTokens != nil ||
|
||||
usage.CacheWriteTokens != nil || usage.ReasoningTokens != nil || usage.Cost != nil
|
||||
}
|
||||
|
||||
// intern returns the index of value in the string table, adding it on first sight.
|
||||
func (builder *TraceSkeletonBuilder) intern(value string) uint32 {
|
||||
if idx, ok := builder.stringIndex[value]; ok {
|
||||
return idx
|
||||
}
|
||||
idx := uint32(len(builder.skeleton.stringTable))
|
||||
builder.skeleton.stringTable = append(builder.skeleton.stringTable, value)
|
||||
builder.stringIndex[value] = idx
|
||||
return idx
|
||||
}
|
||||
|
||||
// linkChildren fills roots, childStart and childList from parents: it counts the children of
|
||||
// every span, turns the counts into start offsets, then places each child.
|
||||
func (skeleton *TraceSkeleton) linkChildren() {
|
||||
n := skeleton.len()
|
||||
skeleton.childStart = make([]int32, n+1)
|
||||
skeleton.roots = skeleton.roots[:0]
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childStart[parent+1]++
|
||||
} else {
|
||||
skeleton.roots = append(skeleton.roots, int32(i))
|
||||
}
|
||||
}
|
||||
for i := range n {
|
||||
skeleton.childStart[i+1] += skeleton.childStart[i]
|
||||
}
|
||||
skeleton.childList = make([]int32, skeleton.childStart[n])
|
||||
next := slices.Clone(skeleton.childStart[:n])
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childList[next[parent]] = int32(i)
|
||||
next[parent]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// walkFromRoots fills treeOrder and level, and returns the number of spans it reached.
|
||||
func (skeleton *TraceSkeleton) walkFromRoots() int {
|
||||
n := skeleton.len()
|
||||
skeleton.treeOrder = make([]int32, 0, n)
|
||||
skeleton.level = make([]uint32, n)
|
||||
// Pushed in reverse, the earliest root and the earliest child are popped first.
|
||||
stack := make([]int32, 0, 64)
|
||||
for r := len(skeleton.roots) - 1; r >= 0; r-- {
|
||||
stack = append(stack, skeleton.roots[r])
|
||||
}
|
||||
for len(stack) > 0 {
|
||||
i := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
skeleton.treeOrder = append(skeleton.treeOrder, i)
|
||||
children := skeleton.children(i)
|
||||
for c := len(children) - 1; c >= 0; c-- {
|
||||
skeleton.level[children[c]] = skeleton.level[i] + 1
|
||||
stack = append(stack, children[c])
|
||||
}
|
||||
}
|
||||
return len(skeleton.treeOrder)
|
||||
}
|
||||
|
||||
// cutParentLoops handles spans no root reaches: they sit on a loop of parents (a under b, b under
|
||||
// a) or below one. The earliest unreached span of each loop becomes a root.
|
||||
func (skeleton *TraceSkeleton) cutParentLoops() {
|
||||
reached := make([]bool, skeleton.len())
|
||||
for _, i := range skeleton.treeOrder {
|
||||
reached[i] = true
|
||||
}
|
||||
for i := range int32(skeleton.len()) {
|
||||
if reached[i] {
|
||||
continue
|
||||
}
|
||||
skeleton.storedParentIDs[i] = skeleton.spanID(skeleton.parents[i])
|
||||
skeleton.parents[i] = noParent
|
||||
stack := []int32{i}
|
||||
for len(stack) > 0 {
|
||||
top := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
if !reached[top] {
|
||||
reached[top] = true
|
||||
stack = append(stack, skeleton.children(top)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// timeCoveredByChildren is the time of span i during which a child was running. Overlapping
|
||||
// children count once, and child time outside the span does not count.
|
||||
func (skeleton *TraceSkeleton) timeCoveredByChildren(i int32) uint64 {
|
||||
start := skeleton.startNano[i]
|
||||
end := start + int64(skeleton.durationNano[i])
|
||||
covered, cursor := int64(0), start
|
||||
for _, child := range skeleton.children(i) {
|
||||
childStart := max(skeleton.startNano[child], cursor)
|
||||
childEnd := min(skeleton.startNano[child]+int64(skeleton.durationNano[child]), end)
|
||||
if childEnd <= childStart {
|
||||
continue
|
||||
}
|
||||
covered += childEnd - childStart
|
||||
cursor = childEnd
|
||||
}
|
||||
return uint64(covered)
|
||||
}
|
||||
|
||||
// groupSameNameSiblings fills groups and groupOf: one group per name among the children of a span.
|
||||
func (skeleton *TraceSkeleton) groupSameNameSiblings() {
|
||||
n := skeleton.len()
|
||||
skeleton.groupOf = make([]int32, n)
|
||||
skeleton.groups = make([]siblingGroup, 0, n)
|
||||
addGroup := func(members []int32) {
|
||||
group := siblingGroup{}
|
||||
for _, i := range members {
|
||||
skeleton.groupOf[i] = int32(len(skeleton.groups))
|
||||
group.spanCount++
|
||||
group.ownTime += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
group.errCount++
|
||||
}
|
||||
}
|
||||
skeleton.groups = append(skeleton.groups, group)
|
||||
}
|
||||
|
||||
for r := range skeleton.roots {
|
||||
addGroup(skeleton.roots[r : r+1])
|
||||
}
|
||||
var siblings []int32
|
||||
for parent := range int32(n) {
|
||||
// Sorting by name puts same-name siblings side by side; the stable sort keeps their time order.
|
||||
siblings = append(siblings[:0], skeleton.children(parent)...)
|
||||
slices.SortStableFunc(siblings, func(a, b int32) int { return int(skeleton.names[a]) - int(skeleton.names[b]) })
|
||||
for first := 0; first < len(siblings); {
|
||||
end := first + 1
|
||||
for end < len(siblings) && skeleton.names[siblings[end]] == skeleton.names[siblings[first]] {
|
||||
end++
|
||||
}
|
||||
addGroup(siblings[first:end])
|
||||
first = end
|
||||
}
|
||||
}
|
||||
}
|
||||
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
@@ -0,0 +1,325 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type skeletonSpec struct {
|
||||
id, parent, name, service string
|
||||
startMs, durationMs int64
|
||||
hasError, hasException bool
|
||||
hasLink bool
|
||||
usage AISpanUsage
|
||||
statusCode string
|
||||
references string
|
||||
}
|
||||
|
||||
// buildSkeleton adds the spans in the given order, which stands for the store's start time order.
|
||||
func buildSkeleton(specs ...skeletonSpec) *TraceSkeleton {
|
||||
builder := NewTraceSkeletonBuilder("trace", len(specs))
|
||||
for _, spec := range specs {
|
||||
span := &SkeletonSpan{
|
||||
Span: Span{
|
||||
SpanID: spec.id,
|
||||
ParentSpanID: spec.parent,
|
||||
DurationNano: uint64(spec.durationMs) * uint64(time.Millisecond),
|
||||
HasError: spec.hasError,
|
||||
Name: spec.name,
|
||||
KindString: "Internal",
|
||||
ResponseStatusCode: spec.statusCode,
|
||||
},
|
||||
StartTime: time.Unix(100, 0).Add(time.Duration(spec.startMs) * time.Millisecond),
|
||||
ServiceName: spec.service,
|
||||
HasExceptionEvent: spec.hasException,
|
||||
HasLink: spec.hasLink,
|
||||
OtherReferences: spec.references,
|
||||
AIUsage: spec.usage,
|
||||
}
|
||||
builder.Add(span)
|
||||
}
|
||||
return builder.Build()
|
||||
}
|
||||
|
||||
func spanIDsOf(skeleton *TraceSkeleton, positions []int32) []string {
|
||||
spanIDs := make([]string, 0, len(positions))
|
||||
for _, i := range positions {
|
||||
spanIDs = append(spanIDs, skeleton.spanID(i))
|
||||
}
|
||||
return spanIDs
|
||||
}
|
||||
|
||||
func positionOf(t *testing.T, skeleton *TraceSkeleton, spanID string) int32 {
|
||||
t.Helper()
|
||||
for i := range int32(skeleton.len()) {
|
||||
if skeleton.spanID(i) == spanID {
|
||||
return i
|
||||
}
|
||||
}
|
||||
require.FailNow(t, "span not in skeleton", spanID)
|
||||
return noParent
|
||||
}
|
||||
|
||||
func TestTraceSkeletonOwnTime(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expected int64
|
||||
}{
|
||||
{
|
||||
// time (ms) 0 10 30 50 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// b |--------------| 30 ms
|
||||
name: "SequentialChildren_SubtractsEach",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "b", parent: "root", startMs: 50, durationMs: 30},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Calls fanned out at once, such as parallel queries. Together they cover 10 to 60.
|
||||
// time (ms) 0 10 20 30 40 50 60 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |-------------------| 40 ms
|
||||
// b |-------------------| 40 ms
|
||||
// c |----| 10 ms
|
||||
name: "ParallelChildren_CountsOverlapOnce",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 40},
|
||||
{id: "b", parent: "root", startMs: 20, durationMs: 40},
|
||||
{id: "c", parent: "root", startMs: 30, durationMs: 10},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Work the parent starts and does not wait for, such as a background job.
|
||||
// time (ms) 0 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |--------------> 500 ms, 20 of them inside root
|
||||
name: "ChildOutlivesParent_ClipsToParentEnd",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 80, durationMs: 500},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew: the child's host clock runs behind the parent's.
|
||||
// time (ms) 0 10 30 110
|
||||
// early |--------------| 30 ms, 20 of them inside root
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildStartsBeforeParent_ClipsToParentStart",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 30},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew again, with a child that also runs past the parent's end.
|
||||
// time (ms) 0 10 110
|
||||
// early |-----------------------------------------------------------> 500 ms
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildCoversParent_LeavesZero",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 500},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
// Only direct children count: a1 is taken from the time of a, not of root.
|
||||
// time (ms) 0 10 30 90 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// a1 |------------------------------------| 75 ms, child of a
|
||||
name: "Grandchild_NotSubtracted",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "a1", parent: "a", startMs: 15, durationMs: 75},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
name: "NoChildren_EqualsDuration",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 70},
|
||||
},
|
||||
expected: 70,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, uint64(testCase.expected)*uint64(time.Millisecond), skeleton.ownTime[positionOf(t, skeleton, "root")])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTree(t *testing.T) {
|
||||
// root 0 to 100
|
||||
// a 10 to 40
|
||||
// a1 15 to 20, error
|
||||
// b 50 to 60
|
||||
// orphan 60 to 70; its parent is not in the trace, so it is a second root
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", service: "web", startMs: 0, durationMs: 100},
|
||||
skeletonSpec{id: "a", parent: "root", name: "a", service: "web", startMs: 10, durationMs: 30},
|
||||
skeletonSpec{id: "a1", parent: "a", name: "a1", service: "db", startMs: 15, durationMs: 5, hasError: true},
|
||||
skeletonSpec{id: "b", parent: "root", name: "b", service: "web", startMs: 50, durationMs: 10},
|
||||
skeletonSpec{id: "orphan", parent: "gone", name: "orphan", service: "worker", startMs: 60, durationMs: 10},
|
||||
)
|
||||
|
||||
assert.Equal(t, []string{"root", "a", "a1", "b", "orphan"}, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
assert.Equal(t, []string{"root", "orphan"}, spanIDsOf(skeleton, skeleton.roots))
|
||||
// root: two children, three spans below it, and 100 less the 30 of a and the 10 of b.
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, ChildCount: 2, SubtreeSpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "root")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 2, OwnTimeNano: uint64(5 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "a1")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, OwnTimeNano: uint64(10 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "orphan")))
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTreeStats(t *testing.T) {
|
||||
// root error
|
||||
// handler error
|
||||
// q1 SELECT, 10 ms
|
||||
// q2 SELECT, 30 ms, error
|
||||
// cache
|
||||
// evict error
|
||||
// q3 SELECT, 20 ms
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", startMs: 0, durationMs: 100, hasError: true},
|
||||
skeletonSpec{id: "handler", parent: "root", name: "handler", startMs: 0, durationMs: 90, hasError: true},
|
||||
skeletonSpec{id: "q1", parent: "handler", name: "SELECT", startMs: 0, durationMs: 10},
|
||||
skeletonSpec{id: "q2", parent: "handler", name: "SELECT", startMs: 10, durationMs: 30, hasError: true},
|
||||
skeletonSpec{id: "cache", parent: "handler", name: "GET cache", startMs: 40, durationMs: 5},
|
||||
skeletonSpec{id: "evict", parent: "cache", name: "evict", startMs: 41, durationMs: 2, hasError: true},
|
||||
skeletonSpec{id: "q3", parent: "handler", name: "SELECT", startMs: 50, durationMs: 20},
|
||||
)
|
||||
|
||||
// q2 has two error spans above it, and shares its name with q1 and q3.
|
||||
stats := skeleton.treeStats(positionOf(t, skeleton, "q2"))
|
||||
assert.Equal(t, uint32(2), stats.ErrorAncestorCount)
|
||||
require.NotNil(t, stats.SameNameSiblings)
|
||||
assert.Equal(t, SameNameSiblingStats{SpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond), ErrorSpanCount: 1}, *stats.SameNameSiblings)
|
||||
|
||||
cache := skeleton.treeStats(positionOf(t, skeleton, "cache"))
|
||||
assert.Nil(t, cache.SameNameSiblings)
|
||||
assert.Equal(t, uint32(2), cache.ErrorAncestorCount)
|
||||
|
||||
// The count stops at the first ancestor that is not an error: cache, the parent of evict.
|
||||
assert.Equal(t, uint32(0), skeleton.treeStats(positionOf(t, skeleton, "evict")).ErrorAncestorCount)
|
||||
}
|
||||
|
||||
func TestTraceSkeletonUnmarkedFailureKind(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
spec skeletonSpec
|
||||
expected UnmarkedFailureKind
|
||||
}{
|
||||
{name: "HTTP400_LowestClientError", spec: skeletonSpec{statusCode: "400"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP499_HighestClientError", spec: skeletonSpec{statusCode: "499"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP200_NotAFailure", spec: skeletonSpec{statusCode: "200"}},
|
||||
// Instrumentation should flag a 5xx as an error; proxies and hand-written spans often do not.
|
||||
{name: "HTTP500_LowestServerError", spec: skeletonSpec{statusCode: "500"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP599_HighestServerError", spec: skeletonSpec{statusCode: "599"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP600_NotAFailure", spec: skeletonSpec{statusCode: "600"}},
|
||||
{name: "GRPC1_LowestFailure", spec: skeletonSpec{statusCode: "1"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC16_HighestFailure", spec: skeletonSpec{statusCode: "16"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC0_OK", spec: skeletonSpec{statusCode: "0"}},
|
||||
{name: "ExceptionEvent_WithoutStatusCode", spec: skeletonSpec{hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "ExceptionEvent_WithSuccessStatusCode", spec: skeletonSpec{statusCode: "200", hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "StatusCodeAndExceptionEvent_ReportsStatusCode", spec: skeletonSpec{statusCode: "404", hasException: true}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "ErrorFlag_NeverUnmarked", spec: skeletonSpec{statusCode: "404", hasException: true, hasError: true}},
|
||||
{name: "NoSignal_NotAFailure", spec: skeletonSpec{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
testCase.spec.id = "span"
|
||||
skeleton := buildSkeleton(testCase.spec)
|
||||
assert.Equal(t, testCase.expected, skeleton.unmarkedFailureKind(0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No valid trace has a parent loop; it comes from instrumentation that reuses span ids. Every span
|
||||
// must still be listed once.
|
||||
func TestTraceSkeletonParentLoop(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expectedRoots []string
|
||||
expectedTreeOrder []string
|
||||
}{
|
||||
{
|
||||
// x is the earliest span of the loop, so it becomes a root; y and under-y stay below it.
|
||||
name: "TwoSpansPointAtEachOther",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 10},
|
||||
{id: "x", parent: "y", startMs: 1, durationMs: 5},
|
||||
{id: "y", parent: "x", startMs: 2, durationMs: 5},
|
||||
{id: "under-y", parent: "y", startMs: 3, durationMs: 1},
|
||||
},
|
||||
expectedRoots: []string{"root", "x"},
|
||||
expectedTreeOrder: []string{"root", "x", "y", "under-y"},
|
||||
},
|
||||
{
|
||||
name: "SpanIsItsOwnParent",
|
||||
specs: []skeletonSpec{
|
||||
{id: "self", parent: "self", startMs: 0, durationMs: 10},
|
||||
{id: "child", parent: "self", startMs: 1, durationMs: 5},
|
||||
},
|
||||
expectedRoots: []string{"self"},
|
||||
expectedTreeOrder: []string{"self", "child"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, testCase.expectedRoots, spanIDsOf(skeleton, skeleton.roots))
|
||||
assert.Equal(t, testCase.expectedTreeOrder, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonSpan_ParentAndReferences(t *testing.T) {
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root"},
|
||||
skeletonSpec{id: "child", parent: "root"},
|
||||
skeletonSpec{id: "linked", parent: "root", references: `[{"traceId":"trace","spanId":"root","refType":"CHILD_OF"},{"traceId":"other","spanId":"far","refType":"FOLLOWS_FROM"}]`},
|
||||
skeletonSpec{id: "orphan", parent: "gone"},
|
||||
// a and b are each other's parent; a, the earliest, becomes a root.
|
||||
skeletonSpec{id: "a", parent: "b"},
|
||||
skeletonSpec{id: "b", parent: "a"},
|
||||
)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
spanID string
|
||||
parentSpanID string
|
||||
references []OtelSpanRef
|
||||
}{
|
||||
{name: "NoStoredReferences_RebuiltFromTheParent", spanID: "child", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}}},
|
||||
{name: "StoredReferences_ReturnedAsStored", spanID: "linked", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}, {TraceId: "other", SpanId: "far", RefType: "FOLLOWS_FROM"}}},
|
||||
{name: "MissingParent_KeepsTheStoredParentID", spanID: "orphan", parentSpanID: "gone", references: []OtelSpanRef{{TraceId: "trace", SpanId: "gone", RefType: "CHILD_OF"}}},
|
||||
{name: "ParentLoop_KeepsTheStoredParentID", spanID: "a", parentSpanID: "b", references: []OtelSpanRef{{TraceId: "trace", SpanId: "b", RefType: "CHILD_OF"}}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
span := skeleton.span(positionOf(t, skeleton, testCase.spanID))
|
||||
assert.Equal(t, testCase.parentSpanID, span.ParentSpanID)
|
||||
assert.Equal(t, testCase.references, span.References)
|
||||
})
|
||||
}
|
||||
}
|
||||
186
pkg/types/spantypes/trace_span_list.go
Normal file
186
pkg/types/spantypes/trace_span_list.go
Normal file
@@ -0,0 +1,186 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"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")
|
||||
)
|
||||
|
||||
// SpanListPage is one page of a span list picked from the tree.
|
||||
type SpanListPage struct {
|
||||
skeleton *TraceSkeleton
|
||||
view SpanListView
|
||||
// total counts the spans the page was cut from.
|
||||
total uint64
|
||||
positions []int32
|
||||
}
|
||||
|
||||
// NewSpanList builds the items of a page.
|
||||
func NewSpanList(page *SpanListPage) *SpanList {
|
||||
skeleton := page.skeleton
|
||||
list := &SpanList{Total: page.total, Items: make([]SpanItem, 0, len(page.positions))}
|
||||
for _, i := range page.positions {
|
||||
item := SpanItem{Span: skeleton.span(i), TreeStats: skeleton.treeStats(i), UnmarkedFailureKind: skeleton.unmarkedFailureKind(i)}
|
||||
if page.view == SpanListViewAIUsage {
|
||||
skeleton.setUsageAttributes(&item.Span, i)
|
||||
}
|
||||
list.Items = append(list.Items, item)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func validateSpanListView(view SpanListView) error {
|
||||
if !slices.Contains(SpanListView("").Enum(), any(view)) {
|
||||
return errors.NewInvalidInputf(ErrCodeTraceSpansInvalidView, "invalid view %q, expected one of error_origins, unmarked_failures, time_spent, ai_usage, links", string(view))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pageLimit(name string, value, fallback int) (int, error) {
|
||||
switch {
|
||||
case value < 0 || value > spanListMaxLimit:
|
||||
return 0, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidLimit, "%s must be between 1 and %d, got %d", name, spanListMaxLimit, value)
|
||||
case value == 0:
|
||||
return fallback, nil
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// page cuts one page out of the spans of scope. A view keeps the ones of its kind, in its own order.
|
||||
func (skeleton *TraceSkeleton) page(scope []int32, view SpanListView, offset, limit int) *SpanListPage {
|
||||
positions := scope
|
||||
if view != "" {
|
||||
positions = skeleton.viewPositions(view, scope)
|
||||
}
|
||||
page := &SpanListPage{skeleton: skeleton, view: view, total: uint64(len(positions))}
|
||||
if offset < len(positions) {
|
||||
page.positions = positions[offset:min(offset+limit, len(positions))]
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// viewPositions lists the spans of scope that are in a view, in the order of the view.
|
||||
func (skeleton *TraceSkeleton) viewPositions(view SpanListView, scope []int32) []int32 {
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
return skeleton.spansWhere(scope, skeleton.errorStartsAt)
|
||||
case SpanListViewUnmarkedFailures:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.unmarkedFailureKind(i) != "" })
|
||||
case SpanListViewLinks:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.hasLink[i] })
|
||||
case SpanListViewTimeSpent:
|
||||
return skeleton.timeSpentSpans(scope)
|
||||
case SpanListViewAIUsage:
|
||||
return skeleton.aiUsageSpans(scope)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// errorStartsAt reports whether span i is an error span with no error span among its children.
|
||||
func (skeleton *TraceSkeleton) errorStartsAt(i int32) bool {
|
||||
return skeleton.hasError[i] && !slices.ContainsFunc(skeleton.children(i), func(child int32) bool { return skeleton.hasError[child] })
|
||||
}
|
||||
|
||||
// spansWhere lists the spans of scope that match, in start time order.
|
||||
func (skeleton *TraceSkeleton) spansWhere(scope []int32, match func(i int32) bool) []int32 {
|
||||
spans := make([]int32, 0)
|
||||
for _, i := range scope {
|
||||
if match(i) {
|
||||
spans = append(spans, i)
|
||||
}
|
||||
}
|
||||
slices.Sort(spans)
|
||||
return spans
|
||||
}
|
||||
|
||||
// timeSpentSpans lists one span for each sibling group in scope, its longest there, the group with
|
||||
// the most own time first. Equal groups fall back to span order, so that every page cuts the same ranking.
|
||||
func (skeleton *TraceSkeleton) timeSpentSpans(scope []int32) []int32 {
|
||||
longest := slices.Repeat([]int32{-1}, len(skeleton.groups))
|
||||
for _, i := range scope {
|
||||
group := skeleton.groupOf[i]
|
||||
if longest[group] < 0 || skeleton.durationNano[i] > skeleton.durationNano[longest[group]] {
|
||||
longest[group] = i
|
||||
}
|
||||
}
|
||||
spans := slices.DeleteFunc(longest, func(i int32) bool { return i < 0 })
|
||||
groupOwnTime := func(i int32) uint64 { return skeleton.groups[skeleton.groupOf[i]].ownTime }
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(groupOwnTime(b), groupOwnTime(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// aiUsageSpans lists the spans of scope that carry gen_ai usage by cost, or by tokens when none
|
||||
// of them carries a cost; equal spans fall back to span order.
|
||||
func (skeleton *TraceSkeleton) aiUsageSpans(scope []int32) []int32 {
|
||||
spans := skeleton.spansWhere(scope, func(i int32) bool {
|
||||
_, ok := skeleton.aiUsage[i]
|
||||
return ok
|
||||
})
|
||||
hasCost := slices.ContainsFunc(spans, func(i int32) bool { return skeleton.aiUsage[i].Cost != nil })
|
||||
weight := func(i int32) float64 {
|
||||
usage := skeleton.aiUsage[i]
|
||||
if hasCost {
|
||||
return floatValue(usage.Cost)
|
||||
}
|
||||
return floatValue(usage.InputTokens) + floatValue(usage.OutputTokens)
|
||||
}
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(weight(b), weight(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// span returns span i with service.name as its only resource attribute.
|
||||
func (skeleton *TraceSkeleton) span(i int32) Span {
|
||||
return Span{
|
||||
SpanID: skeleton.spanID(i),
|
||||
TraceID: skeleton.traceID,
|
||||
ParentSpanID: skeleton.parentSpanID(i),
|
||||
Name: skeleton.stringTable[skeleton.names[i]],
|
||||
KindString: skeleton.stringTable[skeleton.kinds[i]],
|
||||
TimeUnix: uint64(skeleton.startNano[i] / 1_000_000),
|
||||
DurationNano: skeleton.durationNano[i],
|
||||
HasError: skeleton.hasError[i],
|
||||
StatusCodeString: skeleton.stringTable[skeleton.statusCodeStrings[i]],
|
||||
StatusMessage: skeleton.stringTable[skeleton.statusMessages[i]],
|
||||
ResponseStatusCode: skeleton.stringTable[skeleton.responseStatusCodes[i]],
|
||||
Resource: map[string]string{"service.name": skeleton.stringTable[skeleton.services[i]]},
|
||||
Attributes: map[string]any{},
|
||||
Events: []Event{},
|
||||
References: skeleton.spanReferences(i),
|
||||
}
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) setUsageAttributes(span *Span, i int32) {
|
||||
usage := skeleton.aiUsage[i]
|
||||
for key, value := range map[string]*float64{
|
||||
aiobservabilitytypes.GenAIUsageInputTokens: usage.InputTokens,
|
||||
aiobservabilitytypes.GenAIUsageOutputTokens: usage.OutputTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheReadInputTokens: usage.CacheReadTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheCreationInputTokens: usage.CacheWriteTokens,
|
||||
aiobservabilitytypes.GenAIUsageReasoningOutputTokens: usage.ReasoningTokens,
|
||||
aiobservabilitytypes.SignozGenAITotalCost: usage.Cost,
|
||||
} {
|
||||
if value != nil {
|
||||
span.Attributes[key] = *value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func floatValue(value *float64) float64 {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return *value
|
||||
}
|
||||
87
pkg/types/spantypes/trace_span_list_test.go
Normal file
87
pkg/types/spantypes/trace_span_list_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
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 TestTraceSkeletonPage_Ranking(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
view SpanListView
|
||||
usage map[string]AISpanUsage
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
// own time: orphan 60, the two SELECTs 35 together, pay 30, root 20, then the 5s in start order.
|
||||
name: "TimeSpent_GroupsSameNameSiblings",
|
||||
view: SpanListViewTimeSpent,
|
||||
expected: []string{"orphan", "q2", "pay", "root", "grpc", "caught", "auth"},
|
||||
},
|
||||
{
|
||||
// grpc has tokens and no cost, so it ranks last.
|
||||
name: "AIUsage_ByCost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {Cost: value(0.01)}, "auth": {Cost: value(0.5)}, "grpc": {InputTokens: value(900)}},
|
||||
expected: []string{"auth", "q1", "grpc"},
|
||||
},
|
||||
{
|
||||
// auth carries no token or cost value, so it is not listed.
|
||||
name: "AIUsage_ByTokensWhenNoSpanHasACost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {InputTokens: value(10), OutputTokens: value(5)}, "q2": {InputTokens: value(100)}, "auth": {}},
|
||||
expected: []string{"q2", "q1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(testCase.usage)
|
||||
page := skeleton.page(skeleton.treeOrder, testCase.view, 0, 50)
|
||||
assert.Equal(t, testCase.expected, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(len(testCase.expected)), page.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonPage_CutsTheViewOfTheGivenSpans(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(nil)
|
||||
|
||||
// Among the children of root: the two SELECTs as one, then pay, then auth.
|
||||
page := skeleton.page(skeleton.children(positionOf(t, skeleton, "root")), SpanListViewTimeSpent, 1, 5)
|
||||
assert.Equal(t, []string{"pay", "auth"}, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(3), page.total)
|
||||
}
|
||||
|
||||
func TestNewSpanList_OnlyAIUsageCarriesUsageAttributes(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
skeleton := checkoutSkeleton(map[string]AISpanUsage{"q1": {InputTokens: value(120), OutputTokens: value(30), Cost: value(0.02)}})
|
||||
|
||||
usage := NewSpanList(skeleton.page(skeleton.treeOrder, SpanListViewAIUsage, 0, 50))
|
||||
require.Len(t, usage.Items, 1)
|
||||
assert.Equal(t, map[string]any{"gen_ai.usage.input_tokens": 120.0, "gen_ai.usage.output_tokens": 30.0, "signoz.gen_ai.usage.tokens.cost": 0.02}, usage.Items[0].Span.Attributes)
|
||||
|
||||
// The same span in any other list carries no attributes.
|
||||
for _, item := range NewSpanList(skeleton.page(skeleton.treeOrder, "", 0, 50)).Items {
|
||||
assert.Empty(t, item.Span.Attributes, item.Span.SpanID)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ type TraceStats struct {
|
||||
TotalErrorSpans uint64
|
||||
HasMissingSpans bool
|
||||
GenAISpanCount uint64
|
||||
LLMCallCount uint64
|
||||
ToolCallCount uint64
|
||||
Tokens TraceAITokens
|
||||
TotalCost *float64
|
||||
}
|
||||
@@ -31,7 +33,9 @@ type GettableTraceSummary struct {
|
||||
|
||||
// TraceAISummary is present when any span carries a gen_ai gate key.
|
||||
type TraceAISummary struct {
|
||||
Tokens TraceAITokens `json:"tokens" required:"true"`
|
||||
LLMCallCount uint64 `json:"llmCallCount" required:"true" description:"Spans with gen_ai.request.model."`
|
||||
ToolCallCount uint64 `json:"toolCallCount" required:"true" description:"Spans with gen_ai.tool.name."`
|
||||
Tokens TraceAITokens `json:"tokens" required:"true"`
|
||||
// TotalCost is omitted when no span carries a cost attribute.
|
||||
TotalCost *float64 `json:"totalCost,omitempty" nullable:"false"`
|
||||
}
|
||||
@@ -56,7 +60,7 @@ func NewGettableTraceSummary(stats *TraceStats) *GettableTraceSummary {
|
||||
HasMissingSpans: stats.HasMissingSpans,
|
||||
}
|
||||
if stats.GenAISpanCount > 0 {
|
||||
summary.AI = &TraceAISummary{Tokens: stats.Tokens, TotalCost: stats.TotalCost}
|
||||
summary.AI = &TraceAISummary{LLMCallCount: stats.LLMCallCount, ToolCallCount: stats.ToolCallCount, Tokens: stats.Tokens, TotalCost: stats.TotalCost}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
2
tests/fixtures/querier.py
vendored
2
tests/fixtures/querier.py
vendored
@@ -741,6 +741,7 @@ def build_heatmap_query(
|
||||
filter_expression: str | None = None,
|
||||
bucket_options: dict | None = None,
|
||||
step_interval: int = DEFAULT_STEP_INTERVAL,
|
||||
disabled: bool = False,
|
||||
) -> dict:
|
||||
"""Omitting bucket_options leaves the server's default log axis."""
|
||||
spec: dict[str, Any] = {
|
||||
@@ -748,6 +749,7 @@ def build_heatmap_query(
|
||||
"signal": signal,
|
||||
"stepInterval": step_interval,
|
||||
"aggregations": [{"expression": expression}],
|
||||
"disabled": disabled,
|
||||
}
|
||||
|
||||
if source:
|
||||
|
||||
7
tests/fixtures/traces.py
vendored
7
tests/fixtures/traces.py
vendored
@@ -184,16 +184,19 @@ class TracesEvent(ABC):
|
||||
name: str
|
||||
time_unix_nano: np.uint64
|
||||
attribute_map: dict[str, str]
|
||||
is_error: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
timestamp: datetime.datetime,
|
||||
attribute_map: dict[str, str] = {},
|
||||
is_error: bool = False,
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.time_unix_nano = np.uint64(int(timestamp.timestamp() * 1e9))
|
||||
self.attribute_map = attribute_map
|
||||
self.is_error = is_error
|
||||
|
||||
def np_arr(self) -> np.array:
|
||||
return np.array([self.name, self.time_unix_nano, json.dumps(self.attribute_map)])
|
||||
@@ -598,13 +601,15 @@ class Traces(ABC):
|
||||
)
|
||||
# DB shape per event: {"name", "timeUnixNano", "attributeMap"}. Must match
|
||||
# what the consume-layer parser in pkg/types/spantypes expects.
|
||||
# The collector writes isError only when it is set.
|
||||
self._events_db = [
|
||||
json.dumps(
|
||||
{
|
||||
"name": event.name,
|
||||
"timeUnixNano": int(event.time_unix_nano),
|
||||
"attributeMap": dict(event.attribute_map),
|
||||
},
|
||||
}
|
||||
| ({"isError": True} if event.is_error else {}),
|
||||
separators=(",", ":"),
|
||||
)
|
||||
for event in events
|
||||
|
||||
@@ -204,3 +204,21 @@ def test_logs_aggregate_multi_group_by(
|
||||
actual = {(row[0], row[1], row[2]) for row in data}
|
||||
expected = {(service, env, count) for (service, env), count in pair_counts.items()}
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_time_series_bare_field_aggregation(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[build_scalar_query("A", "logs", [build_aggregation("attribute.quantity")])],
|
||||
)
|
||||
# only a heatmap buckets a bare field; elsewhere it reaches ClickHouse unaggregated
|
||||
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, response.text
|
||||
|
||||
@@ -7,10 +7,13 @@ import pytest
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.logs import Logs
|
||||
from fixtures.metrics import Metrics
|
||||
from fixtures.querier import (
|
||||
RequestType,
|
||||
assert_distribution_sums_heatmap,
|
||||
build_aggregation,
|
||||
build_builder_query,
|
||||
build_formula_query,
|
||||
build_group_by_field,
|
||||
build_heatmap_query,
|
||||
build_linear_bucket_options,
|
||||
@@ -22,6 +25,7 @@ from fixtures.querier import (
|
||||
get_error_message,
|
||||
get_heatmap_columns,
|
||||
index_series_by_label,
|
||||
make_preview_query_request,
|
||||
make_query_request,
|
||||
)
|
||||
|
||||
@@ -205,3 +209,287 @@ def test_heatmap_rejections(
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert expected_message in get_error_message(response.json())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled_expression", ["attribute.quantity", "count()"], ids=["bare_field", "aggregation"])
|
||||
def test_disabled_query_without_formula(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_logs: Callable[[list[Logs]], None],
|
||||
disabled_expression: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
insert_logs(
|
||||
[
|
||||
Logs(
|
||||
timestamp=now - timedelta(seconds=index + 1),
|
||||
resources={"service.name": "heatmap-disabled-input"},
|
||||
attributes={"response_bytes": response_bytes, "quantity": quantity},
|
||||
body=f"served {response_bytes} bytes for {quantity} items",
|
||||
)
|
||||
for index, (response_bytes, quantity) in enumerate([(50, 3), (250, 7)])
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
start_ms = int((now - timedelta(minutes=5)).timestamp() * 1000)
|
||||
end_ms = int((now + timedelta(seconds=5)).timestamp() * 1000)
|
||||
drawn = build_heatmap_query(
|
||||
"A",
|
||||
"logs",
|
||||
"response_bytes",
|
||||
filter_expression="service.name = 'heatmap-disabled-input'",
|
||||
bucket_options=build_linear_bucket_options(1000, 10),
|
||||
)
|
||||
alone = make_query_request(signoz, token, start_ms, end_ms, [drawn], request_type=RequestType.HEATMAP)
|
||||
assert alone.status_code == HTTPStatus.OK, alone.text
|
||||
|
||||
# no formula reads the disabled query, so it does not run
|
||||
queries = [drawn, build_heatmap_query("B", "logs", disabled_expression, filter_expression="service.name = 'heatmap-disabled-input'", disabled=True)]
|
||||
response = make_query_request(signoz, token, start_ms, end_ms, queries, request_type=RequestType.HEATMAP)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert_distribution_sums_heatmap(signoz, token, start_ms, end_ms, queries, response)
|
||||
|
||||
data = response.json()
|
||||
assert [result["queryName"] for result in data["data"]["data"]["results"]] == ["A"]
|
||||
assert get_buckets(data, "A") == pytest.approx(get_buckets(alone.json(), "A"))
|
||||
assert [column["values"] for column in get_heatmap_columns(data, "A")] == [column["values"] for column in get_heatmap_columns(alone.json(), "A")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_type", [RequestType.HEATMAP, RequestType.DISTRIBUTION], ids=["heatmap", "distribution"])
|
||||
@pytest.mark.parametrize("expression", ["response_bytes", "avg(response_bytes)"], ids=["bare_field", "aggregation"])
|
||||
def test_formula_over_logs_query(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
expression: str,
|
||||
request_type: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[
|
||||
build_heatmap_query("A", "logs", expression, disabled=True),
|
||||
build_formula_query("F1", "A * 2"),
|
||||
],
|
||||
request_type=request_type,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert 'formula "F1" reads logs or traces query "A", but logs and traces heatmaps do not support formulas' in get_error_message(response.json())
|
||||
|
||||
|
||||
MIXED_SERVICE = "heatmap-mixed-signals"
|
||||
MIXED_METRIC = "test_heatmap_mixed_signals"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_type", [RequestType.HEATMAP, RequestType.DISTRIBUTION], ids=["heatmap", "distribution"])
|
||||
def test_mixed_signals_both_enabled(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
request_type: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[
|
||||
build_heatmap_query("A", "logs", "response_bytes"),
|
||||
build_builder_query("B", MIXED_METRIC, "max", "max"),
|
||||
],
|
||||
request_type=request_type,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert f"{request_type} requests take one enabled query, but 2 are enabled" in get_error_message(response.json())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_type", [RequestType.HEATMAP, RequestType.DISTRIBUTION], ids=["heatmap", "distribution"])
|
||||
def test_formula_over_mixed_signals(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
request_type: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[
|
||||
build_heatmap_query("A", "logs", "response_bytes", disabled=True),
|
||||
build_builder_query("B", MIXED_METRIC, "max", "max", disabled=True),
|
||||
build_formula_query("F1", "A + B"),
|
||||
],
|
||||
request_type=request_type,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert 'formula "F1" reads logs or traces query "A", but logs and traces heatmaps do not support formulas' in get_error_message(response.json())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hidden_formula", [False, True], ids=["no_formula", "hidden_formula"])
|
||||
@pytest.mark.parametrize("drawn", ["A", "B"], ids=["logs_drawn", "metrics_drawn"])
|
||||
def test_mixed_signals_one_drawn(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_logs: Callable[[list[Logs]], None],
|
||||
insert_metrics: Callable[[list[Metrics]], None],
|
||||
drawn: str,
|
||||
hidden_formula: bool,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
insert_logs(
|
||||
[
|
||||
Logs(
|
||||
timestamp=now - timedelta(seconds=index + 1),
|
||||
resources={"service.name": MIXED_SERVICE},
|
||||
attributes={"response_bytes": response_bytes},
|
||||
body=f"served {response_bytes} bytes",
|
||||
)
|
||||
for index, response_bytes in enumerate([50, 250, 650])
|
||||
]
|
||||
)
|
||||
insert_metrics(
|
||||
[
|
||||
Metrics(
|
||||
metric_name=MIXED_METRIC,
|
||||
labels={"host": host},
|
||||
timestamp=now - timedelta(minutes=minute + 1),
|
||||
value=value,
|
||||
type_="Gauge",
|
||||
is_monotonic=False,
|
||||
)
|
||||
for host, value in {"host-a": 120, "host-b": 480}.items()
|
||||
for minute in range(3)
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
start_ms = int((now - timedelta(minutes=5)).timestamp() * 1000)
|
||||
end_ms = int((now + timedelta(seconds=5)).timestamp() * 1000)
|
||||
bucket_options = build_linear_bucket_options(1000, 10)
|
||||
by_name = {
|
||||
"A": build_heatmap_query("A", "logs", "response_bytes", filter_expression=f"service.name = '{MIXED_SERVICE}'", bucket_options=bucket_options, disabled=drawn != "A"),
|
||||
"B": build_builder_query("B", MIXED_METRIC, "max", "max", group_by=["host"], bucket_options=bucket_options, disabled=drawn != "B"),
|
||||
}
|
||||
alone = make_query_request(signoz, token, start_ms, end_ms, [by_name[drawn]], request_type=RequestType.HEATMAP)
|
||||
assert alone.status_code == HTTPStatus.OK, alone.text
|
||||
assert get_all_series(alone.json(), drawn), f"{drawn} drew nothing on its own"
|
||||
|
||||
# the other signal's query is disabled and no enabled formula reads it, so
|
||||
# it does not run; a hidden formula over it is neither run nor checked
|
||||
hidden = "B" if drawn == "A" else "A"
|
||||
queries = list(by_name.values())
|
||||
if hidden_formula:
|
||||
queries.append(build_formula_query("F1", f"{hidden} * 2", disabled=True))
|
||||
response = make_query_request(signoz, token, start_ms, end_ms, queries, request_type=RequestType.HEATMAP)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert_distribution_sums_heatmap(signoz, token, start_ms, end_ms, queries, response)
|
||||
|
||||
data = response.json()
|
||||
assert [result["queryName"] for result in data["data"]["data"]["results"]] == [drawn]
|
||||
assert data["data"]["data"]["results"] == alone.json()["data"]["data"]["results"]
|
||||
|
||||
|
||||
def test_metrics_formula_with_unread_logs_query(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_metrics: Callable[[list[Metrics]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
insert_metrics(
|
||||
[
|
||||
Metrics(
|
||||
metric_name=MIXED_METRIC,
|
||||
labels={"host": host},
|
||||
timestamp=now - timedelta(minutes=minute + 1),
|
||||
value=value,
|
||||
type_="Gauge",
|
||||
is_monotonic=False,
|
||||
)
|
||||
for host, value in {"host-a": 120, "host-b": 480}.items()
|
||||
for minute in range(3)
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
start_ms = int((now - timedelta(minutes=5)).timestamp() * 1000)
|
||||
end_ms = int((now + timedelta(seconds=5)).timestamp() * 1000)
|
||||
metrics_only = [
|
||||
build_builder_query("B", MIXED_METRIC, "max", "max", group_by=["host"], disabled=True),
|
||||
build_formula_query("F1", "B * 2", bucket_options=build_linear_bucket_options(2000, 10)),
|
||||
]
|
||||
alone = make_query_request(signoz, token, start_ms, end_ms, metrics_only, request_type=RequestType.HEATMAP)
|
||||
assert alone.status_code == HTTPStatus.OK, alone.text
|
||||
assert get_all_series(alone.json(), "F1"), "F1 drew nothing over the metrics query alone"
|
||||
|
||||
# the formula reads only the metrics query, so the disabled logs query
|
||||
# beside it, bare field and all, does not run
|
||||
queries = [build_heatmap_query("A", "logs", "response_bytes", disabled=True), *metrics_only]
|
||||
response = make_query_request(signoz, token, start_ms, end_ms, queries, request_type=RequestType.HEATMAP)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert_distribution_sums_heatmap(signoz, token, start_ms, end_ms, queries, response)
|
||||
|
||||
data = response.json()
|
||||
assert [result["queryName"] for result in data["data"]["data"]["results"]] == ["F1"]
|
||||
assert get_buckets(data, "F1") == pytest.approx(get_buckets(alone.json(), "F1"))
|
||||
# a formula's series come back in no set order
|
||||
assert index_series_by_label(get_all_series(data, "F1"), "host") == index_series_by_label(get_all_series(alone.json(), "F1"), "host")
|
||||
|
||||
|
||||
def test_preview_reads_formula_inputs_off_the_whole_request(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_metrics: Callable[[list[Metrics]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
insert_metrics(
|
||||
[
|
||||
Metrics(
|
||||
metric_name=MIXED_METRIC,
|
||||
labels={"host": "host-a"},
|
||||
timestamp=now - timedelta(minutes=1),
|
||||
value=120,
|
||||
type_="Gauge",
|
||||
is_monotonic=False,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_preview_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[
|
||||
build_heatmap_query("A", "logs", "response_bytes", disabled=True),
|
||||
build_builder_query("B", MIXED_METRIC, "max", "max", disabled=True),
|
||||
build_formula_query("F1", "B * 2", bucket_options=build_linear_bucket_options(2000, 10)),
|
||||
],
|
||||
request_type=RequestType.HEATMAP,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
previews = response.json()["data"]["compositeQuery"]
|
||||
|
||||
# the formula reads B, so B runs and previews its statement even though it
|
||||
# is previewed on its own
|
||||
assert previews["B"]["valid"], previews["B"]
|
||||
assert previews["B"]["statements"], previews["B"]
|
||||
|
||||
# nothing reads A, so it does not run and has no statement
|
||||
assert previews["A"]["valid"], previews["A"]
|
||||
assert previews["A"]["statements"] == []
|
||||
assert 'query "A" is disabled and no enabled formula reads it, so it does not run' in previews["A"]["warnings"]
|
||||
|
||||
@@ -9,10 +9,12 @@ from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import (
|
||||
RequestType,
|
||||
assert_distribution_sums_heatmap,
|
||||
build_formula_query,
|
||||
build_heatmap_query,
|
||||
build_linear_bucket_options,
|
||||
build_log_bucket_options,
|
||||
get_buckets,
|
||||
get_error_message,
|
||||
get_heatmap_columns,
|
||||
make_query_request,
|
||||
)
|
||||
@@ -111,3 +113,73 @@ def test_span_attribute_heatmap(
|
||||
buckets = get_buckets(data, "A")
|
||||
assert buckets == pytest.approx([0.0, 10.0, 20.0, 30.0, 40.0, 50.0])
|
||||
assert [sum(column["values"][slot] for column in get_heatmap_columns(data, "A")) for slot in range(len(buckets) + 1)] == [0, 3, 0, 0, 0, 2, 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled_expression", ["db.rows_returned", "count()"], ids=["bare_field", "aggregation"])
|
||||
def test_disabled_query_without_formula(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
disabled_expression: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
insert_traces(
|
||||
[
|
||||
Traces(
|
||||
timestamp=now - timedelta(minutes=2, seconds=index),
|
||||
duration=duration,
|
||||
trace_id=TraceIdGenerator.trace_id(),
|
||||
span_id=TraceIdGenerator.span_id(),
|
||||
name="SELECT carts",
|
||||
kind=TracesKind.SPAN_KIND_CLIENT,
|
||||
resources={"service.name": "heatmap-disabled-input"},
|
||||
attributes={"db.rows_returned": 5},
|
||||
)
|
||||
for index, duration in enumerate([timedelta(milliseconds=5), timedelta(seconds=1)])
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
start_ms = int((now - timedelta(minutes=5)).timestamp() * 1000)
|
||||
end_ms = int(now.timestamp() * 1000)
|
||||
drawn = build_heatmap_query("A", "traces", "duration_nano", filter_expression="service.name = 'heatmap-disabled-input'", bucket_options=build_log_bucket_options(0))
|
||||
alone = make_query_request(signoz, token, start_ms, end_ms, [drawn], request_type=RequestType.HEATMAP)
|
||||
assert alone.status_code == HTTPStatus.OK, alone.text
|
||||
|
||||
# no formula reads the disabled query, so it does not run
|
||||
queries = [drawn, build_heatmap_query("B", "traces", disabled_expression, filter_expression="service.name = 'heatmap-disabled-input'", disabled=True)]
|
||||
response = make_query_request(signoz, token, start_ms, end_ms, queries, request_type=RequestType.HEATMAP)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert_distribution_sums_heatmap(signoz, token, start_ms, end_ms, queries, response)
|
||||
|
||||
data = response.json()
|
||||
assert [result["queryName"] for result in data["data"]["data"]["results"]] == ["A"]
|
||||
assert get_buckets(data, "A") == pytest.approx(get_buckets(alone.json(), "A"))
|
||||
assert [column["values"] for column in get_heatmap_columns(data, "A")] == [column["values"] for column in get_heatmap_columns(alone.json(), "A")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_type", [RequestType.HEATMAP, RequestType.DISTRIBUTION], ids=["heatmap", "distribution"])
|
||||
@pytest.mark.parametrize("expression", ["duration_nano", "avg(duration_nano)"], ids=["bare_field", "aggregation"])
|
||||
def test_formula_over_traces_query(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
expression: str,
|
||||
request_type: str,
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
int(now.timestamp() * 1000),
|
||||
[
|
||||
build_heatmap_query("A", "traces", expression, disabled=True),
|
||||
build_formula_query("F1", "A * 2"),
|
||||
],
|
||||
request_type=request_type,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
assert 'formula "F1" reads logs or traces query "A", but logs and traces heatmaps do not support formulas' in get_error_message(response.json())
|
||||
|
||||
@@ -119,6 +119,8 @@ def test_summary_ai_trace(
|
||||
assert summary["totalErrorSpansCount"] == 1
|
||||
assert summary["hasMissingSpans"] is False
|
||||
|
||||
assert summary["ai"]["llmCallCount"] == 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)
|
||||
|
||||
@@ -195,6 +197,8 @@ 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"]["llmCallCount"] == 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)
|
||||
|
||||
|
||||
81
tests/integration/tests/tracedetail/05_authz.py
Normal file
81
tests/integration/tests/tracedetail/05_authz.py
Normal file
@@ -0,0 +1,81 @@
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from wiremock.resources.mappings import Mapping
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import (
|
||||
USER_ADMIN_EMAIL,
|
||||
USER_ADMIN_PASSWORD,
|
||||
add_license,
|
||||
change_user_role,
|
||||
create_active_user,
|
||||
)
|
||||
from fixtures.role import transaction_group
|
||||
from fixtures.traces import TraceIdGenerator
|
||||
|
||||
user_password = "password123Z$"
|
||||
viewer_email = "tracedetail-viewer@telemetry.test"
|
||||
scoped_role = "tracedetail-scope-key-a"
|
||||
scoped_email = "tracedetail-scope-key-a@telemetry.test"
|
||||
logs_role = "tracedetail-logs-only"
|
||||
logs_email = "tracedetail-logs-only@telemetry.test"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
span_id = TraceIdGenerator.span_id()
|
||||
|
||||
routes = [
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/summary", None, id="summary"),
|
||||
pytest.param("POST", f"/api/v4/traces/{trace_id}/waterfall", {"selectedSpanId": "", "uncollapsedSpans": []}, id="waterfall"),
|
||||
pytest.param("POST", f"/api/v1/traces/{trace_id}/aggregations", {"aggregations": [{"field": {"name": "service.name", "fieldContext": "resource"}, "aggregation": "span_count"}]}, id="aggregations"),
|
||||
pytest.param("POST", f"/api/v3/traces/{trace_id}/flamegraph", {"selectedSpanId": ""}, id="flamegraph"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/thread", None, id="thread"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/highlights", None, id="highlights"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/spans", None, id="spans"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/spans/{span_id}", None, id="span"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/spans/{span_id}/children", None, id="children"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/spans/{span_id}/descendants", None, id="descendants"),
|
||||
pytest.param("GET", f"/api/v1/traces/{trace_id}/spans/{span_id}/ancestors", None, id="ancestors"),
|
||||
]
|
||||
|
||||
|
||||
def test_setup(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: types.Operation, # pylint: disable=unused-argument
|
||||
make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
|
||||
get_token: Callable[[str, str], str],
|
||||
create_role: Callable[..., str],
|
||||
) -> None:
|
||||
add_license(signoz, make_http_mocks, get_token)
|
||||
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
create_active_user(signoz, admin_token, email=viewer_email, role="signoz-viewer", password=user_password)
|
||||
|
||||
create_role(admin_token, scoped_role, [transaction_group("read", "telemetryresource", "traces", ["builder_query/signoz.workspace.key.id/key-a"])])
|
||||
scoped_user = create_active_user(signoz, admin_token, email=scoped_email, role="signoz-viewer", password=user_password)
|
||||
change_user_role(signoz, admin_token, scoped_user, "signoz-viewer", scoped_role)
|
||||
|
||||
create_role(admin_token, logs_role, [transaction_group("read", "telemetryresource", "logs", ["builder_query/*"])])
|
||||
logs_user = create_active_user(signoz, admin_token, email=logs_email, role="signoz-viewer", password=user_password)
|
||||
change_user_role(signoz, admin_token, logs_user, "signoz-viewer", logs_role)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("method", "path", "body"), routes)
|
||||
@pytest.mark.parametrize(
|
||||
("email", "allowed"),
|
||||
[(USER_ADMIN_EMAIL, True), (viewer_email, True), (scoped_email, False), (logs_email, False)],
|
||||
ids=["admin", "viewer", "traces_scoped_to_key", "logs_only"],
|
||||
)
|
||||
def test_routes_need_traces_read_on_every_trace(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
method: str,
|
||||
path: str,
|
||||
body: dict | None,
|
||||
email: str,
|
||||
allowed: bool,
|
||||
) -> None:
|
||||
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
|
||||
response = requests.request(method, signoz.self.host_configs["8080"].get(path), json=body, headers={"Authorization": f"Bearer {token}"}, timeout=10)
|
||||
assert (response.status_code != HTTPStatus.FORBIDDEN) == allowed, response.text
|
||||
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
@@ -0,0 +1,194 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
|
||||
|
||||
SPAN_LISTS = ("errorOrigins", "unmarkedFailures", "timeSpent", "aiUsage", "links")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_trace_highlights(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
other_trace_id = TraceIdGenerator.trace_id()
|
||||
names = ("root", "place_order", "charge_card", "inventory_http", "inventory_grpc", "render", "notify", "consume", "model", "tool")
|
||||
ids = {name: TraceIdGenerator.span_id() for name in names}
|
||||
gateway, orders, agent = (f"td-highlights-{service}-{attribute_backend}" for service in ("gateway", "orders", "agent"))
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(key: str, parent: str, name: str, service: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
|
||||
return Traces(
|
||||
timestamp=start + timedelta(milliseconds=offset_ms),
|
||||
duration=timedelta(milliseconds=duration_ms),
|
||||
trace_id=trace_id,
|
||||
span_id=ids[key],
|
||||
parent_span_id=ids[parent] if parent else "",
|
||||
name=name,
|
||||
resources={"service.name": service, "k8s.pod.name": f"{service}-0"},
|
||||
attribute_write_mode=write_mode,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
span("root", "", "POST /checkout", gateway, 0, 1000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.response.status_code": 500}),
|
||||
# the error is carried up from charge_card through place_order to the root
|
||||
span("place_order", "root", "place_order", orders, 10, 600, status_code=TracesStatusCode.STATUS_CODE_ERROR),
|
||||
span("charge_card", "place_order", "charge_card", orders, 20, 300, kind=TracesKind.SPAN_KIND_CLIENT, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="card declined", attributes={"payment.provider": "worldpay"}),
|
||||
# four failures that do not carry the error flag
|
||||
span("inventory_http", "place_order", "GET /inventory", orders, 330, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 404}),
|
||||
span("inventory_grpc", "place_order", "inventory.Check", orders, 380, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"rpc.grpc.status_code": 5}),
|
||||
span("render", "root", "render_receipt", gateway, 700, 50, events=[TracesEvent("exception", now, {"exception.message": "template missing, fell back"}, is_error=True)]),
|
||||
span("notify", "root", "POST /notify", gateway, 752, 5, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 503}),
|
||||
# a link out to another trace
|
||||
span("consume", "root", "consume order.created", orders, 760, 20, kind=TracesKind.SPAN_KIND_CONSUMER, links=[TracesLink(trace_id=other_trace_id, span_id="aaaaaaaaaaaaaaaa", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)]),
|
||||
span("model", "root", "chat gpt-4o-mini", agent, 800, 100, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"gen_ai.request.model": "gpt-4o-mini", "gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": 0.01}),
|
||||
span("tool", "root", "execute_tool", agent, 910, 30, attributes={"gen_ai.tool.name": "get_weather"}),
|
||||
]
|
||||
)
|
||||
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights"), headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# own time is the duration minus what the children cover
|
||||
assert [(service["serviceName"], service["spanCount"], service["errorSpanCount"], service["ownTimeNano"]) for service in highlights["services"]] == [
|
||||
(orders, 5, 2, 620_000_000),
|
||||
(gateway, 3, 1, 250_000_000),
|
||||
(agent, 2, 0, 130_000_000),
|
||||
]
|
||||
|
||||
# one entry for the error, at the span that threw it
|
||||
errors = highlights["errorOrigins"]
|
||||
assert errors["total"] == 1
|
||||
error = errors["items"][0]
|
||||
assert error["span"] == {
|
||||
"span_id": ids["charge_card"],
|
||||
"trace_id": trace_id,
|
||||
"parent_span_id": ids["place_order"],
|
||||
"name": "charge_card",
|
||||
"kind_string": "Client",
|
||||
"time_unix": int(start.timestamp()) * 1_000 + 20,
|
||||
"duration_nano": 300_000_000,
|
||||
"has_error": True,
|
||||
"status_code_string": "STATUS_CODE_ERROR",
|
||||
"status_message": "card declined",
|
||||
"response_status_code": "",
|
||||
"resource": {"service.name": orders},
|
||||
"attributes": {},
|
||||
"events": [],
|
||||
"references": [{"traceId": trace_id, "spanId": ids["place_order"], "refType": "CHILD_OF"}],
|
||||
}
|
||||
assert error["treeStats"] == {"level": 2, "childCount": 0, "subtreeSpanCount": 0, "ownTimeNano": 300_000_000, "errorAncestorCount": 2}
|
||||
assert "unmarkedFailureKind" not in error
|
||||
assert "matches" not in error
|
||||
|
||||
unmarked = highlights["unmarkedFailures"]
|
||||
assert unmarked["total"] == 4
|
||||
assert [(item["span"]["span_id"], item["unmarkedFailureKind"]) for item in unmarked["items"]] == [(ids["inventory_http"], "http_4xx"), (ids["inventory_grpc"], "grpc_status"), (ids["render"], "exception_event"), (ids["notify"], "http_5xx")]
|
||||
assert unmarked["items"][0]["span"]["response_status_code"] == "404"
|
||||
|
||||
links = highlights["links"]
|
||||
assert links["total"] == 1
|
||||
assert links["items"][0]["span"]["span_id"] == ids["consume"]
|
||||
assert {"traceId": other_trace_id, "spanId": "aaaaaaaaaaaaaaaa", "refType": "FOLLOWS_FROM"} in links["items"][0]["span"]["references"]
|
||||
|
||||
# no other list carries attributes
|
||||
ai_usage = highlights["aiUsage"]
|
||||
# the tool span carries no token or cost value, so it is not listed
|
||||
assert ai_usage["total"] == 1
|
||||
assert ai_usage["items"][0]["span"]["span_id"] == ids["model"]
|
||||
assert ai_usage["items"][0]["span"]["attributes"] == {"gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": pytest.approx(0.01)}
|
||||
|
||||
# every span is its own entry here, most own time first
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 10
|
||||
assert [item["span"]["span_id"] for item in time_spent["items"][:3]] == [ids["charge_card"], ids["place_order"], ids["root"]]
|
||||
assert time_spent["items"][0]["treeStats"]["ownTimeNano"] == 300_000_000
|
||||
assert "sameNameSiblings" not in time_spent["items"][0]["treeStats"]
|
||||
assert time_spent["items"][1]["treeStats"] == {"level": 1, "childCount": 3, "subtreeSpanCount": 3, "ownTimeNano": 220_000_000, "errorAncestorCount": 1}
|
||||
|
||||
# the totals of the trace are not here: they come from the summary route
|
||||
assert set(highlights) == {"services", *SPAN_LISTS}
|
||||
for name in SPAN_LISTS:
|
||||
for item in highlights[name]["items"]:
|
||||
assert item["span"]["events"] == [], name
|
||||
assert list(item["span"]["resource"]) == ["service.name"], name
|
||||
|
||||
|
||||
def test_trace_highlights_limits(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
root_id = TraceIdGenerator.span_id()
|
||||
resources = {"service.name": "td-highlights-limits"}
|
||||
start = now - timedelta(seconds=30)
|
||||
spans = [Traces(timestamp=start, duration=timedelta(seconds=20), trace_id=trace_id, span_id=root_id, name="POST /import", kind=TracesKind.SPAN_KIND_SERVER, resources=resources)]
|
||||
for i in range(150):
|
||||
failed = {"status_code": TracesStatusCode.STATUS_CODE_ERROR, "status_message": f"failure {i:03d}"} if i < 12 else {}
|
||||
spans.append(Traces(timestamp=start + timedelta(seconds=1, milliseconds=i * 10), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), parent_span_id=root_id, name="write_item", resources=resources, **failed))
|
||||
insert_traces(spans)
|
||||
|
||||
url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(url, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# the default: 10 spans of a list, with the total behind it
|
||||
assert highlights["errorOrigins"]["total"] == 12
|
||||
assert [item["span"]["status_message"] for item in highlights["errorOrigins"]["items"]] == [f"failure {i:03d}" for i in range(10)]
|
||||
assert highlights["aiUsage"] == {"total": 0, "items": []}
|
||||
|
||||
# the 150 same-name children are one entry of the timeSpent list, shown by one of them
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 2
|
||||
group = next(item for item in time_spent["items"] if item["span"]["name"] == "write_item")
|
||||
assert group["treeStats"]["sameNameSiblings"] == {"spanCount": 150, "ownTimeNano": 150 * 5_000_000, "errorSpanCount": 12}
|
||||
assert group["span"]["parent_span_id"] == root_id
|
||||
root = next(item for item in time_spent["items"] if item["span"]["span_id"] == root_id)
|
||||
assert root["treeStats"]["childCount"] == 150
|
||||
assert root["treeStats"]["subtreeSpanCount"] == 150
|
||||
|
||||
sized = requests.get(url, params={"limit": 3}, headers=headers, timeout=10).json()["data"]
|
||||
assert len(sized["errorOrigins"]["items"]) == 3
|
||||
assert sized["errorOrigins"]["total"] == 12
|
||||
|
||||
# the highest value accepted returns everything
|
||||
largest = requests.get(url, params={"limit": 1000}, headers=headers, timeout=10)
|
||||
assert largest.status_code == HTTPStatus.OK, largest.text
|
||||
assert len(largest.json()["data"]["errorOrigins"]["items"]) == 12
|
||||
|
||||
# views names the lists to return; the others are left out
|
||||
picked = requests.get(url, params={"views": ["error_origins", "time_spent"]}, headers=headers, timeout=10)
|
||||
assert picked.status_code == HTTPStatus.OK, picked.text
|
||||
assert set(picked.json()["data"]) == {"services", "errorOrigins", "timeSpent"}
|
||||
assert picked.json()["data"]["errorOrigins"]["total"] == 12
|
||||
assert picked.json()["data"]["timeSpent"]["total"] == 2
|
||||
|
||||
for params in ({"limit": 1001}, {"limit": -1}, {"views": "fastest"}, {"views": "all"}):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, f"{params}: {response.text}"
|
||||
|
||||
unknown = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/highlights"), headers=headers, timeout=10)
|
||||
assert unknown.status_code == HTTPStatus.NOT_FOUND, unknown.text
|
||||
Reference in New Issue
Block a user