Compare commits

...

13 Commits

Author SHA1 Message Date
nityanandagohain
255b6fa1ac feat(trace-details): build the span tree and the overview of the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect now returns the overview. Like the
  waterfall, each call loads the trace's spans with one narrow query and builds
  the tree in memory, with each span's own time, level and the number of spans
  below it. There is no cache and no cap on the number of spans.

  From the tree it returns:
  - identity, with per-service totals and gen_ai usage
  - the spans where each error started, failures not marked as errors, the
    slowest spans by own time, the most expensive gen_ai spans, span links
  - the tree: the first 50 spans, level by level from the root, in time order;
    a trace of up to 50 spans also carries each span's record when they fit

  Every list pages with its nextCursor, and every item carries the span's
  direct parent. A page loads only what its list needs. Span attributes are
  read from the JSON column when it is filled, without the feature flag.

  spanId, search and allSpans answer 501 until the next PRs.

  Refs SigNoz/nerve-pod#651
2026-11-19 21:49:28 +05:30
nityanandagohain
75686f4004 fix(trace-details): update the trace inspect contract for the tree and the span cap 2026-11-19 21:18:30 +05:30
nityanandagohain
2df97d39e2 feat(trace-details): add the API contract for the trace inspect endpoint
Adds GET /api/v1/traces/{traceID}/inspect to the API spec with its query
  parameters and response types. The handler answers 501 for now; the
  implementation follows in separate PRs (overview, open a span, search).

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

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

  Refs SigNoz/nerve-pod#651
2026-11-19 16:42:40 +05:30
Abhi kumar
f0370c6cc1 feat(query-builder): add a builder slot for AI queries (#13484)
#### Description

- AI queries get their own slot (`Query.builder_ai_query`), like
ClickHouse and PromQL.
- Composites from the API map AI queries into it; builder-only checks
accept AI queries.
- The provider and V2 editor edit and render the active slot.
- Nothing changes on the wire: AI still goes out as `builder` with
`builder_ai_query` envelopes.

#### Additional Information

- 2/4, stacked on #13483.
Closes https://github.com/SigNoz/pulse-pod/issues/582
2026-11-18 10:12:36 +00:00
Abhi kumar
b106d86bef fix(dashboard): drill into empty top list groups and add top list stories (#13629)
#### Description

- Adds Storybook stories for the top list panel: default, rank and
share, thresholds, the share-of-p99 warning, no data, and the editor's
Appearance section. Their plays check rows, rank and share columns,
threshold colours and the data warning.
- Drilling into an `(empty)` top list row now filters the missing group
as `NOT EXISTS`. Before, the null value was dropped and the explorer
showed every record (Greptile P1 on #13084).

#### Screenshots / Screen Recordings

Visual diff against the merge-base, dark and light:
https://claude.ai/artifact/QqtPhnEJQsksa3reCWV12d

401 pairs identical, 12 new (top list stories), 16 changed (Top List
card in the panel picker), 43 unrelated movers (clock tick, focus rings,
toast fades).

#### Additional Information

- Stacked on #13084.
- The pie and table panels drop null group values the same way; left for
a follow-up.
2026-11-18 08:56:33 +00:00
Naman Verma
d8c00a34b9 fix: only fetch last saved rule state history if restart hasn't been handled (#13634)
#### Description

This heavy clickhouse call is in no way needed all the time.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/740
Part of https://github.com/SigNoz/signoz/issues/11493
2026-11-18 08:44:49 +00:00
Abhi kumar
0d3eee5c78 refactor(dashboard): fold QueryMode into EQueryType (#13483)
#### Description

- Panel capabilities and definitions key on `EQueryType` instead of a
separate `QueryMode`.
- No behavior change.

#### Additional Information

- 1/4 of a stack splitting #13222.
2026-11-18 08:30:27 +00:00
Nityananda Gohain
9d5c5871cb fix(ai-o11y): return trace aggregate keys as number (#13525)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
## Description

- `/api/v1/ai_observability/fields/keys` returned the `trace.`
aggregates as `float64`, unlike every other numeric key, so
`fieldDataType=number` dropped them.
- Aggregates are now declared `number`, and
`FieldKeySelector.MatchesKey` treats `number`/`int64`/`float64` as one
family. The static-fields matcher in `telemetrymetadata` now reuses it
instead of keeping its
  own copy.
- Frontend default AI trace columns switch to `number` so their column
ids still match the keys endpoint. Otherwise the field selector offers
them again as not added.

  ## Issues closed by this PR

  Closes SigNoz/nerve-pod#639

  ## Additional Information

Concerns
* If the user have removed one of these columns in select fields, it
will appear again, user has to remove it once more.
* Since saved view is not released so not a problem if we merge this
before that goes out.
2026-11-18 04:43:28 +00:00
Pandey
f1f1b14f00 feat(tokenizer): raise default max tokens per user to 20 (#13632)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Raise `tokenizer.opaque.token.max_per_user` default from 5 to 20.
- MCP clients now authenticate through regular SigNoz sessions, so a
user with a few browsers and MCP clients exceeded 5 and had their oldest
session silently evicted.
- Bump `lastObservedAt` cache expected entries to match (1000 users ×
20); `MaxCost` already fits ~21.8k entries.

Co-authored-by: Vishal Sharma <makeavish786@gmail.com>
2026-11-17 21:04:02 +00:00
Tushar Vats
6480c786be test(ruler): wait for the org alertmanager before creating webhook channels (#13625)
#### Description

- The first ruler test of a session can fail: its rule fires before the
new org's alertmanager is registered (the next 5s sync), `PutAlerts`
fails silently and the ruler only resends after 1m, past the test's 30s
wait.
- `create_webhook_notification_channel` now waits for the org
alertmanager with `wait_for_alertmanager_sync`, as the alertmanager
suite already does.

#### Additional Information

- Seen in
https://github.com/SigNoz/signoz/actions/runs/44092243746/job/134070088185
(`test_threshold_above_at_least_once`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-17 19:07:56 +00:00
Abhi kumar
313de0a00c feat(dashboards): add plugin schema for top list panel (#13084)
#### Description

- Adds `signoz/TopListPanel`: ranks the top N groups by one value as
horizontal bars. Spec mirrors `NumberPanelSpec` (visualization,
formatting, comparison thresholds) plus `appearance` (rank, share, bar
color).
- Allowed query kinds: builder, composite, formula, trace operator and
ClickHouse SQL. PromQL is rejected, including inside a composite.
- Frontend panel and regenerated Orval types follow in #13086.
- Artifact:
https://claude.ai/artifact/QqtPhnEJQsksa3reCWV12d?sk=S0XuyygvJdC1QYsz7grKvA

---------

Co-authored-by: Naman Verma <naman.verma@signoz.io>
2026-11-17 18:18:55 +00:00
Swapnil Nakade
e972f26992 feat(serviceaccount): add resource def to update my service account r… (#13623)
#### Description
- add a resource def to `PUT /api/v1/service_accounts/me`, taking the
service account id from the caller's claims
- why? so the auditor records a service account renaming itself; it
wrote no audit event before
- a self update and an admin update of the same account record the same
resource id

#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/7
2026-11-17 14:42:01 +00:00
Vinicius Lourenço
42e84652bf fix(storybook): skip the 5s animation wait on stories with scrollbars (#13492)
#### Description

- OverlayScrollbars animates its scrollbars with `ScrollTimeline`, and
those animations never finish. Storybook waits up to 5s for animations
after every story, so each story with a scroll pane took 5s longer to
capture. `preview-head.html` now removes `ScrollTimeline`, and
OverlayScrollbars falls back to script.
- The `sbshot-visual-diff` skill now says to capture from `pnpm
storybook:build` and to turn off a11y checks during capture. Together
the dev server and the checks added 7 to 12s per story.

#### Additional Information

- CI time does not change: the test runner already skips the animation
wait.
2026-11-17 14:39:03 +00:00
241 changed files with 12276 additions and 2070 deletions

View File

@@ -18,7 +18,9 @@ tag <diff> <tag> <story-id>... # what the reviewer should look at
export <diff> --out <dir> # a static site, hostable
```
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. The frontend has **no `build-storybook` script**, only `storybook dev -p 6006`, so point `capture` at a dev server.
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. **Capture from a build**: `pnpm storybook:build` in `frontend` (about 2 minutes) writes `storybook-static/`. A dev server serves the preview module by module, which adds 5 to 10 seconds to every story and, with several stories at once, ends in `page.goto: Timeout 30000ms exceeded` retries.
Pass `--globals 'a11y.manual:!true'` to every `capture`. The a11y addon otherwise runs axe after every story, about 2 seconds each, and nothing it does shows in a shot.
## Cover the change with stories first
@@ -30,7 +32,7 @@ Then confirm it worked: the two runs' story counts should differ by exactly the
## Rules that are not optional
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next.
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next. A build made in each ref's worktree has none of this.
**Capture both themes: `--theme dark,light`.** Without it sbshot shoots the story's own default and everything lands in a single `default/` folder, so every regression in the other theme is invisible. Themes double the shot count, so scope with `--stories` or `--title`, never by dropping a theme.

View File

@@ -364,7 +364,7 @@ tokenizer:
interval: 1h
token:
# The maximum number of tokens a user can have. This limits the number of concurrent sessions a user can have.
max_per_user: 5
max_per_user: 20
##################### Flagger #####################
flagger:

View File

@@ -5527,6 +5527,7 @@ components:
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
signoz/TextPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
signoz/TopListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
propertyName: kind
oneOf:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
@@ -5541,6 +5542,7 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5556,6 +5558,7 @@ components:
- signoz/HeatmapPanel
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5737,6 +5740,21 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/TopListPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelSpec:
properties:
display:
@@ -6499,6 +6517,43 @@ components:
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
type: object
DashboardtypesTopListAppearance:
properties:
barColor:
description: Hex color of every bar; a matching background threshold overrides
it.
type: string
showRank:
description: Numbers each row by its position in the list.
type: boolean
showShare:
description: Shows each row's share of the listed rows' total.
type: boolean
required:
- barColor
type: object
DashboardtypesTopListPanelSpec:
properties:
appearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListAppearance'
description: Rank, share and bar color options.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the values.
thresholds:
description: Rules that recolor a row when its value compares to a threshold
as specified.
items:
$ref: '#/components/schemas/DashboardtypesComparisonThreshold'
nullable: true
type: array
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the rows are computed over.
type: object
DashboardtypesUpdatableDashboardV2:
properties:
image:
@@ -12625,6 +12680,19 @@ components:
minimum: 0
type: integer
type: object
SpantypesEventV2:
properties:
attributes:
additionalProperties: {}
type: object
isError:
type: boolean
name:
type: string
timeUnixNano:
minimum: 0
type: integer
type: object
SpantypesFieldContext:
enum:
- attribute
@@ -12737,6 +12805,19 @@ components:
required:
- aggregations
type: object
SpantypesGettableTraceInspection:
properties:
find:
$ref: '#/components/schemas/SpantypesTraceSpanList'
overview:
$ref: '#/components/schemas/SpantypesTraceOverview'
span:
$ref: '#/components/schemas/SpantypesTraceSpanDetail'
type:
$ref: '#/components/schemas/SpantypesInspectType'
required:
- type
type: object
SpantypesGettableTraceSummary:
properties:
ai:
@@ -12817,6 +12898,19 @@ components:
nullable: true
type: array
type: object
SpantypesInspectType:
enum:
- overview
- span
- find
type: string
SpantypesLink:
properties:
spanId:
type: string
traceId:
type: string
type: object
SpantypesOtelSpanRef:
properties:
refType:
@@ -13108,6 +13202,100 @@ components:
nullable: true
type: object
type: object
SpantypesSpanRecord:
properties:
attributes:
additionalProperties: {}
type: object
events:
items:
$ref: '#/components/schemas/SpantypesEventV2'
type: array
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
resource:
additionalProperties:
type: string
type: object
spanId:
type: string
statusCode:
type: string
statusMessage:
type: string
truncated:
items:
$ref: '#/components/schemas/SpantypesTruncatedField'
type: array
required:
- spanId
- statusCode
- statusMessage
- attributes
- resource
- events
- links
- truncated
type: object
SpantypesSpanSummary:
properties:
childCount:
minimum: 0
type: integer
durationNano:
minimum: 0
type: integer
hasError:
type: boolean
kind:
type: string
level:
minimum: 0
type: integer
name:
type: string
ownTimeNano:
minimum: 0
type: integer
parentSpanId:
type: string
responseStatusCode:
type: string
serviceName:
type: string
spanId:
type: string
startOffsetNano:
minimum: 0
type: integer
subtreeSpanCount:
minimum: 0
type: integer
required:
- spanId
- name
- serviceName
- kind
- startOffsetNano
- durationNano
- ownTimeNano
- hasError
- level
- childCount
- subtreeSpanCount
type: object
SpantypesSpanTextMatch:
properties:
field:
type: string
snippet:
type: string
required:
- field
- snippet
type: object
SpantypesThreadSpan:
properties:
attributes:
@@ -13174,6 +13362,23 @@ components:
- formattedOutput
- formatterWarnings
type: object
SpantypesTraceAIIdentity:
properties:
modelCallCount:
minimum: 0
type: integer
tokens:
$ref: '#/components/schemas/SpantypesTraceAITokens'
toolCallCount:
minimum: 0
type: integer
totalCost:
type: number
required:
- modelCallCount
- toolCallCount
- tokens
type: object
SpantypesTraceAISummary:
properties:
tokens:
@@ -13207,6 +13412,379 @@ components:
- cacheWrite
- reasoning
type: object
SpantypesTraceErrorItem:
properties:
errorAncestorCount:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
statusMessage:
type: string
required:
- span
- statusMessage
- errorAncestorCount
type: object
SpantypesTraceErrorList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceErrorItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceExpensiveItem:
properties:
cost:
type: number
inputTokens:
minimum: 0
type: integer
outputTokens:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- inputTokens
- outputTokens
type: object
SpantypesTraceExpensiveList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceExpensiveItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceIdentity:
properties:
ai:
$ref: '#/components/schemas/SpantypesTraceAIIdentity'
durationNano:
minimum: 0
type: integer
errorSpanCount:
minimum: 0
type: integer
hasMissingSpans:
type: boolean
root:
$ref: '#/components/schemas/SpantypesSpanSummary'
rootCount:
minimum: 0
type: integer
serviceCount:
minimum: 0
type: integer
services:
items:
$ref: '#/components/schemas/SpantypesTraceServiceStats'
type: array
spanCount:
minimum: 0
type: integer
startTimestampMillis:
minimum: 0
type: integer
traceId:
type: string
required:
- traceId
- startTimestampMillis
- durationNano
- spanCount
- errorSpanCount
- rootCount
- hasMissingSpans
- serviceCount
- services
type: object
SpantypesTraceLinkItem:
properties:
linkCount:
minimum: 0
type: integer
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- linkCount
- links
type: object
SpantypesTraceLinkList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceLinkItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceOverview:
properties:
errors:
$ref: '#/components/schemas/SpantypesTraceErrorList'
expensive:
$ref: '#/components/schemas/SpantypesTraceExpensiveList'
identity:
$ref: '#/components/schemas/SpantypesTraceIdentity'
links:
$ref: '#/components/schemas/SpantypesTraceLinkList'
slowest:
$ref: '#/components/schemas/SpantypesTraceSlowestList'
tree:
$ref: '#/components/schemas/SpantypesTraceTree'
unmarkedFailures:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureList'
type: object
SpantypesTraceServiceStats:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
serviceName:
type: string
spanCount:
minimum: 0
type: integer
required:
- serviceName
- spanCount
- errorSpanCount
- ownTimeNano
type: object
SpantypesTraceSlowestItem:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
spanCount:
minimum: 0
type: integer
required:
- span
- spanCount
- ownTimeNano
- errorSpanCount
type: object
SpantypesTraceSlowestList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSlowestItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanDetail:
properties:
ancestorCount:
minimum: 0
type: integer
ancestors:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
descendants:
items:
$ref: '#/components/schemas/SpantypesTraceSpanLevel'
type: array
percentile:
$ref: '#/components/schemas/SpantypesTraceSpanPercentile'
record:
$ref: '#/components/schemas/SpantypesSpanRecord'
summary:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- summary
- record
- ancestors
- ancestorCount
- descendants
type: object
SpantypesTraceSpanLevel:
properties:
level:
minimum: 0
type: integer
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- level
- total
- spans
type: object
SpantypesTraceSpanList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSpanMatch'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanMatch:
properties:
matches:
items:
$ref: '#/components/schemas/SpantypesSpanTextMatch'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- matches
type: object
SpantypesTraceSpanPercentile:
properties:
p50Nano:
minimum: 0
type: integer
p90Nano:
minimum: 0
type: integer
p99Nano:
minimum: 0
type: integer
position:
format: double
type: number
windowMinutes:
minimum: 0
type: integer
required:
- p50Nano
- p90Nano
- p99Nano
- position
- windowMinutes
type: object
SpantypesTraceTree:
properties:
complete:
type: boolean
records:
items:
$ref: '#/components/schemas/SpantypesSpanRecord'
type: array
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- total
- complete
- spans
type: object
SpantypesTraceUnmarkedFailureItem:
properties:
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
reason:
$ref: '#/components/schemas/SpantypesUnmarkedFailureReason'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- reason
type: object
SpantypesTraceUnmarkedFailureList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTruncatedField:
properties:
field:
type: string
length:
minimum: 0
type: integer
required:
- field
- length
type: object
SpantypesUnmarkedFailureReason:
enum:
- http_4xx
- grpc_status
- exception_event
type: string
SpantypesUpdatableSpanMapper:
properties:
config:
@@ -19229,6 +19807,150 @@ paths:
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/inspect:
get:
deprecated: false
description: 'Returns one of three parts of a trace of any size, named by type,
each within 50,000 characters. Without spanId or search it returns the overview:
the trace''s identity with per-service totals, the spans where each error
started, the failures not marked as errors (a 4xx response, a gRPC status
other than OK, an exception event), the slowest spans by own time with same-name
spans under one parent taken together, the most expensive gen_ai spans, and
the span tree. The tree holds the first 50 spans of the trace: level by level
from the root, and in time order on the level that does not fit. A trace of
up to 50 spans also returns each span''s full record when they fit in 20,000
characters. With spanId it returns that span''s summary and full record, its
ancestors, and the spans below it level by level, at most 20 per level; values
over 500 characters are cut and listed in truncated. With search it returns
the matching spans, each with where the words were found; allSpans returns
every span instead. Every list carries its total, and every list item the
span''s direct parent. Pass a nextCursor as cursor with the same parameters
to get the next page.'
operationId: InspectTrace
parameters:
- description: Returns this span in full with the spans around it. Cannot be
combined with search.
in: query
name: spanId
schema:
description: Returns this span in full with the spans around it. Cannot
be combined with search.
type: string
- description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
in: query
name: search
schema:
description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
type: string
- description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
in: query
name: depth
schema:
description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
type: integer
- description: 'Returns a different response: every span of the trace as a short
line, in tree order, or with spanId that span and every span below it. Cannot
be combined with search or depth.'
in: query
name: allSpans
schema:
description: 'Returns a different response: every span of the trace as a
short line, in tree order, or with spanId that span and every span below
it. Cannot be combined with search or depth.'
type: boolean
- description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
in: query
name: selectFields
schema:
description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
items:
type: string
type: array
- description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans when
it would pass the 50,000 character limit.
in: query
name: limit
schema:
description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans
when it would pass the 50,000 character limit.
type: integer
- description: The nextCursor of an earlier response to the same request; returns
the next page.
in: query
name: cursor
schema:
description: The nextCursor of an earlier response to the same request;
returns the next page.
type: string
- in: path
name: traceID
required: true
schema:
type: string
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/SpantypesGettableTraceInspection'
status:
type: string
required:
- status
- data
type: object
description: OK
"400":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Bad Request
"401":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Unauthorized
"403":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
security:
- api_key:
- VIEWER
- tokenizer:
- VIEWER
summary: Inspect a trace
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/summary:
get:
deprecated: false

View File

@@ -34,6 +34,12 @@
pylon: { enabled: false, appId: '', identitySecret: '' },
},
};
// OverlayScrollbars drives its handles with scroll-driven animations when the
// browser has `ScrollTimeline`. Those never finish, and Storybook waits up to
// 5s for running animations after every `play`, so each story with a scroller
// would pay the full 5s. Without it the handles are positioned from script.
delete window.ScrollTimeline;
</script>
<script>

View File

@@ -7190,6 +7190,63 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesGeoMapPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind {
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
export interface DashboardtypesTopListAppearanceDTO {
/**
* @type string
* @description Hex color of every bar; a matching background threshold overrides it.
*/
barColor: string;
/**
* @type boolean
* @description Numbers each row by its position in the list.
*/
showRank?: boolean;
/**
* @type boolean
* @description Shows each row's share of the listed rows' total.
*/
showShare?: boolean;
}
export interface DashboardtypesTopListPanelSpecDTO {
/**
* @description Rank, share and bar color options.
*/
appearance?: DashboardtypesTopListAppearanceDTO;
/**
* @description Unit and decimal precision of the values.
*/
formatting?: DashboardtypesPanelFormattingDTO;
/**
* @type array,null
* @description Rules that recolor a row when its value compares to a threshold as specified.
*/
thresholds?: DashboardtypesComparisonThresholdDTO[] | null;
/**
* @description The time range the rows are computed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO {
/**
* @enum signoz/TopListPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesTopListPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7202,7 +7259,8 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -8490,6 +8548,7 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
@@ -13758,6 +13817,28 @@ export interface SpantypesEventDTO {
timeUnixNano?: number;
}
export type SpantypesEventV2DTOAttributes = { [key: string]: unknown };
export interface SpantypesEventV2DTO {
/**
* @type object
*/
attributes?: SpantypesEventV2DTOAttributes;
/**
* @type boolean
*/
isError?: boolean;
/**
* @type string
*/
name?: string;
/**
* @type integer
* @minimum 0
*/
timeUnixNano?: number;
}
export enum SpantypesFieldContextDTO {
attribute = 'attribute',
resource = 'resource',
@@ -14077,6 +14158,168 @@ export interface SpantypesGettableTraceAggregationsDTO {
aggregations: SpantypesSpanAggregationResultDTO[];
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
*/
field: string;
/**
* @type string
*/
snippet: string;
}
export interface SpantypesSpanSummaryDTO {
/**
* @type integer
* @minimum 0
*/
childCount: number;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type boolean
*/
hasError: boolean;
/**
* @type string
*/
kind: string;
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type string
*/
name: string;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
parentSpanId?: string;
/**
* @type string
*/
responseStatusCode?: string;
/**
* @type string
*/
serviceName: string;
/**
* @type string
*/
spanId: string;
/**
* @type integer
* @minimum 0
*/
startOffsetNano: number;
/**
* @type integer
* @minimum 0
*/
subtreeSpanCount: number;
}
export interface SpantypesTraceSpanMatchDTO {
/**
* @type array
*/
matches: SpantypesSpanTextMatchDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanListDTO {
/**
* @type array
*/
items: SpantypesTraceSpanMatchDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceErrorItemDTO {
/**
* @type integer
* @minimum 0
*/
errorAncestorCount: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type string
*/
statusMessage: string;
}
export interface SpantypesTraceErrorListDTO {
/**
* @type array
*/
items: SpantypesTraceErrorItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceExpensiveItemDTO {
/**
* @type number
*/
cost?: number;
/**
* @type integer
* @minimum 0
*/
inputTokens: number;
/**
* @type integer
* @minimum 0
*/
outputTokens: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceExpensiveListDTO {
/**
* @type array
*/
items: SpantypesTraceExpensiveItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceAITokensDTO {
/**
* @type integer
@@ -14105,6 +14348,354 @@ export interface SpantypesTraceAITokensDTO {
reasoning: number;
}
export interface SpantypesTraceAIIdentityDTO {
/**
* @type integer
* @minimum 0
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
*/
toolCallCount: number;
/**
* @type number
*/
totalCost?: number;
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceIdentityDTO {
ai?: SpantypesTraceAIIdentityDTO;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type boolean
*/
hasMissingSpans: boolean;
root?: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
rootCount: number;
/**
* @type integer
* @minimum 0
*/
serviceCount: number;
/**
* @type array
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @type integer
* @minimum 0
*/
spanCount: number;
/**
* @type integer
* @minimum 0
*/
startTimestampMillis: number;
/**
* @type string
*/
traceId: string;
}
export interface SpantypesLinkDTO {
/**
* @type string
*/
spanId?: string;
/**
* @type string
*/
traceId?: string;
}
export interface SpantypesTraceLinkItemDTO {
/**
* @type integer
* @minimum 0
*/
linkCount: number;
/**
* @type array
*/
links: SpantypesLinkDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceLinkListDTO {
/**
* @type array
*/
items: SpantypesTraceLinkItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSlowestItemDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceSlowestListDTO {
/**
* @type array
*/
items: SpantypesTraceSlowestItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTruncatedFieldDTO {
/**
* @type string
*/
field: string;
/**
* @type integer
* @minimum 0
*/
length: number;
}
export type SpantypesSpanRecordDTOAttributes = { [key: string]: unknown };
export type SpantypesSpanRecordDTOResource = { [key: string]: string };
export interface SpantypesSpanRecordDTO {
/**
* @type object
*/
attributes: SpantypesSpanRecordDTOAttributes;
/**
* @type array
*/
events: SpantypesEventV2DTO[];
/**
* @type array
*/
links: SpantypesLinkDTO[];
/**
* @type object
*/
resource: SpantypesSpanRecordDTOResource;
/**
* @type string
*/
spanId: string;
/**
* @type string
*/
statusCode: string;
/**
* @type string
*/
statusMessage: string;
/**
* @type array
*/
truncated: SpantypesTruncatedFieldDTO[];
}
export interface SpantypesTraceTreeDTO {
/**
* @type boolean
*/
complete: boolean;
/**
* @type array
*/
records?: SpantypesSpanRecordDTO[];
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesTraceUnmarkedFailureItemDTO {
parent?: SpantypesSpanSummaryDTO;
reason: SpantypesUnmarkedFailureReasonDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceUnmarkedFailureListDTO {
/**
* @type array
*/
items: SpantypesTraceUnmarkedFailureItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceOverviewDTO {
errors?: SpantypesTraceErrorListDTO;
expensive?: SpantypesTraceExpensiveListDTO;
identity?: SpantypesTraceIdentityDTO;
links?: SpantypesTraceLinkListDTO;
slowest?: SpantypesTraceSlowestListDTO;
tree?: SpantypesTraceTreeDTO;
unmarkedFailures?: SpantypesTraceUnmarkedFailureListDTO;
}
export interface SpantypesTraceSpanLevelDTO {
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSpanPercentileDTO {
/**
* @type integer
* @minimum 0
*/
p50Nano: number;
/**
* @type integer
* @minimum 0
*/
p90Nano: number;
/**
* @type integer
* @minimum 0
*/
p99Nano: number;
/**
* @type number
* @format double
*/
position: number;
/**
* @type integer
* @minimum 0
*/
windowMinutes: number;
}
export interface SpantypesTraceSpanDetailDTO {
/**
* @type integer
* @minimum 0
*/
ancestorCount: number;
/**
* @type array
*/
ancestors: SpantypesSpanSummaryDTO[];
/**
* @type array
*/
descendants: SpantypesTraceSpanLevelDTO[];
percentile?: SpantypesTraceSpanPercentileDTO;
record: SpantypesSpanRecordDTO;
summary: SpantypesSpanSummaryDTO;
}
export enum SpantypesInspectTypeDTO {
overview = 'overview',
span = 'span',
find = 'find',
}
export interface SpantypesGettableTraceInspectionDTO {
find?: SpantypesTraceSpanListDTO;
overview?: SpantypesTraceOverviewDTO;
span?: SpantypesTraceSpanDetailDTO;
type: SpantypesInspectTypeDTO;
}
export interface SpantypesTraceAISummaryDTO {
tokens: SpantypesTraceAITokensDTO;
/**
@@ -15976,6 +16567,55 @@ export type GetTraceAggregations200 = {
status: string;
};
export type InspectTracePathParameters = {
traceID: string;
};
export type InspectTraceParams = {
/**
* @type string
* @description Returns this span in full with the spans around it. Cannot be combined with search.
*/
spanId?: string;
/**
* @type string
* @description Returns the spans that match, earliest first: words, a filter expression, or both, such as worldpay AND has_error = true. Words match the span name, status message, attribute values and events, ignoring case.
*/
search?: string;
/**
* @type integer
* @description With spanId, the number of levels of ancestors and of descendants returned, 1 to 10; 2 when not given. The root span is always returned.
*/
depth?: number;
/**
* @type boolean
* @description Returns a different response: every span of the trace as a short line, in tree order, or with spanId that span and every span below it. Cannot be combined with search or depth.
*/
allSpans?: boolean;
/**
* @type array
* @description With spanId, attribute names returned without the 500 character cut; the record then holds only these attributes.
*/
selectFields?: string[];
/**
* @type integer
* @description Page size for search and for allSpans, at most 1000; when not given, 20 with search and 400 with allSpans. A page holds fewer spans when it would pass the 50,000 character limit.
*/
limit?: number;
/**
* @type string
* @description The nextCursor of an earlier response to the same request; returns the next page.
*/
cursor?: string;
};
export type InspectTrace200 = {
data: SpantypesGettableTraceInspectionDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};

View File

@@ -29,6 +29,9 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
InspectTrace200,
InspectTraceParams,
InspectTracePathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -158,6 +161,117 @@ export const useGetTraceAggregations = <
> => {
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns one of three parts of a trace of any size, named by type, each within 50,000 characters. Without spanId or search it returns the overview: the trace's identity with per-service totals, the spans where each error started, the failures not marked as errors (a 4xx response, a gRPC status other than OK, an exception event), the slowest spans by own time with same-name spans under one parent taken together, the most expensive gen_ai spans, and the span tree. The tree holds the first 50 spans of the trace: level by level from the root, and in time order on the level that does not fit. A trace of up to 50 spans also returns each span's full record when they fit in 20,000 characters. With spanId it returns that span's summary and full record, its ancestors, and the spans below it level by level, at most 20 per level; values over 500 characters are cut and listed in truncated. With search it returns the matching spans, each with where the words were found; allSpans returns every span instead. Every list carries its total, and every list item the span's direct parent. Pass a nextCursor as cursor with the same parameters to get the next page.
* @summary Inspect a trace
*/
export const inspectTrace = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTrace200>({
url: `/api/v1/traces/${traceID}/inspect`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceQueryKey = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTrace>>> = ({
signal,
}) => inspectTrace({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTrace>>
>;
export type InspectTraceQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a trace
*/
export function useInspectTrace<
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceQueryOptions({ traceID }, params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a trace
*/
export const invalidateInspectTrace = async (
queryClient: QueryClient,
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace

View File

@@ -903,6 +903,40 @@ describe('prepareQueryRangePayloadV5', () => {
const logSpec = builderQuery.spec as LogBuilderQuery;
expect(logSpec.filter).toStrictEqual({ expression: '' });
});
it('sends the AI slot as builder_ai_query envelopes, ignoring builder', () => {
const props: GetQueryResultsProps = {
query: {
queryType: EQueryType.AI_QUERY_BUILDER,
id: 'q-ai',
unit: undefined,
promql: [],
clickhouse_sql: [],
builder: {
queryData: [baseBuilderQuery({ queryName: 'M' })],
queryFormulas: [],
queryTraceOperator: [],
},
builder_ai_query: {
queryData: [
baseBuilderQuery({ queryName: 'A', dataSource: DataSource.TRACES }),
],
queryFormulas: [],
queryTraceOperator: [],
},
},
graphType: PANEL_TYPES.TIME_SERIES,
selectedTime: 'GLOBAL_TIME',
start,
end,
};
const { queries } =
prepareQueryRangePayloadV5(props).queryPayload.compositeQuery;
expect(
queries.map((q) => [q.type, (q.spec as { name: string }).name]),
).toStrictEqual([['builder_ai_query', 'A']]);
});
});
describe('mapPanelTypeToRequestType', () => {

View File

@@ -3,6 +3,7 @@
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { foldAISlot } from 'lib/query/builderSlot';
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
import { isEmpty } from 'lodash-es';
@@ -55,6 +56,7 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
case PANEL_TYPES.PIE:
case PANEL_TYPES.VALUE:
case PANEL_TYPES.GEO_MAP:
case PANEL_TYPES.TOP_LIST:
return 'scalar';
case PANEL_TYPES.TRACE:
return 'trace';
@@ -279,7 +281,8 @@ export function createAggregation(
panelType === PANEL_TYPES.SCATTER ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.GEO_MAP);
panelType === PANEL_TYPES.GEO_MAP ||
panelType === PANEL_TYPES.TOP_LIST);
if (queryData.dataSource === DataSource.METRICS) {
return [
@@ -561,9 +564,15 @@ export const prepareQueryRangePayloadV5 = (
const requestType = mapPanelTypeToRequestType(graphType);
let queries: QueryEnvelope[] = [];
switch (query.queryType) {
const foldedQuery = foldAISlot(query);
switch (foldedQuery.queryType) {
case EQueryType.QUERY_BUILDER: {
const { queryData: data, queryFormulas, queryTraceOperator } = query.builder;
const {
queryData: data,
queryFormulas,
queryTraceOperator,
} = foldedQuery.builder;
const currentQueryData = mapQueryDataToApi(data, 'queryName', tableParams);
const currentFormulas = mapQueryDataToApi(queryFormulas, 'queryName');
@@ -625,13 +634,15 @@ export const prepareQueryRangePayloadV5 = (
break;
}
case EQueryType.PROM: {
const promQueries = reduceQueriesToObject(query[query.queryType]);
const promQueries = reduceQueriesToObject(
foldedQuery[foldedQuery.queryType],
);
queries = convertPromQueriesToV5(promQueries.queries);
legendMap = promQueries.legends;
break;
}
case EQueryType.CLICKHOUSE: {
const chQueries = reduceQueriesToObject(query[query.queryType]);
const chQueries = reduceQueriesToObject(foldedQuery[foldedQuery.queryType]);
queries = convertClickHouseQueriesToV5(chQueries.queries);
legendMap = chQueries.legends;
break;

View File

@@ -1,4 +1,5 @@
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import { Formula } from 'container/QueryBuilder/components/Formula';
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
@@ -49,6 +50,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
initialDataSource,
handleRunQuery,
} = useQueryBuilder();
const activeBuilder = getActiveBuilder(currentQuery);
const containerRef = useRef(null);
@@ -129,28 +131,28 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
const renderedQueries = useMemo(
() =>
isMultiQueryAllowed
? currentQuery.builder.queryData
: currentQuery.builder.queryData.slice(0, 1),
[isMultiQueryAllowed, currentQuery.builder.queryData],
? activeBuilder.queryData
: activeBuilder.queryData.slice(0, 1),
[isMultiQueryAllowed, activeBuilder.queryData],
);
const traceOperator = useMemo((): IBuilderTraceOperator | undefined => {
if (
currentQuery.builder.queryTraceOperator &&
currentQuery.builder.queryTraceOperator.length > 0
activeBuilder.queryTraceOperator &&
activeBuilder.queryTraceOperator.length > 0
) {
return currentQuery.builder.queryTraceOperator[0];
return activeBuilder.queryTraceOperator[0];
}
return undefined;
}, [currentQuery.builder.queryTraceOperator]);
}, [activeBuilder.queryTraceOperator]);
const hasAtLeastOneTraceQuery = useMemo(
() =>
currentQuery.builder.queryData.some(
activeBuilder.queryData.some(
(query) => query.dataSource === DataSource.TRACES,
),
[currentQuery.builder.queryData],
[activeBuilder.queryData],
);
const hasTraceOperator = useMemo(
@@ -225,9 +227,9 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
{!isMultiQueryAllowed ? (
<QueryV2
ref={containerRef}
key={currentQuery.builder.queryData[0].queryName}
key={activeBuilder.queryData[0].queryName}
index={0}
query={currentQuery.builder.queryData[0]}
query={activeBuilder.queryData[0]}
fieldsConfig={fieldsConfig}
allowedDataSources={queryDataSources}
isMultiQueryAllowed={isMultiQueryAllowed}
@@ -238,7 +240,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
queryVariant={config?.queryVariant || 'dropdown'}
showOnlyWhereClause={showOnlyWhereClause}
isRawQuery={isRawQuery}
signalSource={currentQuery.builder.queryData[0].source as 'meter' | ''}
signalSource={activeBuilder.queryData[0].source as 'meter' | ''}
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
signalSourceChangeEnabled={signalSourceChangeEnabled}
queriesCount={1}
@@ -264,28 +266,26 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
signalSource={query.source as 'meter' | ''}
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
signalSourceChangeEnabled={signalSourceChangeEnabled}
queriesCount={currentQuery.builder.queryData.length}
queriesCount={activeBuilder.queryData.length}
savePreviousQuery={savePreviousQuery}
/>
))
)}
{!showOnlyWhereClause &&
currentQuery.builder.queryFormulas?.length > 0 && (
<div className="qb-formulas-container">
{currentQuery.builder.queryFormulas.map((formula, index) => {
const query =
currentQuery.builder.queryData[index] ||
currentQuery.builder.queryData[0];
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
<div className="qb-formulas-container">
{activeBuilder.queryFormulas.map((formula, index) => {
const query =
activeBuilder.queryData[index] || activeBuilder.queryData[0];
return (
<div key={formula.queryName} className="qb-formula">
<Formula query={query} formula={formula} index={index} isQBV2 />
</div>
);
})}
</div>
)}
return (
<div key={formula.queryName} className="qb-formula">
<Formula query={query} formula={formula} index={index} isQBV2 />
</div>
);
})}
</div>
)}
{shouldShowFooter && (
<QueryFooter
@@ -319,7 +319,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
</div>
))}
{currentQuery.builder.queryFormulas?.map((formula) => (
{activeBuilder.queryFormulas?.map((formula) => (
<div key={formula.queryName} className="formula-name">
{formula.queryName}
</div>

View File

@@ -88,6 +88,9 @@ export function QueryBuilderV2Provider({
);
}
export const useIsInQueryBuilderV2 = (): boolean =>
useContext(QueryBuilderV2Context) !== undefined;
export const useQueryBuilderV2Context = (): QueryBuilderV2ContextType => {
const context = useContext(QueryBuilderV2Context);
if (!context) {

View File

@@ -12,7 +12,13 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { get, isEmpty } from 'lodash-es';
import { ChevronUp } from '@signozhq/icons';
import { Querybuildertypesv5BucketOptionsDTO } from 'api/generated/services/sigNoz.schemas';
import {
Querybuildertypesv5BucketOptionsDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
} from 'api/generated/services/sigNoz.schemas';
import { isLoneBuilderQuery } from 'lib/query/builderEnvelope';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { MetricAggregation } from 'types/api/v5/queryRange';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
@@ -147,10 +153,34 @@ function QueryAddOns({
[resolvedFields],
);
// A panel's default limit applies only to a lone query: per-query limits can keep
// different groups and break a formula's join.
const isLoneQuery = useMemo(
() =>
isLoneBuilderQuery([
...(currentQuery.builder?.queryData ?? [query]).map((data) => ({
type:
data.builderQueryType ??
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
})),
...(currentQuery.builder?.queryFormulas ?? []).map(() => ({
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
})),
...(currentQuery.builder?.queryTraceOperator ?? []).map(() => ({
type:
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator,
})),
]),
[currentQuery.builder, query],
);
const placeholderOf = useCallback(
(key: InputAddOnField): string =>
resolvedFields.get(key)?.placeholder ?? ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields],
(key === QueryBuilderField.Limit && !isLoneQuery
? undefined
: resolvedFields.get(key)?.placeholder) ??
ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields, isLoneQuery],
);
const isDisabled = useCallback(

View File

@@ -67,7 +67,9 @@ function QueryAggregationOptions({
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE || panelType === PANEL_TYPES.PIE
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}

View File

@@ -25,6 +25,7 @@ import CodeMirror, {
import { Button, Popover, Tooltip } from 'antd';
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { tracesAggregateOperatorOptions } from 'constants/queryBuilderOperators';
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { Info, TriangleAlert } from '@signozhq/icons';
@@ -321,6 +322,7 @@ function QueryAggregationSelect({
functionContextForFetch &&
OPERATORS_WITHOUT_DATA_TYPE.includes(functionContextForFetch)
);
const builderQueryType = useBuilderQueryType(queryData);
const { data: fieldKeys, isLoading: isLoadingFields } = useFieldKeysSuggestion(
{
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
@@ -329,7 +331,7 @@ function QueryAggregationSelect({
? TelemetrytypesFieldDataTypeDTO.number
: undefined,
},
queryData.builderQueryType,
builderQueryType,
{
enabled:
!!functionContextForFetch &&

View File

@@ -1,4 +1,5 @@
import { useMemo } from 'react';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { Button, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import WarningPopover from 'components/WarningPopover/WarningPopover';
@@ -15,28 +16,25 @@ function TraceOperatorSection({
addTraceOperator?: () => void;
}): JSX.Element {
const { currentQuery, panelType } = useQueryBuilder();
const activeBuilder = getActiveBuilder(currentQuery);
const showTraceOperatorWarning = useMemo(() => {
const isRawQueryPanel =
panelType === PANEL_TYPES.LIST || panelType === PANEL_TYPES.TRACE;
const hasMultipleQueries = currentQuery.builder.queryData.length > 1;
const hasMultipleQueries = activeBuilder.queryData.length > 1;
const hasTraceOperator =
currentQuery.builder.queryTraceOperator &&
currentQuery.builder.queryTraceOperator.length > 0;
activeBuilder.queryTraceOperator &&
activeBuilder.queryTraceOperator.length > 0;
return isRawQueryPanel && hasMultipleQueries && !hasTraceOperator;
}, [
currentQuery?.builder?.queryData,
currentQuery?.builder?.queryTraceOperator,
panelType,
]);
}, [activeBuilder.queryData, activeBuilder.queryTraceOperator, panelType]);
const traceOperatorWarning = useMemo(() => {
if (currentQuery.builder.queryData.length === 0) {
if (activeBuilder.queryData.length === 0) {
return '';
}
const firstQuery = currentQuery.builder.queryData[0];
const firstQuery = activeBuilder.queryData[0];
return `Currently, you are only seeing results from query ${firstQuery.queryName}. Add a trace operator to combine results of multiple queries.`;
}, [currentQuery]);
}, [activeBuilder.queryData]);
return (
<div className="qb-trace-operator-button-container">
<Tooltip

View File

@@ -33,6 +33,7 @@ import {
queryOperatorSuggestions,
} from 'constants/antlrQueryConstants';
import { useDynamicVariableSuggestions } from 'hooks/dashboard/useDynamicVariableSuggestions';
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
import { useIsDarkMode } from 'hooks/useDarkMode';
import useDebounce from 'hooks/useDebounce';
import { debounce, isNull } from 'lodash-es';
@@ -148,6 +149,7 @@ function QuerySearch({
metricNamespace,
valueSuggestionsOverride,
}: QuerySearchProps): JSX.Element {
const builderQueryType = useBuilderQueryType(queryData);
const isDarkMode = useIsDarkMode();
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
const [activeKey, setActiveKey] = useState<string>('');
@@ -359,7 +361,7 @@ function QuerySearch({
source: signalSource as TelemetrytypesSourceDTO,
metricNamespace,
},
queryData.builderQueryType,
builderQueryType,
);
if (response.data.keys) {
@@ -397,7 +399,7 @@ function QuerySearch({
hardcodedAttributeKeys,
showFilterSuggestionsWithoutMetric,
metricNamespace,
queryData.builderQueryType,
builderQueryType,
],
);
@@ -539,7 +541,7 @@ function QuerySearch({
source: signalSource as TelemetrytypesSourceDTO,
metricName: debouncedMetricName ?? undefined,
},
queryData.builderQueryType,
builderQueryType,
).then((response) => {
const responseData = response.data;
const responseDataValues = responseData.values;
@@ -642,7 +644,7 @@ function QuerySearch({
signalSource,
toggleSuggestions,
valueSuggestionsOverride,
queryData.builderQueryType,
builderQueryType,
],
);

View File

@@ -12,6 +12,7 @@ import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
import QBEntityOptions from 'container/QueryBuilder/components/QBEntityOptions/QBEntityOptions';
import { QueryProps } from 'container/QueryBuilder/type';
import SpanScopeSelector from 'container/QueryBuilder/filters/QueryBuilderSearchV2/SpanScopeSelector';
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { Copy, Ellipsis, Trash } from '@signozhq/icons';
@@ -62,7 +63,8 @@ export const QueryV2 = forwardRef(function QueryV2(
const { cloneQuery, panelType } = useQueryBuilder();
const hasQueryFunctions = query?.functions?.length > 0;
const { dataSource, builderQueryType } = query;
const { dataSource } = query;
const builderQueryType = useBuilderQueryType(query);
const [isCollapsed, setIsCollapsed] = useState(false);

View File

@@ -2,6 +2,7 @@
/* eslint-disable sonarjs/no-identical-functions */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getActiveBuilder } from 'lib/query/builderSlot';
import {
autocompletion,
closeCompletion,
@@ -87,17 +88,18 @@ function TraceOperatorEditor({
const [isExternalQueryChange, setIsExternalQueryChange] = useState(false);
const [lastExternalValue, setLastExternalValue] = useState<string>('');
const { currentQuery } = useQueryBuilder();
const activeBuilder = getActiveBuilder(currentQuery);
const queryOptions = useMemo(
() =>
currentQuery.builder.queryData
activeBuilder.queryData
.filter((query) => query.dataSource === DataSource.TRACES) // Only show trace queries
.map((query) => ({
label: query.queryName,
type: 'atom',
apply: query.queryName,
})),
[currentQuery.builder.queryData],
[activeBuilder.queryData],
);
const toggleSuggestions = useCallback(

View File

@@ -10,7 +10,11 @@ import { ENVIRONMENT } from 'constants/env';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import type {
IBuilderQuery,
Query,
} from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
@@ -107,12 +111,18 @@ beforeEach(() => {
);
});
async function enterAggregation(text: string): Promise<void> {
async function enterAggregation(
text: string,
queryData: IBuilderQuery = aiQuery,
currentQuery?: Query,
): Promise<void> {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2Provider>
<QueryAggregationSelect queryData={aiQuery} />
<QueryAggregationSelect queryData={queryData} />
</QueryBuilderV2Provider>,
undefined,
{ queryBuilderOverrides: currentQuery && { currentQuery } },
);
const content = (
@@ -165,4 +175,26 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
},
TEST_TIMEOUT_MS,
);
it(
'uses the AI keys endpoint for an untagged query on the AI query type',
async () => {
await enterAggregation(
'avg(',
{ ...aiQuery, builderQueryType: undefined },
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
);
await waitFor(
() =>
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]),
{ timeout: SUGGESTIONS_TIMEOUT_MS },
);
expect(keysRequests).toHaveLength(0);
},
TEST_TIMEOUT_MS,
);
});

View File

@@ -7,6 +7,7 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
PANEL_TYPES.PIE,
PANEL_TYPES.VALUE,
PANEL_TYPES.GEO_MAP,
PANEL_TYPES.TOP_LIST,
]);
export function isScalarPanelType(panelType?: string | null): boolean {

View File

@@ -15,6 +15,9 @@ import QueryAddOns from '../QueryV2/QueryAddOns/QueryAddOns';
// Mocks: only what is required for this component to render and for us to assert handler calls
const mockHandleChangeQueryData = jest.fn();
const mockHandleSetQueryData = jest.fn();
let mockCurrentQuery: { unit: string | undefined; builder?: unknown } = {
unit: undefined,
};
jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
useQueryOperations: (): {
@@ -27,10 +30,10 @@ jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): {
handleSetQueryData: typeof mockHandleSetQueryData;
currentQuery: { unit: string | undefined };
currentQuery: typeof mockCurrentQuery;
} => ({
handleSetQueryData: mockHandleSetQueryData,
currentQuery: { unit: undefined },
currentQuery: mockCurrentQuery,
}),
}));
@@ -229,6 +232,77 @@ describe('QueryAddOns', () => {
);
});
describe('a pinned limit with a default', () => {
const renderPinnedLimit = (): void => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TOP_LIST}
index={0}
fieldsConfig={{
[QueryBuilderField.Limit]: {
state: 'pinned',
placeholder: 'Default 10',
},
}}
isForTraceOperator={false}
/>,
);
};
afterEach(() => {
mockCurrentQuery = { unit: undefined };
});
it('is open with its default as the placeholder', () => {
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Default 10',
);
});
it('drops the default for an AI query, which the request leaves unlimited', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [{ ...baseQuery(), builderQueryType: 'builder_ai_query' }],
queryFormulas: [],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
it('drops the default once a formula joins the query', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [baseQuery()],
queryFormulas: [{ expression: 'A * 2' }],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
});
it('auto-opens Order By and Limit when present in query', () => {
const query = baseQuery({
orderBy: [{ columnName: 'duration', order: 'desc' }],

View File

@@ -0,0 +1,71 @@
import {
initialQueriesMap,
initialQueryAIWithType,
PANEL_TYPES,
} from 'constants/queryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { render, screen } from 'tests/test-utils';
import type {
IBuilderQuery,
Query,
} from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { QueryBuilderV2 } from '../QueryBuilderV2';
jest.mock('../QueryV2/QueryV2', () => ({
QueryV2: ({ query }: { query: IBuilderQuery }): JSX.Element => (
<div data-testid="query-v2">{query.queryName}</div>
),
}));
jest.mock('../QueryV2/QueryFooter/QueryFooter', () => (): null => null);
function renderWith(currentQuery: Query): void {
render(
<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} version="v3" />,
undefined,
{
queryBuilderOverrides: {
currentQuery,
panelType: PANEL_TYPES.TIME_SERIES,
initialDataSource: null,
handleSetConfig: jest.fn(),
addNewBuilderQuery: jest.fn(),
addNewFormula: jest.fn(),
addTraceOperator: jest.fn(),
handleRunQuery: jest.fn(),
},
},
);
}
const builderWithQuery = (
builder: Query['builder'],
queryName: string,
): Query['builder'] => ({
...builder,
queryData: [{ ...builder.queryData[0], queryName }],
});
const query: Query = {
...initialQueriesMap.metrics,
builder: builderWithQuery(initialQueriesMap.metrics.builder, 'MAIN'),
builder_ai_query: builderWithQuery(
getActiveBuilder(initialQueryAIWithType),
'AI',
),
};
describe('QueryBuilderV2 builder slot', () => {
it('renders the AI slot when AI is the query type', () => {
renderWith({ ...query, queryType: EQueryType.AI_QUERY_BUILDER });
expect(screen.getByTestId('query-v2')).toHaveTextContent('AI');
});
it('renders builder when Query Builder is the query type', () => {
renderWith(query);
expect(screen.getByTestId('query-v2')).toHaveTextContent('MAIN');
});
});

View File

@@ -1,8 +1,8 @@
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { render } from 'tests/test-utils';
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import { QueryBuilderV2 } from '../QueryBuilderV2';
@@ -19,7 +19,7 @@ const aiQuery: Query = {
...initialQueriesMap.traces.builder,
queryData: initialQueriesMap.traces.builder.queryData.map((query) => ({
...query,
builderQueryType: QueryMode.AI_QUERY_BUILDER,
builderQueryType: EQueryType.AI_QUERY_BUILDER,
})),
},
};

View File

@@ -1,13 +1,16 @@
import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { extractQueryPairs } from 'utils/queryContextUtils';
import {
adjustQueryForV5,
convertAggregationToExpression,
convertExpressionToFilters,
convertFiltersToExpression,
@@ -1684,3 +1687,31 @@ describe('formatValueForExpression', () => {
});
});
});
describe('adjustQueryForV5', () => {
it('adjusts the AI builder slot for AI query builder queries', () => {
const emptyBuilder = {
queryData: [],
queryFormulas: [],
queryTraceOperator: [],
};
const query: Query = {
id: 'q',
queryType: EQueryType.AI_QUERY_BUILDER,
promql: [],
clickhouse_sql: [],
builder: emptyBuilder,
builder_ai_query: {
...emptyBuilder,
queryData: [initialQueryBuilderFormValuesMap.logs],
},
};
const result = adjustQueryForV5(query);
expect(result.builder).toBe(emptyBuilder);
expect(result.builder_ai_query?.queryData[0]).not.toHaveProperty(
'aggregateOperator',
);
});
});

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef } from 'react';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
@@ -20,7 +21,8 @@ export function useSyncQueryBuilderFields(
fields: SyncedQueryBuilderField[] = NO_FIELDS,
): void {
const { currentQuery, handleSetQueryData } = useQueryBuilder();
const queries = currentQuery.builder.queryData;
const activeBuilder = getActiveBuilder(currentQuery);
const queries = activeBuilder.queryData;
const previousRef = useRef<Map<string, IBuilderQuery>>();
const enabled = fields.length > 0;

View File

@@ -9,6 +9,11 @@ import {
QUERY_BUILDER_FUNCTIONS,
} from 'constants/antlrQueryConstants';
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
import {
getActiveBuilder,
getBuilderSlotKeyForQueryType,
isBuilderQueryType,
} from 'lib/query/builderSlot';
import FilterQueryLexer from 'parser/FilterQueryLexer';
import FilterQueryParser, {
AndExpressionContext,
@@ -33,7 +38,6 @@ import {
MetricAggregation,
TraceAggregation,
} from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { extractQueryPairs } from 'utils/queryContextUtils';
import { isQuoted, unquote } from 'utils/stringUtils';
@@ -1030,8 +1034,9 @@ export function getQueryLabelWithAggregation(
}
export const adjustQueryForV5 = (currentQuery: Query): Query => {
if (currentQuery.queryType === EQueryType.QUERY_BUILDER) {
const newQueryData = currentQuery.builder.queryData.map((query) => {
if (isBuilderQueryType(currentQuery.queryType)) {
const activeBuilder = getActiveBuilder(currentQuery);
const newQueryData = activeBuilder.queryData.map((query) => {
const aggregations = query.aggregations?.map((aggregation) => {
if (query.dataSource === DataSource.METRICS) {
const metricAggregation = aggregation as MetricAggregation;
@@ -1072,8 +1077,8 @@ export const adjustQueryForV5 = (currentQuery: Query): Query => {
return {
...currentQuery,
builder: {
...currentQuery.builder,
[getBuilderSlotKeyForQueryType(currentQuery.queryType)]: {
...activeBuilder,
queryData: newQueryData,
},
};

View File

@@ -4,6 +4,8 @@ function QueryTypeTag({ queryType }: IQueryTypeTagProps): JSX.Element {
switch (queryType) {
case EQueryType.QUERY_BUILDER:
return <span>Query Builder</span>;
case EQueryType.AI_QUERY_BUILDER:
return <span>AI Query Builder</span>;
case EQueryType.CLICKHOUSE:
return <span>ClickHouse Query</span>;

View File

@@ -3,6 +3,8 @@ import {
convertFiltersToExpressionWithExistingQuery,
} from 'components/QueryBuilderV2/utils';
import { QuickFiltersSource } from 'components/QuickFilters/types';
import { initialQueriesMap } from 'constants/queryBuilder';
import { EQueryType } from 'types/common/dashboard';
import {
Query,
TagFilter,
@@ -556,3 +558,50 @@ describe('clearFilterFromQuery', () => {
expect(active.filter?.expression).toBe(`http.method = 'GET'`);
});
});
describe('quick filters on an AI query', () => {
const builderQuery = buildQuery([], '').builder;
const aiQuery: Query = {
...initialQueriesMap.traces,
queryType: EQueryType.AI_QUERY_BUILDER,
builder: builderQuery,
builder_ai_query: buildQuery(
[{ key: KEY, op: 'in', value: ['a'] }],
`${KEY} IN ['a']`,
).builder,
};
it('a checkbox toggle writes into the AI slot and leaves builder alone', () => {
const result = applyCheckboxToggle({
currentQuery: aiQuery,
activeQueryIndex: 0,
filter: { attributeKey: { key: KEY, type: 'tag' } } as never,
quickFilterSource: QuickFiltersSource.AI_OBSERVABILITY,
attributeValues: ['a', 'b', 'c'],
value: 'b',
checked: true,
isOnlyOrAllClicked: false,
});
expect(result.builder).toBe(builderQuery);
expect(
result.builder_ai_query?.queryData[0].filters?.items.map(
(item) => item.value,
),
).toStrictEqual([['a', 'b']]);
});
it('clearing a filter clears it from the AI slot', () => {
const result = clearFilterFromQuery({
currentQuery: aiQuery,
filterKey: KEY,
activeQueryIndex: 0,
});
expect(result.builder).toBe(builderQuery);
expect(result.builder_ai_query?.queryData[0].filters?.items).toStrictEqual(
[],
);
expect(result.builder_ai_query?.queryData[0].filter?.expression).toBe('');
});
});

View File

@@ -10,6 +10,11 @@ import {
import { OPERATORS } from 'constants/antlrQueryConstants';
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
import { cloneDeep, isArray } from 'lodash-es';
import {
getBuilderBySlotKey,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { v4 as uuid } from 'uuid';
@@ -157,8 +162,10 @@ export function applyCheckboxToggle({
previousState?: CheckedState;
sectionType?: SectionType;
}): Query {
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
const activeItems =
currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items;
activeBuilder.queryData?.[activeQueryIndex]?.filters?.items;
const isSomeFilterPresentForCurrentAttribute = !!activeItems?.some((item) =>
isKeyMatch(item.key?.key, filter.attributeKey.key),
@@ -173,7 +180,7 @@ export function applyCheckboxToggle({
const isMultipleValuesTrueForTheKey =
Object.values(currentFilterState).filter((val) => val).length > 1;
const query = cloneDeep(currentQuery.builder.queryData?.[activeQueryIndex]);
const query = cloneDeep(activeBuilder.queryData?.[activeQueryIndex]);
// if only or all are clicked we do not need to worry about anything just override whatever we have
// by either adding a new IN operator value clause in case of ONLY or remove everything we have for ALL.
@@ -430,18 +437,15 @@ export function applyCheckboxToggle({
query.filters = synced.filters;
}
return {
...currentQuery,
builder: {
...currentQuery.builder,
queryData: [
...currentQuery.builder.queryData.map((q, idx) => {
if (idx === activeQueryIndex) {
return query;
}
return q;
}),
],
},
};
return replaceBuilderBySlotKey(currentQuery, slotKey, {
...activeBuilder,
queryData: [
...activeBuilder.queryData.map((q, idx) => {
if (idx === activeQueryIndex) {
return query;
}
return q;
}),
],
});
}

View File

@@ -1,6 +1,7 @@
import { useMemo, useState } from 'react';
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { DEFAULT_VISIBLE_ITEMS_COUNT } from './constants';
import { isKeyMatch } from './utils';
@@ -37,12 +38,13 @@ function useCheckboxDisclosure({
DEFAULT_VISIBLE_ITEMS_COUNT,
);
const { queryData } = getActiveBuilder(currentQuery);
const isSomeFilterPresentForCurrentAttribute = useMemo(
() =>
!!currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items?.some(
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
!!queryData?.[activeQueryIndex]?.filters?.items?.some((item) =>
isKeyMatch(item.key?.key, filter.attributeKey.key),
),
[currentQuery.builder.queryData, activeQueryIndex, filter.attributeKey.key],
[queryData, activeQueryIndex, filter.attributeKey.key],
);
const isOpen = useMemo(() => {

View File

@@ -4,6 +4,7 @@ import {
QuickFiltersSource,
} from 'components/QuickFilters/types';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { isEqual, isFunction } from 'lodash-es';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -77,7 +78,7 @@ function useCheckboxFilterActions({
dispatch(updatedQuery);
if (onQuickFilterChange) {
const queryData = updatedQuery.builder.queryData[activeQueryIndex];
const queryData = getActiveBuilder(updatedQuery).queryData[activeQueryIndex];
const expression = queryData?.filter?.expression || '';
const filterItemKeys = (queryData?.filters?.items || [])
.map((item) => item.key?.key)

View File

@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { deriveCheckboxState } from './checkboxFilterQuery';
import { isKeyMatch } from './utils';
@@ -31,33 +32,28 @@ function useCheckboxFilterState({
activeQueryIndex,
}: UseCheckboxFilterStateProps): UseCheckboxFilterStateReturn {
const { currentQuery } = useQueryBuilder();
const activeQueryData = currentQuery
? getActiveBuilder(currentQuery).queryData
: undefined;
// derive the state of each filter key here and keep it in sync with current query
const currentFilterState = useMemo(
() =>
deriveCheckboxState({
attributeValues,
filterItems:
currentQuery?.builder.queryData?.[activeQueryIndex]?.filters?.items,
filterItems: activeQueryData?.[activeQueryIndex]?.filters?.items,
filterKey: filter.attributeKey.key,
}),
[
attributeValues,
currentQuery?.builder.queryData,
filter.attributeKey,
activeQueryIndex,
],
[attributeValues, activeQueryData, filter.attributeKey, activeQueryIndex],
);
// disable the filter when there are multiple entries of the same attribute key present in the filter bar
const isFilterDisabled = useMemo(
() =>
(currentQuery?.builder?.queryData?.[
activeQueryIndex
]?.filters?.items?.filter((item) =>
(activeQueryData?.[activeQueryIndex]?.filters?.items?.filter((item) =>
isKeyMatch(item.key?.key, filter.attributeKey.key),
)?.length || 0) > 1,
[currentQuery?.builder?.queryData, activeQueryIndex, filter.attributeKey],
[activeQueryData, activeQueryIndex, filter.attributeKey],
);
// whether the current filter has multiple values to its name in the key op value section

View File

@@ -11,6 +11,7 @@ import {
} from 'components/QuickFilters/types';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -128,18 +129,15 @@ export default function CheckboxFilterV2(
onToggleOpen();
};
const activeQueryData = currentQuery
? getActiveBuilder(currentQuery).queryData
: undefined;
const currentFilterOp = useMemo(() => {
const filterSync = currentQuery?.builder.queryData?.[
activeQueryIndex
]?.filters?.items.find((item) =>
isKeyMatch(item.key?.key, filter.attributeKey.key),
const filterSync = activeQueryData?.[activeQueryIndex]?.filters?.items.find(
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
);
return filterSync?.op;
}, [
currentQuery?.builder.queryData,
activeQueryIndex,
filter.attributeKey.key,
]);
}, [activeQueryData, activeQueryIndex, filter.attributeKey.key]);
const isNotInOperator = NON_SELECTED_OPERATORS.includes(currentFilterOp || '');

View File

@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { QuickFilterCheckboxUseFieldApis } from 'components/QuickFilters/types';
@@ -18,6 +19,9 @@ export function useExistingQuery({
activeQueryIndex,
}: UseExistingQueryParams): UseExistingQueryResult {
const { stagedQuery } = useQueryBuilder();
const stagedQueryData = stagedQuery
? getActiveBuilder(stagedQuery).queryData
: undefined;
const existingQuery = useMemo(() => {
if (useFieldApis.existingQuery === null) {
@@ -28,7 +32,7 @@ export function useExistingQuery({
return useFieldApis.existingQuery;
}
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
const queryData = stagedQueryData?.[activeQueryIndex];
// Prefer V5 filter.expression
if (queryData?.filter?.expression) {
@@ -41,21 +45,17 @@ export function useExistingQuery({
}
return undefined;
}, [
useFieldApis.existingQuery,
stagedQuery?.builder.queryData,
activeQueryIndex,
]);
}, [useFieldApis.existingQuery, stagedQueryData, activeQueryIndex]);
// Check if ANY filters exist in query (V3 items or V5 expression)
// This is separate from existingQuery because existingQuery can be explicitly
// disabled (null) while filters still exist in the query for UI purposes
const hasExistingQuery = useMemo(() => {
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
const queryData = stagedQueryData?.[activeQueryIndex];
const hasV3Items = (queryData?.filters?.items?.length ?? 0) > 0;
const hasV5Expression = !!queryData?.filter?.expression;
return hasV3Items || hasV5Expression || !!existingQuery;
}, [stagedQuery?.builder.queryData, activeQueryIndex, existingQuery]);
}, [stagedQueryData, activeQueryIndex, existingQuery]);
return { existingQuery, hasExistingQuery };
}

View File

@@ -9,6 +9,12 @@ import {
import { getMs } from 'utils/timeUtils';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import {
getActiveBuilder,
getBuilderBySlotKey,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { cloneDeep, isArray, isEqual, isFunction } from 'lodash-es';
import {
AllTraceFilterKeys,
@@ -57,7 +63,8 @@ function Duration({
// eslint-disable-next-line sonarjs/cognitive-complexity
const syncSelectedFilters = useMemo((): FilterType => {
const filters =
compositeQuery?.builder.queryData?.[activeQueryIndex]?.filters;
compositeQuery &&
getActiveBuilder(compositeQuery).queryData?.[activeQueryIndex]?.filters;
if (!filters) {
return {} as FilterType;
}
@@ -183,49 +190,51 @@ function Duration({
};
const removeFilterItemIds = (query: Query): Query => {
const clonedQuery = cloneDeep(query);
clonedQuery.builder.queryData = clonedQuery.builder.queryData.map((data) => ({
...data,
filters: {
...data.filters,
items:
data.filters?.items?.map((item) => ({
...item,
id: '',
})) || [],
op: data.filters?.op || 'AND',
},
}));
return clonedQuery;
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
const activeBuilder = getBuilderBySlotKey(query, slotKey);
return replaceBuilderBySlotKey(cloneDeep(query), slotKey, {
...activeBuilder,
queryData: activeBuilder.queryData.map((data) => ({
...data,
filters: {
...data.filters,
items:
data.filters?.items?.map((item) => ({
...item,
id: '',
})) || [],
op: data.filters?.op || 'AND',
},
})),
});
};
const handleRun = useCallback(
(props?: HandleRunProps): void => {
const preparedQuery: Query = {
...currentQuery,
builder: {
...currentQuery.builder,
queryData: currentQuery.builder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
return {
...item,
filters: {
...item.filters,
items: props?.resetAll
? []
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
.map((item) =>
item.key?.key === props?.clearByType ? undefined : item,
)
.filter((i) => i) as TagFilterItem[]),
op: item.filters?.op || 'AND',
},
};
}),
},
};
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
...activeBuilder,
queryData: activeBuilder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
return {
...item,
filters: {
...item.filters,
items: props?.resetAll
? []
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
.map((item) =>
item.key?.key === props?.clearByType ? undefined : item,
)
.filter((i) => i) as TagFilterItem[]),
op: item.filters?.op || 'AND',
},
};
}),
});
const currentQueryWithoutIds = removeFilterItemIds(currentQuery);
const preparedQueryWithoutIds = removeFilterItemIds(preparedQuery);

View File

@@ -1,4 +1,9 @@
import { removeKeysFromExpression } from 'components/QueryBuilderV2/utils';
import {
getBuilderBySlotKey,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { getKeySpellings, isKeyMatch } from '../Checkbox/utils';
@@ -20,34 +25,33 @@ export function clearFilterFromQuery({
activeQueryIndex: number;
operators?: string[];
}): Query {
return {
...currentQuery,
builder: {
...currentQuery.builder,
queryData: currentQuery.builder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
return {
...item,
filter: {
expression: removeKeysFromExpression(
item.filter?.expression ?? '',
getKeySpellings(filterKey),
false,
operators,
),
},
filters: {
...item.filters,
items:
item.filters?.items?.filter(
(fil) => !isKeyMatch(fil.key?.key, filterKey),
) || [],
op: item.filters?.op || 'AND',
},
};
}),
},
};
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
return replaceBuilderBySlotKey(currentQuery, slotKey, {
...activeBuilder,
queryData: activeBuilder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
return {
...item,
filter: {
expression: removeKeysFromExpression(
item.filter?.expression ?? '',
getKeySpellings(filterKey),
false,
operators,
),
},
filters: {
...item.filters,
items:
item.filters?.items?.filter(
(fil) => !isKeyMatch(fil.key?.key, filterKey),
) || [],
op: item.filters?.op || 'AND',
},
};
}),
});
}

View File

@@ -32,6 +32,11 @@ import {
QuickFilterReadPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
import { isFunction } from 'lodash-es';
import {
getActiveBuilder,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import useActiveQueryIndex from './hooks/useActiveQueryIndex';
@@ -87,15 +92,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
panelType,
} = useQueryBuilder();
const [open, setOpen] = useState(false);
const activeBuilder = currentQuery
? getActiveBuilder(currentQuery)
: undefined;
// Sync lastUsedQuery when queries change (e.g., after deletion)
const validQueryIndex = useMemo(
() =>
Math.min(
lastUsedQuery || 0,
(currentQuery?.builder?.queryData?.length || 1) - 1,
),
[lastUsedQuery, currentQuery?.builder?.queryData?.length],
Math.min(lastUsedQuery || 0, (activeBuilder?.queryData?.length || 1) - 1),
[lastUsedQuery, activeBuilder?.queryData?.length],
);
// Determine if we're in ListView mode
@@ -103,15 +108,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
// Generate query options based on available queries
const queryOptions = useMemo(() => {
if (!currentQuery?.builder?.queryData) {
if (!activeBuilder?.queryData) {
return [];
}
return currentQuery.builder.queryData.map((query, index) => ({
return activeBuilder.queryData.map((query, index) => ({
label: query.queryName || String.fromCharCode(65 + index),
value: index,
}));
}, [currentQuery?.builder?.queryData]);
}, [activeBuilder?.queryData]);
// Show dropdown in ListView only for TRACES_EXPLORER source
const shouldShowDropdownInListView =
@@ -127,36 +132,34 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
// clear all the filters for the query which is in sync with filters
const handleReset = (): void => {
const activeQuery = currentQuery?.builder.queryData?.[activeQueryIndex];
const activeQuery = activeBuilder?.queryData?.[activeQueryIndex];
if (!activeQuery) {
if (!activeBuilder || !activeQuery) {
return;
}
const preparedQuery: Query = {
...currentQuery,
builder: {
...currentQuery.builder,
queryData: currentQuery.builder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
...activeBuilder,
queryData: activeBuilder.queryData.map((item, idx) => {
if (idx !== activeQueryIndex) {
return item;
}
return {
...item,
filter: {
...item.filter,
expression: '',
},
filters: {
...item.filters,
items: [],
op: item.filters?.op || 'AND',
},
};
}),
},
};
return {
...item,
filter: {
...item.filter,
expression: '',
},
filters: {
...item.filters,
items: [],
op: item.filters?.op || 'AND',
},
};
}),
});
if (onFilterChange && isFunction(onFilterChange)) {
onFilterChange(preparedQuery);
@@ -166,13 +169,12 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
};
const lastQueryName =
showQueryName &&
currentQuery.builder.queryData?.[lastUsedQuery || 0]?.queryName;
showQueryName && activeBuilder?.queryData?.[lastUsedQuery || 0]?.queryName;
// In ListView, always show the 0th query's name; otherwise use the active query's name
const displayedQueryName =
isListView || isAIObservabilityRowView
? showQueryName && currentQuery.builder.queryData?.[0]?.queryName
? showQueryName && activeBuilder?.queryData?.[0]?.queryName
: lastQueryName;
const handleQueryChange = (value: number): void => {

View File

@@ -35,6 +35,7 @@ export const getComponentForPanelType = (
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
[PANEL_TYPES.TEXT]: null,
[PANEL_TYPES.SCATTER]: null,

View File

@@ -311,14 +311,10 @@ export const initialQueryMeterWithType: Query = {
export const initialQueryAIWithType: Query = {
...initialQueryWithType,
builder: {
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: {
...initialQueryWithType.builder,
queryData: [
{
...initialQueryBuilderFormValuesMap.traces,
builderQueryType: 'builder_ai_query',
},
],
queryData: [initialQueryBuilderFormValuesMap.traces],
},
};
@@ -341,6 +337,7 @@ export enum PANEL_TYPES {
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
GEO_MAP = 'geo_map',
TOP_LIST = 'top_list',
TEXT = 'text',
EMPTY_WIDGET = 'EMPTY_WIDGET',
}

View File

@@ -13,6 +13,11 @@ import {
Query,
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
import {
getBuilderBySlotKey,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { v4 as uuidv4 } from 'uuid';
/** Param shape emitted by the AI for every filter-touching action. */
@@ -56,12 +61,14 @@ export function replaceFirstQueryData(
query: Query,
updated: IBuilderQuery,
): Query {
const queryData = [...query.builder.queryData];
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
const activeBuilder = getBuilderBySlotKey(query, slotKey);
const queryData = [...activeBuilder.queryData];
queryData[0] = updated;
return {
...query,
builder: { ...query.builder, queryData },
};
return replaceBuilderBySlotKey(query, slotKey, {
...activeBuilder,
queryData,
});
}
/** Page-state deps required by the runQuery / addFilter actions. */

View File

@@ -40,6 +40,7 @@ export function getQueryNames(currentQuery: Query): BaseOptionType[] {
[EQueryType.PROM]: () => getSelectedQueryOptions(currentQuery.promql),
[EQueryType.CLICKHOUSE]: () =>
getSelectedQueryOptions(currentQuery.clickhouse_sql),
[EQueryType.AI_QUERY_BUILDER]: () => [],
};
return queryConfig[currentQuery.queryType]?.() || [];

View File

@@ -25,6 +25,7 @@ import {
useHandleExplorerTabChange,
} from 'hooks/useHandleExplorerTabChange';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { isEmpty } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
@@ -186,7 +187,9 @@ function Explorer(): JSX.Element {
const isFilterApplied = useMemo(() => {
// if any of the non-disabled queries has filters applied, return true
const result = stagedQuery?.builder?.queryData?.filter(
const result = (
stagedQuery ? getActiveBuilder(stagedQuery) : undefined
)?.queryData?.filter(
(item) => !isEmpty(item.filters?.items) && !item.disabled,
);
return !!result?.length;

View File

@@ -15,6 +15,7 @@ import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
import APIError from 'types/api/error';
@@ -35,7 +36,7 @@ function TimeSeriesViewContainer({
const isValidToConvertToMs = useMemo(() => {
const isValid: boolean[] = [];
currentQuery.builder.queryData.forEach(
getActiveBuilder(currentQuery).queryData.forEach(
({ aggregateAttribute, aggregateOperator }) => {
const isExistDurationNanoAttribute =
aggregateAttribute?.key === 'durationNano' ||

View File

@@ -33,7 +33,7 @@ jest.mock('../../TracesTable/TracesTable', () => ({
<button
data-testid="remove-total-tokens"
type="button"
onClick={(): void => onColumnRemove?.('trace:total_tokens:float64')}
onClick={(): void => onColumnRemove?.('trace:total_tokens:number')}
>
remove
</button>
@@ -48,7 +48,7 @@ const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
const TOTAL_TOKENS = {
name: 'total_tokens',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
};
const storedColumnNames = (): string[] | undefined => {

View File

@@ -63,7 +63,7 @@ const mockFieldKeys = (names: string[]): void => {
{
name,
fieldContext: TelemetrytypesFieldContextDTO.trace,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
},
],
]),

View File

@@ -18,6 +18,7 @@ import {
FilterDeps,
replaceFirstQueryData,
} from 'container/AIAssistant/pageActions/builderQueryHelpers';
import { getActiveBuilder } from 'lib/query/builderSlot';
import {
ActionResult,
PageAction,
@@ -93,7 +94,7 @@ export function tracesRunQueryAction(
},
autoApply: true,
execute: async ({ filters }): Promise<ActionResult> => {
const baseQuery = deps.currentQuery.builder.queryData[0];
const baseQuery = getActiveBuilder(deps.currentQuery).queryData[0];
if (!baseQuery) {
throw new Error('No active query found in Traces Explorer.');
}
@@ -117,7 +118,7 @@ export function tracesRunQueryAction(
},
getContext: (): Record<string, unknown> => ({
filters:
deps.currentQuery.builder.queryData[0]?.filters?.items?.map(
getActiveBuilder(deps.currentQuery).queryData[0]?.filters?.items?.map(
(f: TagFilterItem) => ({
key: f.key?.key,
op: f.op,
@@ -158,7 +159,7 @@ export function tracesAddFilterAction(
},
autoApply: true,
execute: async ({ key, op, value }): Promise<ActionResult> => {
const baseQuery = deps.currentQuery.builder.queryData[0];
const baseQuery = getActiveBuilder(deps.currentQuery).queryData[0];
if (!baseQuery) {
throw new Error('No active query found in Traces Explorer.');
}

View File

@@ -73,7 +73,7 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'estimated_total_cost',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{ name: 'trace_duration_nano' },
{ name: 'span_count' },
@@ -81,37 +81,37 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'total_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{
name: 'input_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{
name: 'output_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{
name: 'distinct_tool_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{
name: 'llm_call_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{
name: 'tool_call_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
{ name: 'start_time' },
{ name: 'end_time' },
@@ -122,7 +122,7 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'max_llm_duration_nano',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'float64',
fieldDataType: 'number',
},
];

View File

@@ -1,4 +1,5 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { cloneDeep } from 'lodash-es';
import { OrderByPayload, Query } from 'types/api/queryBuilder/queryBuilderData';
import { parseListOrderBy } from 'utils/explorerUtils';
@@ -15,8 +16,9 @@ export const getListViewQuery = (
? [parseListOrderBy(orderBy)]
: [];
for (let i = 0; i < query.builder.queryData.length; i++) {
const queryData = query.builder.queryData[i];
const { queryData: builderQueries } = getActiveBuilder(query);
for (let i = 0; i < builderQueries.length; i++) {
const queryData = builderQueries[i];
queryData.groupBy = [];
queryData.having = {
expression: '',

View File

@@ -29,6 +29,7 @@ import { getMetricNameForQuery } from '../utils';
import OptionRenderer from '../OptionRenderer/OptionRenderer';
import { GroupByFilterProps } from './GroupByFilter.interfaces';
import { toAttributeKey } from './utils';
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
export const GroupByFilter = memo(function GroupByFilter({
query,
@@ -45,6 +46,7 @@ export const GroupByFilter = memo(function GroupByFilter({
const debouncedValue = useDebounce(searchText, DEBOUNCE_DELAY);
const builderQueryType = useBuilderQueryType(query);
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
{
signal: DATA_SOURCE_TO_SIGNAL[query.dataSource],
@@ -52,7 +54,7 @@ export const GroupByFilter = memo(function GroupByFilter({
metricName: getMetricNameForQuery(query),
searchText: debouncedValue,
},
query.builderQueryType,
builderQueryType,
{ enabled: !disabled && isFocused, keepPreviousData: true },
);

View File

@@ -14,6 +14,7 @@ import { selectStyle } from '../QueryBuilderSearchV2/config';
import { getMetricNameForQuery } from '../utils';
import { OrderByFilterProps } from './OrderByFilter.interfaces';
import { useOrderByFilter } from './useOrderByFilter';
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
export function OrderByFilter({
query,
@@ -34,6 +35,7 @@ export function OrderByFilter({
handleSearchKeys,
} = useOrderByFilter({ query, onChange, entityVersion });
const builderQueryType = useBuilderQueryType(query);
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
{
signal: DATA_SOURCE_TO_SIGNAL[query.dataSource],
@@ -41,7 +43,7 @@ export function OrderByFilter({
metricName: getMetricNameForQuery(query),
searchText: debouncedSearchText,
},
query.builderQueryType,
builderQueryType,
{
enabled: !!query.aggregateAttribute?.key || isRawQuery,
keepPreviousData: true,

View File

@@ -9,6 +9,7 @@ import {
useState,
} from 'react';
import { type RefSelectProps, Select, Spin } from 'antd';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { Pill } from '@signozhq/ui/pill';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import cx from 'classnames';
@@ -820,14 +821,10 @@ function QueryBuilderSearchV2(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query]);
const isLastQuery = useMemo(
() =>
isEqual(
currentQuery.builder.queryData[currentQuery.builder.queryData.length - 1],
query,
),
[currentQuery, query],
);
const isLastQuery = useMemo(() => {
const { queryData } = getActiveBuilder(currentQuery);
return isEqual(queryData[queryData.length - 1], query);
}, [currentQuery, query]);
useEffect(() => {
if (isLastQuery) {

View File

@@ -2,6 +2,7 @@ import { useMemo } from 'react';
import { UseQueryResult } from 'react-query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { isBuilderQueryType } from 'lib/query/builderSlot';
import { ContextLinksData } from 'types/api/widgets/widget';
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -41,7 +42,7 @@ export function useGraphContextMenu({
} {
const drilldownQuery = useGetCompositeQueryParam() || query;
const isQueryTypeBuilder = drilldownQuery?.queryType === 'builder';
const isQueryTypeBuilder = isBuilderQueryType(drilldownQuery.queryType);
const { aggregateDrilldownConfig } = useAggregateDrilldown({
query: drilldownQuery,

View File

@@ -3,6 +3,7 @@ import { useAppParams } from 'lib/router/useAppParams';
import cx from 'classnames';
import { ResizeTable } from 'components/ResizeTable';
import Download from 'container/Download/Download';
import { isBuilderQueryType } from 'lib/query/builderSlot';
import {
createTableColumnsFromQuery,
RowData,
@@ -33,7 +34,7 @@ export function QueryTable({
...props
}: QueryTableProps): JSX.Element {
const { isDownloadEnabled = false, fileName = '' } = downloadOption || {};
const isQueryTypeBuilder = query.queryType === 'builder';
const isQueryTypeBuilder = isBuilderQueryType(query.queryType);
const { servicename: encodedServiceName } = useAppParams<'servicename'>();
const servicename = decodeURIComponent(encodedServiceName || '');

View File

@@ -1,6 +1,7 @@
import WidgetHeader from 'container/WidgetCard/Header';
import { mockAppLocation } from 'tests/router-mocks';
import { fireEvent, render } from 'tests/test-utils';
import { EQueryType } from 'types/common/dashboard';
import { QueryTable } from '../QueryTable';
import { QueryTableProps, WidgetHeaderProps } from './mocks';
@@ -29,6 +30,21 @@ describe('QueryTable -', () => {
const tableRows = container.querySelectorAll('tr.ant-table-row');
expect(tableRows).toHaveLength(3);
});
it('should enable drilldown cells for AI query builder queries', () => {
const { container } = render(
<QueryTable
{...QueryTableProps}
query={{
...QueryTableProps.query,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: QueryTableProps.query.builder,
}}
enableDrillDown
/>,
);
expect(container.querySelector('.clickable-cell')).toBeInTheDocument();
});
});
const setSearchTerm = jest.fn();

View File

@@ -33,6 +33,7 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
HISTOGRAM: false,
HEATMAP: false,
GEO_MAP: false,
TOP_LIST: false,
TEXT: false,
EMPTY_WIDGET: false,
};

View File

@@ -14,12 +14,12 @@ import { useNotifications } from 'hooks/useNotifications';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import createQueryParams from 'lib/createQueryParams';
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import {
getCustomTimeRangeWindowSweepInMS,
getStartAndEndTimesInMilliseconds,
} from 'pages/MessagingQueues/MessagingQueuesUtils';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import { useGraphClickToShowButton } from 'container/WidgetCard/hooks/useGraphClickToShowButton';
@@ -132,13 +132,13 @@ function WidgetGraphComponent({
const [searchTerm, setSearchTerm] = useState<string>('');
const widgetQueryData = widget?.query
? getActiveBuilder(widget.query)?.queryData
: undefined;
const graphClick = useGraphClickToShowButton({
graphRef: currentGraphRef?.current ? currentGraphRef : graphRef,
isButtonEnabled: (widget?.query?.builder?.queryData &&
Array.isArray(widget.query.builder.queryData)
? widget.query.builder.queryData
: []
).some(
isButtonEnabled: (Array.isArray(widgetQueryData) ? widgetQueryData : []).some(
(q) =>
q.dataSource === DataSource.TRACES || q.dataSource === DataSource.LOGS,
),
@@ -219,7 +219,7 @@ function WidgetGraphComponent({
customOnDragSelect={customOnDragSelect}
setCurrentGraphRef={setCurrentGraphRef}
enableDrillDown={
enableDrillDown && widget?.query?.queryType === EQueryType.QUERY_BUILDER
enableDrillDown && isBuilderQueryType(widget.query.queryType)
}
/>
</Modal>

View File

@@ -1,4 +1,5 @@
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import {
createColumnsAndDataSource,
@@ -47,6 +48,18 @@ describe('Table Panel utils', () => {
expect(getQueryLegend(query, 'B')).toBeUndefined();
});
it('getQueryLegend reads the AI builder slot', () => {
const builderQuery = widgetQueryWithLegend as Query;
const query: Query = {
...builderQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder: { queryData: [], queryFormulas: [], queryTraceOperator: [] },
builder_ai_query: builderQuery.builder,
};
expect(getQueryLegend(query, 'A')).toBe('p99');
});
it('sorter function for table sorting', () => {
let rowA: {
A: string | number;

View File

@@ -4,6 +4,7 @@ import { ThresholdProps } from 'types/api/widgets/threshold';
import { QUERY_TABLE_CONFIG } from 'container/QueryTable/config';
import { QueryTableProps } from 'container/QueryTable/QueryTable.intefaces';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { isEmpty, isNaN } from 'lodash-es';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
@@ -119,14 +120,15 @@ export function getQueryLegend(
let legend: string | undefined;
switch (currentQuery.queryType) {
case EQueryType.QUERY_BUILDER:
case EQueryType.AI_QUERY_BUILDER:
// check if the value is present in the queries
legend = currentQuery?.builder?.queryData?.find(
legend = getActiveBuilder(currentQuery)?.queryData?.find(
(query) => query.queryName === queryName,
)?.legend;
if (!legend) {
// check if the value is present in the formula
legend = currentQuery?.builder?.queryFormulas?.find(
legend = getActiveBuilder(currentQuery)?.queryFormulas?.find(
(query) => query.queryName === queryName,
)?.legend;
}
@@ -199,7 +201,7 @@ export function createColumnsAndDataSource(
: undefined;
const isNewAggregation =
currentQuery?.builder?.queryData?.find(
getActiveBuilder(currentQuery).queryData?.find(
(query) => query.queryName === item.queryName,
)?.aggregations?.length || 0;

View File

@@ -6,6 +6,7 @@ import ValueGraph from 'components/ValueGraph';
import { generateGridTitle } from 'utils/generateGridTitle';
import useGraphContextMenu from 'container/QueryTable/Drilldown/useGraphContextMenu';
import ContextMenu, { useCoordinates } from 'periscope/components/ContextMenu';
import { isBuilderQueryType } from 'lib/query/builderSlot';
import { EQueryType } from 'types/common/dashboard';
import {
@@ -73,7 +74,7 @@ function GridValueComponent({
}
const isQueryTypeBuilder =
widget?.query?.queryType === EQueryType.QUERY_BUILDER;
!!widget && isBuilderQueryType(widget.query.queryType);
return (
<>

View File

@@ -58,6 +58,27 @@ describe('getLegend', () => {
expect(legendsData).toBe('alias_sum');
});
it('should read the AI builder slot for AI query builder queries', () => {
const payloadQuery = getMockQuery({
...mockQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: {
...mockQuery.builder,
queryData: [
{
...mockQuery.builder.queryData[0],
queryName: mockQueryData.queryName,
dataSource: DataSource.LOGS,
aggregations: [{ expression: "sum(bytes) as 'alias_sum'" }],
},
],
},
});
const legendsData = getLegend(mockQueryData, payloadQuery, MOCK_LABEL_NAME);
expect(legendsData).toBe('alias_sum');
});
it('should return legend when single builder query with no alias but legend set (builder)', () => {
const payloadQuery = getMockQuery({
...mockQuery,

View File

@@ -25,4 +25,5 @@ export const PanelTypeVsPanelWrapper = {
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
};

View File

@@ -0,0 +1,53 @@
import { QueryBuilderV2Provider } from 'components/QueryBuilderV2/QueryBuilderV2Context';
import { initialQueriesMap } from 'constants/queryBuilder';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import type { BuilderQueryType } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { useBuilderQueryType } from '../useBuilderQueryType';
function renderBuilderQueryType(
queryType: EQueryType,
query: Pick<IBuilderQuery, 'builderQueryType'>,
inQueryBuilder = true,
): BuilderQueryType | undefined {
return renderHook(() => useBuilderQueryType(query), {
wrapper: ({ children }) => (
<AllTheProviders
queryBuilderOverrides={{
currentQuery: { ...initialQueriesMap.traces, queryType },
}}
>
{inQueryBuilder ? (
<QueryBuilderV2Provider>{children}</QueryBuilderV2Provider>
) : (
children
)}
</AllTheProviders>
),
}).result.current;
}
describe('useBuilderQueryType', () => {
it('ignores the AI query type outside the query builder', () => {
expect(
renderBuilderQueryType(EQueryType.AI_QUERY_BUILDER, {}, false),
).toBeUndefined();
});
it('is AI for every query while AI is the query type', () => {
expect(renderBuilderQueryType(EQueryType.AI_QUERY_BUILDER, {})).toBe(
'builder_ai_query',
);
});
it("follows the query's own tag otherwise", () => {
expect(
renderBuilderQueryType(EQueryType.QUERY_BUILDER, {
builderQueryType: 'builder_ai_query',
}),
).toBe('builder_ai_query');
expect(renderBuilderQueryType(EQueryType.QUERY_BUILDER, {})).toBeUndefined();
});
});

View File

@@ -2,6 +2,7 @@ import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap, initialQueryState } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
@@ -105,21 +106,55 @@ describe('useGetCompositeQueryParam', () => {
},
});
const { QUERY_BUILDER, AI_QUERY_BUILDER } = EQueryType;
[
[ROUTES.LOGS_EXPLORER, DataSource.LOGS, ''],
[ROUTES.AI_OBSERVABILITY_EXPLORER, DataSource.TRACES, ''],
[ROUTES.METRICS_EXPLORER_EXPLORER, DataSource.METRICS, ''],
[ROUTES.METER_EXPLORER, DataSource.METRICS, TelemetrytypesSourceDTO.meter],
].forEach(([route, dataSource, source]) => {
[ROUTES.LOGS_EXPLORER, QUERY_BUILDER, DataSource.LOGS, ''],
[ROUTES.AI_OBSERVABILITY_EXPLORER, AI_QUERY_BUILDER, DataSource.TRACES, ''],
[ROUTES.METRICS_EXPLORER_EXPLORER, QUERY_BUILDER, DataSource.METRICS, ''],
[
ROUTES.METER_EXPLORER,
QUERY_BUILDER,
DataSource.METRICS,
TelemetrytypesSourceDTO.meter,
],
].forEach(([route, queryType, dataSource, source]) => {
const query = renderOn(clickhouseWithOperator, route);
const builder = query && getActiveBuilder(query);
expect(query?.queryType).toBe(EQueryType.QUERY_BUILDER);
expect(query?.builder.queryData[0].dataSource).toBe(dataSource);
expect(query?.builder.queryData[0].source ?? '').toBe(source);
expect(query?.builder.queryTraceOperator).toStrictEqual([]);
expect(query?.queryType).toBe(queryType);
expect(builder?.queryData[0].dataSource).toBe(dataSource);
expect(builder?.queryData[0].source ?? '').toBe(source);
expect(builder?.queryTraceOperator).toStrictEqual([]);
});
});
it('converts the legacy fields of an older AI link moved into the AI slot', () => {
const query = renderOn(
JSON.stringify({
...initialQueriesMap.traces,
builder: {
...initialQueriesMap.traces.builder,
queryData: [
{
...initialQueriesMap.traces.builder.queryData[0],
aggregateOperator: 'avg',
aggregations: undefined,
having: [],
},
],
},
}),
ROUTES.AI_OBSERVABILITY_EXPLORER,
);
const [aiQuery] = getActiveBuilder(query as Query).queryData;
expect(query?.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
expect(aiQuery.having).toStrictEqual({ expression: '' });
expect(aiQuery.aggregations).toStrictEqual([
expect.objectContaining({ expression: expect.stringContaining('avg') }),
]);
});
it('keeps the query type on a route without constraints', () => {
const query = renderOn(
JSON.stringify({

View File

@@ -1,16 +1,14 @@
import {
Querybuildertypesv5QueryTypeDTO,
TelemetrytypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { BuilderQueryType } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { BuilderQuerySource, DataSource } from 'types/common/queryBuilder';
export type ExplorerQueryRules = {
dataSource: DataSource;
/** `meter` on the meter explorer, which shares the metrics signal; '' elsewhere. */
source: BuilderQuerySource;
builderQueryType: BuilderQueryType;
/** AI_QUERY_BUILDER on the AI explorer, whose queries live in the AI slot. */
queryType: EQueryType.QUERY_BUILDER | EQueryType.AI_QUERY_BUILDER;
allowsTraceOperator: boolean;
};
@@ -18,31 +16,31 @@ const EXPLORER_QUERY_RULES: Partial<Record<string, ExplorerQueryRules>> = {
[ROUTES.LOGS_EXPLORER]: {
dataSource: DataSource.LOGS,
source: '',
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
queryType: EQueryType.QUERY_BUILDER,
allowsTraceOperator: false,
},
[ROUTES.TRACES_EXPLORER]: {
dataSource: DataSource.TRACES,
source: '',
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
queryType: EQueryType.QUERY_BUILDER,
allowsTraceOperator: true,
},
[ROUTES.AI_OBSERVABILITY_EXPLORER]: {
dataSource: DataSource.TRACES,
source: '',
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_ai_query,
queryType: EQueryType.AI_QUERY_BUILDER,
allowsTraceOperator: false,
},
[ROUTES.METRICS_EXPLORER_EXPLORER]: {
dataSource: DataSource.METRICS,
source: '',
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
queryType: EQueryType.QUERY_BUILDER,
allowsTraceOperator: false,
},
[ROUTES.METER_EXPLORER]: {
dataSource: DataSource.METRICS,
source: TelemetrytypesSourceDTO.meter,
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
queryType: EQueryType.QUERY_BUILDER,
allowsTraceOperator: false,
},
};

View File

@@ -8,11 +8,8 @@ import {
initialQueryState,
} from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import {
IBuilderQuery,
Query,
QueryMode,
} from 'types/api/queryBuilder/queryBuilderData';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
@@ -44,8 +41,9 @@ function firstBuilderQuery(
queryData: unknown[],
pathname: string,
): IBuilderQuery {
return normalizeCompositeQuery(withBuilderQueries(query, queryData), pathname)
.query.builder.queryData[0];
return getActiveBuilder(
normalizeCompositeQuery(withBuilderQueries(query, queryData), pathname).query,
).queryData[0];
}
function without(builderQuery: object, key: keyof IBuilderQuery): object {
@@ -62,9 +60,11 @@ describe('normalizeCompositeQuery', () => {
queryType: EQueryType.CLICKHOUSE,
extra: 'kept',
};
const aiQuery = withBuilderQueries(initialQueriesMap.traces, [
{ ...tracesQuery, builderQueryType: QueryMode.AI_QUERY_BUILDER },
]);
const aiQuery: Query = {
...initialQueriesMap.traces,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: initialQueriesMap.traces.builder,
};
[NOT_AN_EXPLORER, ROUTES.LOGS_EXPLORER].forEach((pathname) =>
expect(
@@ -86,6 +86,33 @@ describe('normalizeCompositeQuery', () => {
).toBe(false);
});
it('moves the AI queries of an older link into the AI slot', () => {
const aiQueryData = [
{ ...tracesQuery, builderQueryType: EQueryType.AI_QUERY_BUILDER },
];
const { query, changed } = normalizeCompositeQuery(
withBuilderQueries(initialQueriesMap.traces, aiQueryData),
ROUTES.AI_OBSERVABILITY_EXPLORER,
);
expect(changed).toBe(true);
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
expect(query.builder_ai_query?.queryData).toStrictEqual([tracesQuery]);
expect(query.builder).toStrictEqual(initialQueryState.builder);
});
it('drops the AI slot outside the AI explorer', () => {
const { query } = normalizeCompositeQuery(
{
...initialQueriesMap.traces,
builder_ai_query: initialQueriesMap.traces.builder,
},
ROUTES.TRACES_EXPLORER,
);
expect(query.builder_ai_query).toBeUndefined();
});
it('adds missing blocks and a stable id without changing its inputs', () => {
const { builder: _, ...builderless } = {
...initialQueriesMap.logs,
@@ -209,7 +236,7 @@ describe('normalizeCompositeQuery', () => {
expect(
firstBuilderQuery(
logs,
[{ ...logsQuery, builderQueryType: QueryMode.AI_QUERY_BUILDER }],
[{ ...logsQuery, builderQueryType: EQueryType.AI_QUERY_BUILDER }],
ROUTES.LOGS_EXPLORER,
).builderQueryType,
).toBeUndefined();
@@ -220,7 +247,7 @@ describe('normalizeCompositeQuery', () => {
{
...tracesQuery,
queryName: 'D',
builderQueryType: QueryMode.AI_QUERY_BUILDER,
builderQueryType: EQueryType.AI_QUERY_BUILDER,
...llmFilter,
},
],
@@ -243,10 +270,7 @@ describe('normalizeCompositeQuery', () => {
).toBe(TelemetrytypesSourceDTO.meter);
expect(
firstBuilderQuery(traces, [{ ...tracesQuery, ...llmFilter }], ai),
).toMatchObject({
builderQueryType: QueryMode.AI_QUERY_BUILDER,
...llmFilter,
});
).toStrictEqual({ ...tracesQuery, ...llmFilter });
expect(
firstBuilderQuery(
traces,
@@ -260,17 +284,13 @@ describe('normalizeCompositeQuery', () => {
],
ai,
),
).toMatchObject({
builderQueryType: QueryMode.AI_QUERY_BUILDER,
queryName: 'B',
filter: { expression: '' },
});
).toStrictEqual({ ...tracesQuery, queryName: 'B', ...llmFilter });
expect(
firstBuilderQuery(traces, [{ ...logsQuery, queryName: 'C' }], ai),
).toMatchObject({
builderQueryType: QueryMode.AI_QUERY_BUILDER,
dataSource: DataSource.TRACES,
queryName: 'C',
filter: { expression: '' },
});
});

View File

@@ -7,8 +7,10 @@ import {
Querybuildertypesv5QueryTypeDTO,
TelemetrytypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import type { QueryBuilderData } from 'types/common/queryBuilder';
import { v5 as uuidv5 } from 'uuid';
import {
@@ -78,6 +80,14 @@ function addMissingBlocks(query: Query, urlQuery: object): void {
if (!query.builder.queryTraceOperator) {
query.builder.queryTraceOperator = [];
}
if (isPlainObject(query.builder_ai_query)) {
const aiBuilder = query.builder_ai_query as QueryBuilderData;
aiBuilder.queryFormulas = aiBuilder.queryFormulas ?? [];
aiBuilder.queryTraceOperator = aiBuilder.queryTraceOperator ?? [];
} else {
delete query.builder_ai_query;
}
}
/**
@@ -93,8 +103,24 @@ function isListOfObjects(value: unknown): boolean {
}
function fitQueryToExplorer(query: Query, rules: ExplorerQueryRules): void {
// Explorers only have the query builder: no PromQL or ClickHouse editor.
query.queryType = EQueryType.QUERY_BUILDER;
// Explorers only have a query builder: no PromQL or ClickHouse editor.
query.queryType = rules.queryType;
if (rules.queryType === EQueryType.AI_QUERY_BUILDER) {
// Older links carry the AI queries inside `builder`.
if (!query.builder_ai_query) {
query.builder_ai_query = query.builder;
query.builder = cloneDeep(initialQueryState.builder);
}
} else {
delete query.builder_ai_query;
}
const activeBuilder = getActiveBuilder(query);
if (
!isListOfObjects(activeBuilder.queryData) ||
activeBuilder.queryData.length === 0
) {
activeBuilder.queryData = cloneDeep(initialQueryState.builder.queryData);
}
if (query.promql.some((promql) => promql.query !== '')) {
query.promql = cloneDeep(initialQueryState.promql);
@@ -105,10 +131,10 @@ function fitQueryToExplorer(query: Query, rules: ExplorerQueryRules): void {
}
if (!rules.allowsTraceOperator) {
query.builder.queryTraceOperator = [];
activeBuilder.queryTraceOperator = [];
}
query.builder.queryData = query.builder.queryData.map((builderQuery) =>
activeBuilder.queryData = activeBuilder.queryData.map((builderQuery) =>
fitBuilderQueryToExplorer(builderQuery, rules),
);
}
@@ -148,12 +174,9 @@ function fillMissingSignal(
builderQuery.source = rules.source;
}
// A missing `builderQueryType` already means builder_query, so only AI needs it written.
if (
builderQuery.builderQueryType === undefined &&
rules.builderQueryType === Querybuildertypesv5QueryTypeDTO.builder_ai_query
) {
builderQuery.builderQueryType = rules.builderQueryType;
// The AI slot marks its queries as AI; a tag from an older link is redundant.
if (rules.queryType === EQueryType.AI_QUERY_BUILDER) {
delete builderQuery.builderQueryType;
}
}
@@ -169,15 +192,11 @@ function belongsToExplorer(
return false;
}
const builderQueryType =
builderQuery.builderQueryType ??
Querybuildertypesv5QueryTypeDTO.builder_query;
if (builderQueryType !== rules.builderQueryType) {
return false;
}
return true;
// Only the AI explorer runs AI queries.
return (
builderQuery.builderQueryType !==
Querybuildertypesv5QueryTypeDTO.builder_ai_query
);
}
function getDefaultBuilderQuery(rules: ExplorerQueryRules): IBuilderQuery {
@@ -186,11 +205,5 @@ function getDefaultBuilderQuery(rules: ExplorerQueryRules): IBuilderQuery {
);
builderQuery.source = rules.source;
if (
rules.builderQueryType === Querybuildertypesv5QueryTypeDTO.builder_ai_query
) {
builderQuery.builderQueryType = rules.builderQueryType;
}
return builderQuery;
}

View File

@@ -0,0 +1,22 @@
import { useIsInQueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2Context';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { BuilderQueryType } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
/**
* The query's builder type, for picking the field suggestion endpoints. The AI query type
* applies only inside the query builder; elsewhere, and in alert editors, which keep AI
* queries in `builder`, the query's own tag decides.
*/
export function useBuilderQueryType(
query: Pick<IBuilderQuery, 'builderQueryType'>,
): BuilderQueryType | undefined {
const { currentQuery } = useQueryBuilder();
const isInQueryBuilder = useIsInQueryBuilderV2();
return isInQueryBuilder &&
currentQuery?.queryType === EQueryType.AI_QUERY_BUILDER
? 'builder_ai_query'
: query.builderQueryType;
}

View File

@@ -9,13 +9,48 @@ import useUrlQuery from 'hooks/useUrlQuery';
import { useAppLocation } from 'lib/router/useAppLocation';
import { isPlainObject } from 'lodash-es';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import {
NormalizedQuery,
normalizeCompositeQuery,
} from './normalizeCompositeQuery';
function toExpressionQuery(query: IBuilderQuery): IBuilderQuery {
const existingExpression = query.filter?.expression || '';
const convertedQuery = { ...query };
const convertedFilter = convertFiltersToExpressionWithExistingQuery(
query.filters || { items: [], op: 'AND' },
existingExpression,
);
convertedQuery.filter = convertedFilter.filter;
convertedQuery.filters = convertedFilter.filters;
// Convert having if needed
if (Array.isArray(query.having)) {
const convertedHaving = convertHavingToExpression(
query.having.filter(isPlainObject),
);
convertedQuery.having = convertedHaving;
}
// Convert aggregation if needed
if (!query.aggregations && query.aggregateOperator) {
const convertedAggregation = convertAggregationToExpression({
aggregateOperator: query.aggregateOperator,
aggregateAttribute: query.aggregateAttribute as BaseAutocompleteData,
dataSource: query.dataSource,
timeAggregation: query.timeAggregation,
spaceAggregation: query.spaceAggregation,
reduceTo: query.reduceTo,
temporality: query.temporality,
}) as any; // Type assertion to handle union type
convertedQuery.aggregations = convertedAggregation;
}
return convertedQuery;
}
export const useNormalizedCompositeQueryParam = (): NormalizedQuery | null => {
const urlQuery = useUrlQuery();
const { pathname } = useAppLocation();
@@ -44,44 +79,15 @@ export const useNormalizedCompositeQueryParam = (): NormalizedQuery | null => {
pathname,
));
// Convert old format to new format for each query in builder.queryData
if (parsedCompositeQuery?.builder?.queryData) {
parsedCompositeQuery.builder.queryData =
parsedCompositeQuery.builder.queryData.map((query) => {
const existingExpression = query.filter?.expression || '';
const convertedQuery = { ...query };
const convertedFilter = convertFiltersToExpressionWithExistingQuery(
query.filters || { items: [], op: 'AND' },
existingExpression,
);
convertedQuery.filter = convertedFilter.filter;
convertedQuery.filters = convertedFilter.filters;
// Convert having if needed
if (Array.isArray(query.having)) {
const convertedHaving = convertHavingToExpression(
query.having.filter(isPlainObject),
);
convertedQuery.having = convertedHaving;
}
// Convert aggregation if needed
if (!query.aggregations && query.aggregateOperator) {
const convertedAggregation = convertAggregationToExpression({
aggregateOperator: query.aggregateOperator,
aggregateAttribute: query.aggregateAttribute as BaseAutocompleteData,
dataSource: query.dataSource,
timeAggregation: query.timeAggregation,
spaceAggregation: query.spaceAggregation,
reduceTo: query.reduceTo,
temporality: query.temporality,
}) as any; // Type assertion to handle union type
convertedQuery.aggregations = convertedAggregation;
}
return convertedQuery;
});
}
// Convert old format to new format in every builder slot
[
parsedCompositeQuery?.builder,
parsedCompositeQuery?.builder_ai_query,
].forEach((builder) => {
if (builder?.queryData) {
builder.queryData = builder.queryData.map(toExpressionQuery);
}
});
} catch (e) {
parsedCompositeQuery = null;
}

View File

@@ -7,6 +7,7 @@ import {
saveAsPreviousQuery,
} from 'components/QueryBuilderV2/QueryV2/previousQuery.utils';
import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { LEGEND } from 'constants/global';
import {
ATTRIBUTE_TYPES,
@@ -488,13 +489,15 @@ export const useQueryOperations: UseQueryOperations = ({
],
);
const activeQueryCount = getActiveBuilder(currentQuery).queryData.length;
const handleDeleteQuery = useCallback(() => {
if (currentQuery.builder.queryData.length > 1) {
if (activeQueryCount > 1) {
removeQueryBuilderEntityByIndex('queryData', index);
}
setLastUsedQuery(0);
}, [
currentQuery.builder.queryData.length,
activeQueryCount,
setLastUsedQuery,
removeQueryBuilderEntityByIndex,
index,

View File

@@ -1,4 +1,5 @@
import { renderHook } from '@testing-library/react';
import { renderHook } from 'tests/test-utils';
import { initialFormulaBuilderFormValues } from 'constants/queryBuilder';
import {
IBuilderFormula,
IClickHouseQuery,
@@ -67,6 +68,23 @@ describe('useGetQueryLabels', () => {
});
});
describe('AI_QUERY_BUILDER type', () => {
it('returns formula labels from builder_ai_query', () => {
const query = buildQuery({
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: {
queryData: [],
queryFormulas: [{ ...initialFormulaBuilderFormValues, queryName: 'F1' }],
queryTraceOperator: [],
},
});
const { result } = renderHook(() => useGetQueryLabels(query));
expect(result.current).toStrictEqual([{ label: 'F1', value: 'F1' }]);
});
});
describe('CLICKHOUSE type', () => {
it('returns empty array when clickhouse_sql is undefined', () => {
const query = buildQuery({

View File

@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import { getQueryLabelWithAggregation } from 'components/QueryBuilderV2/utils';
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
@@ -7,25 +8,24 @@ export const useGetQueryLabels = (
currentQuery: Query,
): { label: string; value: string }[] =>
useMemo(() => {
if (currentQuery?.queryType === EQueryType.QUERY_BUILDER) {
if (isBuilderQueryType(currentQuery.queryType)) {
const activeBuilder = getActiveBuilder(currentQuery);
const queryLabels = getQueryLabelWithAggregation(
currentQuery?.builder?.queryData || [],
);
const formulaLabels = (currentQuery?.builder?.queryFormulas ?? []).map(
(formula) => ({
label: formula.queryName,
value: formula.queryName,
}),
activeBuilder.queryData ?? [],
);
const formulaLabels = (activeBuilder.queryFormulas ?? []).map((formula) => ({
label: formula.queryName,
value: formula.queryName,
}));
return [...queryLabels, ...formulaLabels];
}
if (currentQuery?.queryType === EQueryType.CLICKHOUSE) {
return (currentQuery?.clickhouse_sql ?? []).map((q) => ({
if (currentQuery.queryType === EQueryType.CLICKHOUSE) {
return (currentQuery.clickhouse_sql ?? []).map((q) => ({
label: q.name,
value: q.name,
}));
}
return (currentQuery?.promql ?? []).map((q) => ({
return (currentQuery.promql ?? []).map((q) => ({
label: q.name,
value: q.name,
}));

View File

@@ -27,7 +27,7 @@ import {
QueryRangeResponseV5,
} from 'types/api/v5/queryRange';
import { QueryData } from 'types/api/widgets/getQuery';
import { EQueryType } from 'types/common/dashboard';
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
import { DataSource } from 'types/common/queryBuilder';
import { prepareQueryRangePayload } from './prepareQueryRangePayload';
@@ -36,11 +36,11 @@ import { prepareQueryRangePayload } from './prepareQueryRangePayload';
* Validates if metric name is available for METRICS data source
*/
function validateMetricNameForMetricsDataSource(query: Query): boolean {
if (query.queryType !== 'builder') {
if (!isBuilderQueryType(query.queryType)) {
return true; // Non-builder queries don't need this validation
}
const { queryData } = query.builder;
const { queryData } = getActiveBuilder(query);
// Check if any METRICS data source queries exist
const metricsQueries = queryData.filter(
@@ -124,14 +124,15 @@ export const getLegend = (
labelName: string,
): string => {
// For non-query builder queries, return the label name directly
if (payloadQuery.queryType !== EQueryType.QUERY_BUILDER) {
if (!isBuilderQueryType(payloadQuery.queryType)) {
return labelName;
}
const activeBuilder = getActiveBuilder(payloadQuery);
// Combine queryData and queryTraceOperator
const allQueries = [
...(payloadQuery?.builder?.queryData || []),
...(payloadQuery?.builder?.queryTraceOperator || []),
...(activeBuilder?.queryData || []),
...(activeBuilder?.queryTraceOperator || []),
];
const aggregationPerQuery = allQueries.reduce((acc, query) => {

View File

@@ -1,3 +1,4 @@
import { initialQueryBuilderFormValues } from 'constants/queryBuilder';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
@@ -161,6 +162,37 @@ describe('extractQueryTextStrings', () => {
expect(texts).toStrictEqual(['env = $deployment_environment']);
});
it('extracts from the AI slot, not builder, for an AI query', () => {
const query: Query = {
...baseQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder: {
queryData: [
{
...initialQueryBuilderFormValues,
filter: { expression: 'env = $ignored' },
},
],
queryFormulas: [],
queryTraceOperator: [],
},
builder_ai_query: {
queryData: [
{
...initialQueryBuilderFormValues,
filter: { expression: 'service.name = $service' },
},
],
queryFormulas: [],
queryTraceOperator: [],
},
};
expect(extractQueryTextStrings(query)).toStrictEqual([
'service.name = $service',
]);
});
it('skips non-string filter values', () => {
const query: Query = {
...baseQuery,

View File

@@ -1,6 +1,8 @@
import { escapeRegExp, isArray } from 'lodash-es';
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import type { QueryBuilderData } from 'types/common/queryBuilder';
/**
* Builds a RegExp that matches any recognized variable reference syntax:
@@ -50,9 +52,11 @@ export function containsAnyVariableReference(text: string): boolean {
return !!text && ANY_VARIABLE_REFERENCE.test(text);
}
function extractQueryBuilderTexts(query: Query): string[] {
function extractQueryBuilderTexts(
builder: QueryBuilderData | undefined,
): string[] {
const texts: string[] = [];
const queryDataList = query.builder?.queryData;
const queryDataList = builder?.queryData;
if (isArray(queryDataList)) {
queryDataList.forEach((queryData) => {
queryData.filters?.items?.forEach((filter: TagFilterItem) => {
@@ -102,13 +106,13 @@ function extractClickhouseSQLTexts(query: Query): string[] {
/**
* Extracts all text strings from a widget Query that could contain variable
* references. Covers:
* - QUERY_BUILDER: filter items' string values + filter.expression
* - QUERY_BUILDER / AI_QUERY_BUILDER: filter items' string values + filter.expression
* - PROM: each promql[].query
* - CLICKHOUSE: each clickhouse_sql[].query
*/
export function extractQueryTextStrings(query: Query): string[] {
if (query.queryType === EQueryType.QUERY_BUILDER) {
return extractQueryBuilderTexts(query);
if (isBuilderQueryType(query.queryType)) {
return extractQueryBuilderTexts(getActiveBuilder(query));
}
if (query.queryType === EQueryType.PROM) {

View File

@@ -0,0 +1,42 @@
import {
initialQueryBuilderFormValuesMap,
PANEL_TYPES,
} from 'constants/queryBuilder';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { mapCompositeQueryFromQuery } from '../mapCompositeQueryFromQuery';
const emptyBuilder = {
queryData: [],
queryFormulas: [],
queryTraceOperator: [],
};
describe('mapCompositeQueryFromQuery', () => {
it('sends an AI query as builder_ai_query envelopes under the builder query type', () => {
const query: Query = {
id: 'q',
queryType: EQueryType.AI_QUERY_BUILDER,
promql: [],
clickhouse_sql: [],
builder: {
...emptyBuilder,
queryData: [
{ ...initialQueryBuilderFormValuesMap.metrics, queryName: 'M' },
],
},
builder_ai_query: {
...emptyBuilder,
queryData: [{ ...initialQueryBuilderFormValuesMap.traces, queryName: 'A' }],
},
};
const composite = mapCompositeQueryFromQuery(query, PANEL_TYPES.TIME_SERIES);
expect(composite.queryType).toBe(EQueryType.QUERY_BUILDER);
expect(
composite.queries?.map((q) => [q.type, (q.spec as { name: string }).name]),
).toStrictEqual([['builder_ai_query', 'A']]);
});
});

View File

@@ -1,5 +1,6 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
import { foldAISlot } from 'lib/query/builderSlot';
import {
BuilderClickHouseResource,
BuilderPromQLResource,
@@ -91,8 +92,13 @@ const buildPromQuery = (
return compositeQuery;
};
const queryTypeMethodMapping = {
const queryTypeMethodMapping: Record<
EQueryType,
(query: Query, panelType: PANEL_TYPES | null) => ICompositeMetricQuery
> = {
[EQueryType.QUERY_BUILDER]: buildBuilderQuery,
[EQueryType.AI_QUERY_BUILDER]: (query, panelType) =>
buildBuilderQuery(foldAISlot(query), panelType),
[EQueryType.CLICKHOUSE]: buildClickHouseQuery,
[EQueryType.PROM]: buildPromQuery,
};

View File

@@ -15,6 +15,7 @@ import {
PromQuery,
QueryBuilderFormula,
} from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import {
convertBuilderQueryToIBuilderQuery,
convertQueryBuilderFormulaToIBuilderFormula,
@@ -37,6 +38,7 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
> = {};
const promQueries: IPromQLQuery[] = [];
const clickhouseQueries: IClickHouseQuery[] = [];
const isAIQuery = compositeQuery.queryType === EQueryType.AI_QUERY_BUILDER;
compositeQuery.queries?.forEach((q) => {
const spec = q.spec as BuilderQuery | PromQuery | ClickHouseQuery;
@@ -49,10 +51,13 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
}
} else if (q.type === 'builder_ai_query') {
if (spec.name) {
builderQueries[spec.name] = {
...convertBuilderQueryToIBuilderQuery(spec as BuilderQuery),
builderQueryType: 'builder_ai_query',
};
const builderQuery = convertBuilderQueryToIBuilderQuery(
spec as BuilderQuery,
);
// Only AI queries kept in `builder` (alerts) need the tag; the AI slot marks its own.
builderQueries[spec.name] = isAIQuery
? builderQuery
: { ...builderQuery, builderQueryType: 'builder_ai_query' };
builderQueryTypes[spec.name] = 'builder_ai_query';
}
} else if (q.type === 'builder_formula') {
@@ -87,8 +92,14 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
});
}
});
const builder = transformQueryBuilderDataModel(
builderQueries,
builderQueryTypes,
);
return {
builder: transformQueryBuilderDataModel(builderQueries, builderQueryTypes),
builder: isAIQuery ? transformQueryBuilderDataModel({}) : builder,
...(isAIQuery && { builder_ai_query: builder }),
promql: promQueries,
clickhouse_sql: clickhouseQueries,
queryType: compositeQuery.queryType,

View File

@@ -0,0 +1,131 @@
import {
initialQueriesMap,
initialQueryAIWithType,
} from 'constants/queryBuilder';
import {
getActiveBuilder,
getBuilderSlotKeyForQueryType,
isAIQueryType,
isBuilderQueryType,
foldAISlot,
toSlotQuery,
} from 'lib/query/builderSlot';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
const baseQuery = initialQueriesMap[DataSource.METRICS];
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
describe('isBuilderQueryType', () => {
it.each([
[EQueryType.QUERY_BUILDER, true],
[EQueryType.AI_QUERY_BUILDER, true],
[EQueryType.CLICKHOUSE, false],
[EQueryType.PROM, false],
])('%s → %s', (queryType, expected) => {
expect(isBuilderQueryType(queryType)).toBe(expected);
});
});
describe('getBuilderSlotKeyForQueryType', () => {
it.each([
[EQueryType.QUERY_BUILDER, EQueryType.QUERY_BUILDER],
[EQueryType.CLICKHOUSE, EQueryType.QUERY_BUILDER],
[EQueryType.PROM, EQueryType.QUERY_BUILDER],
[EQueryType.AI_QUERY_BUILDER, EQueryType.AI_QUERY_BUILDER],
])('maps %s to %s', (queryType, slotKey) => {
expect(getBuilderSlotKeyForQueryType(queryType)).toBe(slotKey);
});
});
describe('getActiveBuilder', () => {
it('reads builder for the Query Builder type', () => {
const query: Query = { ...baseQuery, builder_ai_query: aiBuilder };
expect(getActiveBuilder(query)).toBe(baseQuery.builder);
});
it('reads the AI slot for the AI type', () => {
const query: Query = {
...baseQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: aiBuilder,
};
expect(getActiveBuilder(query)).toBe(aiBuilder);
});
it('reads an unused AI slot as holding no queries', () => {
const query: Query = { ...baseQuery, queryType: EQueryType.AI_QUERY_BUILDER };
expect(getActiveBuilder(query)).toStrictEqual({
queryData: [],
queryFormulas: [],
queryTraceOperator: [],
});
});
it('keeps builder for ClickHouse and PromQL', () => {
const query: Query = { ...baseQuery, queryType: EQueryType.PROM };
expect(getActiveBuilder(query)).toBe(baseQuery.builder);
});
});
describe('foldAISlot', () => {
it('passes non-AI queries through untouched', () => {
expect(foldAISlot(baseQuery)).toBe(baseQuery);
});
it('sends AI as a builder query holding the AI slot, every query tagged', () => {
const untagged = {
...aiBuilder.queryData[0],
builderQueryType: undefined,
};
const query: Query = {
...baseQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: { ...aiBuilder, queryData: [untagged] },
};
const foldedQuery = foldAISlot(query);
expect(foldedQuery.queryType).toBe(EQueryType.QUERY_BUILDER);
expect(foldedQuery.builder.queryData).toStrictEqual([
{ ...untagged, builderQueryType: 'builder_ai_query' },
]);
});
});
describe('isAIQueryType', () => {
it.each([
[EQueryType.AI_QUERY_BUILDER, true],
[EQueryType.QUERY_BUILDER, false],
[EQueryType.CLICKHOUSE, false],
[EQueryType.PROM, false],
])('%s → %s', (queryType, expected) => {
expect(isAIQueryType(queryType)).toBe(expected);
});
});
describe('toSlotQuery', () => {
it('returns non-AI queries unchanged', () => {
expect(toSlotQuery(baseQuery, baseQuery)).toBe(baseQuery);
});
it('moves request-shape builder edits back into the AI slot', () => {
const slotQuery: Query = {
...baseQuery,
queryType: EQueryType.AI_QUERY_BUILDER,
builder_ai_query: aiBuilder,
};
const requestQuery = foldAISlot(slotQuery);
const refined: Query = {
...requestQuery,
builder: { ...requestQuery.builder, queryFormulas: [] },
};
const restored = toSlotQuery(refined, slotQuery);
expect(restored.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
expect(restored.builder).toBe(baseQuery.builder);
expect(restored.builder_ai_query).toBe(refined.builder);
});
});

View File

@@ -32,6 +32,17 @@ export function isAIBuilderEnvelope(
);
}
/** Exactly one `builder_query`: the only request a panel's default row limit applies to. */
export function isLoneBuilderQuery<T extends { type: string }>(
envelopes: T[],
): envelopes is [Extract<T, Querybuildertypesv5QueryEnvelopeBuilderDTO>] {
return (
envelopes.length === 1 &&
envelopes[0].type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
);
}
const BUILDER_PLUGIN_KINDS: string[] = [
DashboardtypesQueryPluginKindDTO['signoz/BuilderQuery'],
DashboardtypesQueryPluginKindDTO['signoz/AIBuilderQuery'],

View File

@@ -0,0 +1,98 @@
import { Querybuildertypesv5QueryTypeDTO } from 'api/generated/services/sigNoz.schemas';
import type {
Query,
QueryState,
} from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import type { QueryBuilderData } from 'types/common/queryBuilder';
export type BuilderSlotKey =
| EQueryType.QUERY_BUILDER
| EQueryType.AI_QUERY_BUILDER;
const EMPTY_BUILDER: QueryBuilderData = {
queryData: [],
queryFormulas: [],
queryTraceOperator: [],
};
/** Query Builder and AI Query Builder; both author builder queries, each in its own slot. */
export function isBuilderQueryType(queryType: EQueryType): boolean {
return (
queryType === EQueryType.QUERY_BUILDER ||
queryType === EQueryType.AI_QUERY_BUILDER
);
}
export function isAIQueryType(queryType: EQueryType): boolean {
return queryType === EQueryType.AI_QUERY_BUILDER;
}
/** The `Query` slot builder edits land in; non-builder types keep `builder`, as they always have. */
export function getBuilderSlotKeyForQueryType(
queryType: EQueryType,
): BuilderSlotKey {
return isAIQueryType(queryType)
? EQueryType.AI_QUERY_BUILDER
: EQueryType.QUERY_BUILDER;
}
/**
* The query as the backend takes it. AI goes out as a `builder` query whose queries carry
* `builderQueryType: builder_ai_query`, the tag set from the slot so a stale one can't leak.
*/
export function foldAISlot(query: Query): Query {
if (!isAIQueryType(query.queryType)) {
return query;
}
const aiBuilder = getActiveBuilder(query);
return {
...query,
queryType: EQueryType.QUERY_BUILDER,
builder: {
...aiBuilder,
queryData: aiBuilder.queryData.map((queryData) => ({
...queryData,
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_ai_query,
})),
},
};
}
/** Undoes `foldAISlot` for `slotQuery`: builder edits made on the request shape land back in its slot. */
export function toSlotQuery(requestQuery: Query, slotQuery: Query): Query {
if (!isAIQueryType(slotQuery.queryType)) {
return requestQuery;
}
return {
...requestQuery,
queryType: slotQuery.queryType,
builder: slotQuery.builder,
builder_ai_query: requestQuery.builder,
};
}
/** The builder at `slotKey`; an unused AI slot holds none. */
export function getBuilderBySlotKey(
state: QueryState,
slotKey: BuilderSlotKey,
): QueryBuilderData {
return state[slotKey] ?? EMPTY_BUILDER;
}
/** `state` with the builder at `slotKey` replaced. */
export function replaceBuilderBySlotKey<T extends QueryState>(
state: T,
slotKey: BuilderSlotKey,
builder: QueryBuilderData,
): T {
return { ...state, [slotKey]: builder };
}
/** The builder queries `queryType` authors; an unused AI slot holds none. */
export function getActiveBuilder(query: Query): QueryBuilderData {
return getBuilderBySlotKey(
query,
getBuilderSlotKeyForQueryType(query.queryType),
);
}

View File

@@ -12,6 +12,7 @@ import {
import { FORMULA_REGEXP } from 'constants/regExp';
import { QUERY_TABLE_CONFIG } from 'container/QueryTable/config';
import { QueryTableProps } from 'container/QueryTable/QueryTable.intefaces';
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
import { get, isEqual, isNaN, isObject } from 'lodash-es';
import {
IBuilderFormula,
@@ -93,8 +94,8 @@ const getQueryByName = <T extends keyof QueryBuilderData>(
queryArray.find((q) => q.name === currentQueryName) || defaultQueryValue
);
}
if (query.queryType === EQueryType.QUERY_BUILDER) {
const queryArray = (query.builder[type] || []) as (
if (isBuilderQueryType(query.queryType)) {
const queryArray = (getActiveBuilder(query)[type] || []) as (
| IBuilderQuery
| IBuilderFormula
)[];
@@ -173,7 +174,7 @@ const addOperatorFormulaColumns = (
return;
}
if (queryType === EQueryType.QUERY_BUILDER) {
if (isBuilderQueryType(queryType)) {
const currentQueryData = query as IBuilderQuery;
let operatorLabel = `${currentQueryData.aggregateOperator}`;
if (currentQueryData.aggregateAttribute?.key) {

View File

@@ -124,50 +124,59 @@ export function handleQueryChange(
): Query {
return {
...supersetQuery,
builder: {
...supersetQuery.builder,
queryData: supersetQuery.builder.queryData.map((query, index) => {
const { dataSource } = query;
const tempQuery = cloneDeep(initialQueryBuilderFormValuesMap[dataSource]);
const fieldsToSelect =
panelTypeDataSourceFormValuesMap[newPanelType][dataSource].builder
.queryData;
fieldsToSelect.forEach((field) => {
set(tempQuery, field, supersetQuery.builder.queryData[index][field]);
});
if (newPanelType === PANEL_TYPES.LIST) {
set(tempQuery, 'aggregateOperator', 'noop');
set(tempQuery, 'offset', 0);
set(tempQuery, 'pageSize', 10);
set(tempQuery, 'orderBy', undefined);
} else if (tempQuery.aggregateOperator === 'noop') {
// this condition takes care of the part where we start with the list panel type and then shift to other panels
// because in other cases we never set list operator and other fields in superset query rather just update in the current / staged query
set(tempQuery, 'aggregateOperator', 'count');
unset(tempQuery, 'offset');
unset(tempQuery, 'pageSize');
}
if (
currentPanelType === PANEL_TYPES.LIST &&
newPanelType !== PANEL_TYPES.LIST
) {
set(tempQuery, 'orderBy', undefined);
}
return tempQuery;
}),
queryFormulas: withHeatmapBucketOptions(
supersetQuery.builder.queryFormulas,
newPanelType,
),
queryTraceOperator:
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
? []
: supersetQuery.builder.queryTraceOperator,
},
builder: rebuildBuilderForPanelType(
newPanelType,
supersetQuery.builder,
currentPanelType,
),
};
}
export function rebuildBuilderForPanelType(
newPanelType: keyof PartialPanelTypes,
builder: Query['builder'],
currentPanelType: PANEL_TYPES,
): Query['builder'] {
return {
...builder,
queryData: builder.queryData.map((query, index) => {
const { dataSource } = query;
const tempQuery = cloneDeep(initialQueryBuilderFormValuesMap[dataSource]);
const fieldsToSelect =
panelTypeDataSourceFormValuesMap[newPanelType][dataSource].builder
.queryData;
fieldsToSelect.forEach((field) => {
set(tempQuery, field, builder.queryData[index][field]);
});
if (newPanelType === PANEL_TYPES.LIST) {
set(tempQuery, 'aggregateOperator', 'noop');
set(tempQuery, 'offset', 0);
set(tempQuery, 'pageSize', 10);
set(tempQuery, 'orderBy', undefined);
} else if (tempQuery.aggregateOperator === 'noop') {
// this condition takes care of the part where we start with the list panel type and then shift to other panels
// because in other cases we never set list operator and other fields in superset query rather just update in the current / staged query
set(tempQuery, 'aggregateOperator', 'count');
unset(tempQuery, 'offset');
unset(tempQuery, 'pageSize');
}
if (
currentPanelType === PANEL_TYPES.LIST &&
newPanelType !== PANEL_TYPES.LIST
) {
set(tempQuery, 'orderBy', undefined);
}
return tempQuery;
}),
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
queryTraceOperator:
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
? []
: builder.queryTraceOperator,
};
}

View File

@@ -18,6 +18,7 @@ export type PartialPanelTypes = {
[PANEL_TYPES.HISTOGRAM]: 'histogram';
[PANEL_TYPES.HEATMAP]: 'heatmap';
[PANEL_TYPES.GEO_MAP]: 'geo_map';
[PANEL_TYPES.TOP_LIST]: 'top_list';
};
export type BuilderField = keyof IBuilderQuery;
@@ -154,6 +155,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.GEO_MAP]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.TOP_LIST]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.VALUE]: bySource(SINGLE_VALUE, SINGLE_VALUE_METRICS),
[PANEL_TYPES.LIST]: bySource(RAW_ROWS, RAW_ROWS_METRICS),
};

View File

@@ -1,51 +0,0 @@
import {
BuilderVariant,
type Query,
QueryMode,
} from 'types/api/queryBuilder/queryBuilderData';
/** Which variant the `builder` slot holds, whatever query type is active. */
export function getBuilderVariant(builder: Query['builder']): BuilderVariant {
return builder.queryData[0]?.builderQueryType === QueryMode.AI_QUERY_BUILDER
? BuilderVariant.AI
: BuilderVariant.MAIN;
}
/** The variant a tab authors; `undefined` for tabs that own their own slot. */
export function toBuilderVariant(mode: QueryMode): BuilderVariant | undefined {
if (mode === QueryMode.AI_QUERY_BUILDER) {
return BuilderVariant.AI;
}
return mode === QueryMode.QUERY_BUILDER ? BuilderVariant.MAIN : undefined;
}
/** The tab a query belongs to: its query type, or AI when a builder query carries the tag. */
export function getQueryMode(query: Query): QueryMode {
if (query.queryType !== QueryMode.QUERY_BUILDER) {
return query.queryType;
}
return getBuilderVariant(query.builder) === BuilderVariant.AI
? QueryMode.AI_QUERY_BUILDER
: QueryMode.QUERY_BUILDER;
}
/** Query Builder and AI both author `Query.builder`; the other modes own their own slot. */
export function isBuilderMode(mode: QueryMode): boolean {
return toBuilderVariant(mode) !== undefined;
}
/** Drops the AI tag, leaving the same query readable as a plain builder query. */
export function withoutAIQueryTag(query: Query): Query {
if (getBuilderVariant(query.builder) !== BuilderVariant.AI) {
return query;
}
return {
...query,
builder: {
...query.builder,
queryData: query.builder.queryData.map(
({ builderQueryType: _tag, ...queryData }) => queryData,
),
},
};
}

View File

@@ -1,3 +1,4 @@
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { validateQuery } from 'utils/queryValidationUtils';
@@ -102,6 +103,23 @@ describe('saveRecentQuery', () => {
expect(store.list('metrics')).toHaveLength(0);
});
it('saves from the AI slot when the query type is AI', () => {
saveRecentQuery({
queryType: EQueryType.AI_QUERY_BUILDER,
builder: buildComposite([{ filter: { expression: "service.name = 'qb'" } }])
.builder,
builder_ai_query: buildComposite([
{
dataSource: DataSource.TRACES,
filter: { expression: "service.name = 'ai'" },
},
]).builder,
});
expect(store.list('logs')).toHaveLength(0);
expect(store.list('traces')[0].filter.expression).toBe("service.name = 'ai'");
});
it('is a no-op when the composite is null, undefined, or empty', () => {
saveRecentQuery(null);
saveRecentQuery(undefined);

View File

@@ -1,5 +1,7 @@
import { getBuilderSlotKeyForQueryType } from 'lib/query/builderSlot';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import type { SignalType } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { validateQuery } from 'utils/queryValidationUtils';
import * as store from './recentQueriesStore';
@@ -16,7 +18,9 @@ function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
}
type CompositeWithBuilder = {
queryType?: EQueryType;
builder?: { queryData?: IBuilderQuery[] };
builder_ai_query?: { queryData?: IBuilderQuery[] };
};
export function saveRecentQueryByExpression(
@@ -43,13 +47,16 @@ export function saveRecentQueryByExpression(
});
}
// Persists each builder query in the composite as a recent entry. Call this
// Persists each query of the composite's active builder as a recent entry. Call this
// only from explicit user-driven Run triggers — reacting to stagedQuery or any
// other derived state pollutes recents with navigation/refresh/go-to traffic.
export function saveRecentQuery(
query: CompositeWithBuilder | null | undefined,
): void {
const queryData = query?.builder?.queryData;
const slotKey = getBuilderSlotKeyForQueryType(
query?.queryType ?? EQueryType.QUERY_BUILDER,
);
const queryData = query?.[slotKey]?.queryData;
if (!Array.isArray(queryData) || queryData.length === 0) {
return;
}

View File

@@ -1,14 +1,9 @@
import { useMemo } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ScatterTooltipProps } from '../types';
import TooltipCard from './components/TooltipCard/TooltipCard';
import { buildChannelRows, resolveHoveredPoint } from './scatterTooltipContent';
import Styles from './ScatterTooltip.module.scss';
/** Own component: the shared Tooltip lists one row per series at a shared x. */
export default function ScatterTooltip({
uPlotInstance,
@@ -50,90 +45,18 @@ export default function ScatterTooltip({
}
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid="scatter-tooltip"
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{
backgroundColor: hoveredPoint.color,
borderColor: hoveredPoint.color,
}}
/>
<Typography.Text
as="span"
className={Styles.title}
title={hoveredPoint.label}
testId="scatter-tooltip-title"
>
{hoveredPoint.label}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId="scatter-tooltip-status"
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div
key={row.label}
className={Styles.row}
data-testid="scatter-tooltip-row"
>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{labels.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{labels.map((label) => (
<div
key={label.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid="scatter-tooltip-label"
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={label.key}
>
{label.key}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={label.value}
>
{label.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{renderTooltipFooter?.({ isPinned, dismiss })}
</div>
<TooltipCard
title={hoveredPoint.label}
color={hoveredPoint.color}
rows={rows.map((row) => ({ key: row.label, ...row }))}
mutedRows={labels.map((label) => ({
key: label.key,
label: label.key,
value: label.value,
}))}
isPinned={isPinned}
footer={renderTooltipFooter?.({ isPinned, dismiss })}
testId="scatter-tooltip"
/>
);
}

View File

@@ -49,7 +49,7 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-weight: 600;
color: var(--text-vanilla-100);
color: var(--l1-foreground);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -70,11 +70,11 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-variant-numeric: tabular-nums;
color: var(--text-vanilla-100);
color: var(--l1-foreground);
}
.rowMuted {
color: var(--text-vanilla-400);
color: var(--l3-foreground);
}
.rowLabel {

View File

@@ -0,0 +1,119 @@
import type { ReactNode } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import Styles from './TooltipCard.module.scss';
export interface TooltipCardRow {
key: string;
label: string;
value: string;
}
interface TooltipCardProps {
title: string;
/** The marker beside the title, matching the item's mark on the chart. */
color: string;
/** What the item says. */
rows: TooltipCardRow[];
/** What names the item, below the rows and muted. */
mutedRows?: TooltipCardRow[];
isPinned?: boolean;
footer?: ReactNode;
/** Prefixes the test ids of the title, status, rows and muted rows. */
testId: string;
}
/** One item's tooltip: a marked title, then label/value rows, on the shared tooltip surface. */
export default function TooltipCard({
title,
color,
rows,
mutedRows = [],
isPinned = false,
footer,
testId,
}: TooltipCardProps): JSX.Element {
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid={testId}
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{ backgroundColor: color, borderColor: color }}
/>
<Typography.Text
as="span"
className={Styles.title}
title={title}
testId={`${testId}-title`}
>
{title}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId={`${testId}-status`}
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div key={row.key} className={Styles.row} data-testid={`${testId}-row`}>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{mutedRows.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{mutedRows.map((row) => (
<div
key={row.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid={`${testId}-label`}
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={row.label}
>
{row.label}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={row.value}
>
{row.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{footer}
</div>
);
}

View File

@@ -1,10 +1,9 @@
import { Flame } from '@signozhq/icons';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getQueryMode } from 'lib/query/queryMode';
import { isAIQueryType } from 'lib/query/builderSlot';
import { getPanelDefinition } from 'pages/DashboardPage/DashboardContainer/Panels/registry';
import { useCreateAlertFromPanel } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useCreateAlertFromPanel';
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
import ConfigActionRow from './ConfigActionRow';
import styles from './ConfigActions.module.scss';
@@ -31,10 +30,7 @@ function ConfigActions({
// Only kinds whose query can seed an alert offer this today; mirror the panel
// menu's create-alert capability.
//TODO: AI query check should be removed after we support alerts on ai query @tewarig
if (
!actions.createAlert ||
getQueryMode(currentQuery) === QueryMode.AI_QUERY_BUILDER
) {
if (!actions.createAlert || isAIQueryType(currentQuery.queryType)) {
return null;
}

View File

@@ -81,7 +81,7 @@ describe('PanelTypeSwitcher', () => {
return {
...OPTIONS.find((option) => option.kind === kind),
mode: kind === 'signoz/TextPanel' ? 'static' : 'query',
supportedQueryModesKindMap: Object.fromEntries(
supportedQueryTypesKindMap: Object.fromEntries(
queryTypes.map((queryType) => [
queryType,
queryType === EQueryType.QUERY_BUILDER

View File

@@ -25,6 +25,25 @@ describe('getPanelTypeDisabledReason', () => {
).toBeUndefined();
});
it('offers the AI kinds to an AI query and explains the rest', () => {
expect(
getPanelTypeDisabledReason({
kind: 'signoz/TimeSeriesPanel',
queryType: EQueryType.AI_QUERY_BUILDER,
signal: TelemetrytypesSignalDTO.traces,
label: 'Time Series',
}),
).toBeUndefined();
expect(
getPanelTypeDisabledReason({
kind: 'signoz/HeatmapPanel',
queryType: EQueryType.AI_QUERY_BUILDER,
signal: TelemetrytypesSignalDTO.traces,
label: 'Heatmap',
}),
).toBe("Heatmap isn't available for AI Query Builder queries");
});
it('explains an unsupported query type', () => {
expect(
getPanelTypeDisabledReason({

View File

@@ -12,6 +12,7 @@ const QUERY_TYPE_LABEL: Record<EQueryType, string> = {
[EQueryType.QUERY_BUILDER]: 'Query Builder',
[EQueryType.CLICKHOUSE]: 'ClickHouse',
[EQueryType.PROM]: 'PromQL',
[EQueryType.AI_QUERY_BUILDER]: 'AI Query Builder',
};
const SIGNAL_LABEL: Record<TelemetrytypesSignalDTO, string> = {

View File

@@ -26,6 +26,22 @@ export const SWITCH_SKETCHES = {
))}
</SketchSvg>
),
rank: (
<SketchSvg>
{[5, 11, 17].map((y, index) => (
<g key={y}>
<circle cx={4} cy={y} r={1.2} fill="var(--l3-foreground)" />
<path d={`M9 ${y} H${36 - index * 9}`} />
</g>
))}
</SketchSvg>
),
share: (
<SketchSvg>
<path d="M3 11 H37" strokeDasharray="3 3" />
<rect x={3} y={8} width={22} height={6} fill="var(--l3-foreground)" />
</SketchSvg>
),
combine: (
<SketchSvg>
<rect x={4} y={10} width={6} height={10} />

View File

@@ -26,6 +26,7 @@ import { fitBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Panels/k
import type { SeededPluginSpec } from 'pages/DashboardPage/DashboardContainer/Panels/utils/buildPluginSpec';
import type { SectionEditorContext } from './sectionContext';
import AppearanceSection from './sections/AppearanceSection/AppearanceSection';
import AxesSection from './sections/AxesSection/AxesSection';
import BucketsSection from './sections/BucketsSection/BucketsSection';
import ChartAppearanceSection from './sections/ChartAppearanceSection/ChartAppearanceSection';
@@ -151,6 +152,13 @@ export const SECTION_REGISTRY: {
update: (spec, chartAppearance): PanelSpec =>
updatePluginSlice(spec, 'chartAppearance', chartAppearance),
},
[SectionKind.Appearance]: {
Component: AppearanceSection,
get: (spec): SectionSpecMap[SectionKind.Appearance] | undefined =>
getPluginSlice<SectionSpecMap[SectionKind.Appearance]>(spec, 'appearance'),
update: (spec, appearance): PanelSpec =>
updatePluginSlice(spec, 'appearance', appearance),
},
[SectionKind.Visualization]: {
Component: VisualizationSection,
get: (spec): PanelVisualizationSlice | undefined =>

View File

@@ -0,0 +1,65 @@
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import ConfigSwitch from '../../controls/ConfigSwitch/ConfigSwitch';
import { SWITCH_SKETCHES } from '../../controls/drawings/switchSketches';
import { createFieldResetter } from '../../utils/changes';
import BarColorField from './BarColorField';
import { DEFAULT_BAR_COLOR } from './barColorOptions';
/**
* Edits the `appearance` slice of a Top List panel spec: bar color, row numbers and
* each row's share of the listed total. Each control is gated by its `controls` flag.
*/
function AppearanceSection({
value,
savedValue,
controls,
onChange,
}: SectionEditorProps<SectionKind.Appearance>): JSX.Element {
const reset = createFieldResetter(value, savedValue, onChange);
const appearance = {
...value,
barColor: value?.barColor || DEFAULT_BAR_COLOR,
};
return (
<>
{controls.barColor && (
<BarColorField
{...reset('barColor')}
value={appearance.barColor}
onChange={(barColor): void => onChange({ ...appearance, barColor })}
/>
)}
{controls.showRank && (
<ConfigSwitch
testId="panel-editor-v2-show-rank"
title="Show rank"
description="Numbers each row by its position."
sketch={SWITCH_SKETCHES.rank}
changed={reset('showRank').changed}
value={appearance.showRank ?? false}
onChange={(showRank): void => onChange({ ...appearance, showRank })}
/>
)}
{controls.showShare && (
<ConfigSwitch
testId="panel-editor-v2-show-share"
title="Show share of total"
description="Each row's percentage of the listed rows' sum. Suits counts and sums, not averages or percentiles."
sketch={SWITCH_SKETCHES.share}
changed={reset('showShare').changed}
value={appearance.showShare ?? false}
onChange={(showShare): void => onChange({ ...appearance, showShare })}
/>
)}
</>
);
}
export default AppearanceSection;

View File

@@ -0,0 +1,42 @@
import ColorSwatches from '../../controls/ColorSwatches/ColorSwatches';
import ConfigField from '../../controls/ConfigField/ConfigField';
import type { FieldResetProps } from '../../utils/changes';
import { BAR_COLOR_OPTIONS, findBarColorPreset } from './barColorOptions';
interface BarColorFieldProps extends Partial<FieldResetProps> {
value: string;
onChange: (barColor: string) => void;
}
function BarColorField({
value,
onChange,
changed,
onReset,
}: BarColorFieldProps): JSX.Element {
const preset = findBarColorPreset(value);
return (
<ConfigField
label="Bar color"
help="Fills every row's bar."
changed={changed}
onReset={onReset}
>
<ColorSwatches
testId="panel-editor-v2-bar-color"
label="Bar color"
value={preset}
options={BAR_COLOR_OPTIONS}
onChange={onChange}
custom={{
value: preset ? undefined : value,
initial: value,
onChange,
}}
/>
</ConfigField>
);
}
export default BarColorField;

View File

@@ -0,0 +1,93 @@
import { Color } from '@signozhq/design-tokens';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import {
render as renderWithProviders,
screen,
userEvent,
} from 'tests/test-utils';
import AppearanceSection from '../AppearanceSection';
type OnChange = SectionEditorProps<SectionKind.Appearance>['onChange'];
// Color swatches use a radix tooltip, which needs a TooltipProvider ancestor.
const render = (ui: JSX.Element): ReturnType<typeof renderWithProviders> =>
renderWithProviders(<TooltipProvider>{ui}</TooltipProvider>);
describe('AppearanceSection', () => {
it('renders only the controls whose flag is set', () => {
render(
<AppearanceSection
value={undefined}
controls={{ showRank: true }}
onChange={jest.fn()}
/>,
);
expect(screen.getByTestId('panel-editor-v2-show-rank')).toBeInTheDocument();
expect(
screen.queryByTestId('panel-editor-v2-show-share'),
).not.toBeInTheDocument();
});
it.each([
{ testId: 'panel-editor-v2-show-rank', field: 'showRank' },
{ testId: 'panel-editor-v2-show-share', field: 'showShare' },
])('toggles $field through onChange', async ({ testId, field }) => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: false, showShare: false, barColor: '#4E74F8' }}
controls={{ showRank: true, showShare: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId(testId));
expect(onChange).toHaveBeenCalledWith({
showRank: false,
showShare: false,
barColor: '#4E74F8',
[field]: true,
});
});
it('picks a bar color, keeping the other fields', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: true, barColor: '#4E74F8' }}
controls={{ barColor: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('panel-editor-v2-bar-color-forest'));
expect(onChange).toHaveBeenCalledWith({
showRank: true,
barColor: Color.BG_FOREST_500,
});
});
it('shows the default bar color when the spec has none', () => {
render(
<AppearanceSection
value={undefined}
controls={{ barColor: true }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-bar-color-robin').querySelector('input'),
).toBeChecked();
});
});

View File

@@ -0,0 +1,26 @@
import { Color } from '@signozhq/design-tokens';
import type { ColorSwatchOption } from '../../controls/ColorSwatches/ColorSwatches';
export const BAR_COLOR_OPTIONS: ColorSwatchOption<string>[] = [
{ id: 'robin', color: Color.BG_ROBIN_500 },
{ id: 'aqua', color: Color.BG_AQUA_500 },
{ id: 'forest', color: Color.BG_FOREST_500 },
{ id: 'amber', color: Color.BG_AMBER_500 },
{ id: 'sienna', color: Color.BG_SIENNA_500 },
].map(({ id, color }) => ({
value: color,
id,
label: id.charAt(0).toUpperCase() + id.slice(1),
fill: color,
}));
/** Matches the server's default for an unset `appearance.barColor`. */
export const DEFAULT_BAR_COLOR = Color.BG_ROBIN_500;
/** The preset a hex matches, ignoring case. */
export function findBarColorPreset(hex: string): string | undefined {
return BAR_COLOR_OPTIONS.find(
(option) => option.value.toLowerCase() === hex.toLowerCase(),
)?.value;
}

View File

@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { useDashboardVariableNames } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardVariableNames';
import type { VariableItem } from './types';
@@ -20,13 +21,16 @@ const GLOBAL_TIMESTAMP_VARIABLES: VariableItem[] = [
*/
export function useContextLinkVariables(): VariableItem[] {
const { currentQuery } = useQueryBuilder();
const activeBuilderQueryData = currentQuery
? getActiveBuilder(currentQuery).queryData
: undefined;
const dashboardVariableNames = useDashboardVariableNames();
// `_`-prefixed to match V1 and avoid colliding with dashboard-variable names.
const fieldVariableNames = useMemo(() => {
const names = new Set<string>();
(currentQuery?.builder?.queryData ?? []).forEach((query) => {
(activeBuilderQueryData ?? []).forEach((query) => {
(query.groupBy ?? []).forEach((field) => {
if (field.key) {
names.add(`_${field.key}`);
@@ -34,7 +38,7 @@ export function useContextLinkVariables(): VariableItem[] {
});
});
return Array.from(names);
}, [currentQuery?.builder?.queryData]);
}, [activeBuilderQueryData]);
return useMemo(
() => [

View File

@@ -14,7 +14,7 @@ jest.mock('pages/DashboardPage/DashboardContainer/Panels/registry', () => ({
displayName: 'Time Series',
icon: (): null => null,
mode: 'query',
supportedQueryModesKindMap: {
supportedQueryTypesKindMap: {
builder: { kind: 'signal', signals: ['metrics', 'logs', 'traces'] },
clickhouse_sql: { kind: 'signal-less' },
promql: { kind: 'signal-less' },

Some files were not shown because too many files have changed in this diff Show More