Compare commits

...

3 Commits

Author SHA1 Message Date
Abhi kumar
084a127bee feat(dashboard): add distribution panel spec (#13535)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
#### Description

- Adds the `signoz/DistributionPanel` plugin spec: bucket counts summed
over the time range, drawn as bars over the bucket bounds. Built on the
`distribution` query_range type from #13379.
- `axes.x`: optional `min` / `max` (validated `min <= max`); every
bucket is drawn equally wide, so there is no x scale. `axes.y.scale`:
`linear` (default) or `log`.
- `visualization.stack` reuses `StackMode`: `normal` (Distribution's
default, written by the backend), `none` (side by side) or `percent`.
`chartAppearance.percentiles`: the backend writes `enabled: true` and
`[50, 90, 99]` when unset, so both are required; values in (0, 100), at
most 5, no duplicates.
- Regenerated `openapi.yml` and the frontend API clients.
- Allowed query kinds match Heatmap.

#### Issues

Closes https://github.com/SigNoz/pulse-pod/issues/699
Closes https://github.com/SigNoz/pulse-pod/issues/665

#### Additional Information

- The generated TS adds `signoz/DistributionPanel` to the panel-kind
union, so `tsc` fails on this PR alone: the exhaustive panel-kind maps
gain the kind in #13537. The stack type-checks once #13537 is on top.
- Stack: #13536 (chart) → this PR → #13537 (panel).

---------

Co-authored-by: Naman Verma <naman.verma@signoz.io>
2026-12-03 17:45:09 +00:00
Swapnil Nakade
9cc5050ba8 feat(telemetrymetadata): discover audit field keys and values from signoz_audit (#13792)
#### Description

- Wire `GET /api/v1/fields/keys` and `GET /api/v1/fields/values` for
`signal=logs&source=audit` by querying `signoz_audit.distributed_logs`
and `signoz_audit.distributed_logs_resource`, skipping complex
non-scalar JSON types (arrays, objects, maps).
- Apply a fixed 30-day lookback to audit field key and value
suggestions, while letting query-building `GetKeysMulti` lookups honor
the query's `[start, end]` range so older audit searches still resolve
resource and attribute keys.
- Short-circuit `GetRelatedValues` for `source=audit` so passing
`existingQuery` does not fall through to
`signoz_metadata.distributed_attributes_metadata` for regular logs.

#### Issues closed by this PR
Closes https://github.com/SigNoz/keystone-pod/issues/240
2026-12-03 17:30:53 +00:00
Nityananda Gohain
5f9e9ef881 feat(trace-details): implement query on the span list routes (#13745)
#### Description

- Implements `query` on the four span list routes: a filter expression
such as `search('worldpay') AND has_error = true`, parsed and resolved
as in the trace explorer.
- `search()` now works on traces (it was logs-only). It matches text,
ignoring case, in the span name, status message, attributes, resource
attributes and events; a second argument limits it to `span`,
`attribute`, `resource` or `event`. The trace explorer, dashboards and
alerts get it too.
- A new `SupportsSearchFunction` trait gates `search()` separately from
the body functions (`has`, `hasToken`, …), which stay logs-only.
- Traces queries with `search()` carry the logs cost guard
(`search_max_scan_rows`) and its advisory warning. Trace operator and
trace-scoped aggregation queries, which have no scan budget, reject
`search()` with a 400.
- The span list finds the matching span ids in one extra query before
the tree is read, so a query that cannot be parsed returns 400 without
loading the trace. Each item carries `matches`: up to three places the
text was found, with a snippet.

  #### Additional Information

  - Text outside `search()` is rejected on traces with a 400.
- Measured locally, `query` adds about 60–90 ms on 30,000 spans, and 75
ms to 0.36 s on 1 million spans depending on how many spans match.

  Refs SigNoz/nerve-pod#651
2026-12-03 17:09:08 +00:00
134 changed files with 5149 additions and 447 deletions

View File

@@ -4523,6 +4523,121 @@ components:
required:
- name
type: object
DashboardtypesDistributionAxes:
properties:
x:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionXAxis'
description: The bucket axis.
"y":
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYAxis'
description: The count axis.
type: object
DashboardtypesDistributionChartAppearance:
properties:
percentiles:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPercentiles'
description: Percentile markers drawn across the bucket axis.
type: object
DashboardtypesDistributionPanelSpec:
properties:
axes:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionAxes'
description: The X (bucket) axis range and Y (count) axis scale.
chartAppearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionChartAppearance'
description: Percentile markers.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the bucket bounds; counts take
no unit.
legend:
allOf:
- $ref: '#/components/schemas/DashboardtypesLegend'
description: Legend placement and series colors.
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionVisualization'
description: The time range the bucket counts are summed over, and how groups
stack.
type: object
DashboardtypesDistributionPercentileValues:
items:
format: double
type: number
maxItems: 5
type: array
uniqueItems: true
DashboardtypesDistributionPercentiles:
properties:
enabled:
description: Whether percentile markers are drawn. Null draws them.
nullable: true
type: boolean
values:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPercentileValues'
description: The percentiles to mark, each greater than 0 and less than
100, at most 5, no repeats. Null or omitted marks 50, 90 and 99; [] marks
none.
required:
- values
type: object
DashboardtypesDistributionStackMode:
enum:
- normal
- none
- percent
type: string
DashboardtypesDistributionVisualization:
properties:
stack:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionStackMode'
description: 'How groups combine in a bucket: normal (default) stacks them,
none draws them side by side, percent stacks them as shares of the bucket.'
timePreference:
allOf:
- $ref: '#/components/schemas/DashboardtypesTimePreference'
description: 'The time range the panel queries: global_time (default) follows
the dashboard range; last_5_min, last_15_min, last_30_min, last_1_hr,
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
required:
- stack
type: object
DashboardtypesDistributionXAxis:
properties:
max:
description: Buckets wholly above this value are hidden. Null shows them
all.
nullable: true
type: number
min:
description: Buckets wholly below this value are hidden. Null shows them
all.
nullable: true
type: number
type: object
DashboardtypesDistributionYAxis:
properties:
scale:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYScale'
description: 'How counts are spaced: linear (default) or log.'
required:
- scale
type: object
DashboardtypesDistributionYScale:
enum:
- linear
- log
type: string
DashboardtypesDynamicVariableSignal:
enum:
- traces
@@ -5518,6 +5633,7 @@ components:
mapping:
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
signoz/DistributionPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
@@ -5544,6 +5660,7 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5560,6 +5677,7 @@ components:
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
- signoz/DistributionPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5591,6 +5709,21 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/DistributionPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
properties:
kind:
@@ -5774,9 +5907,9 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPlugin'
description: 'The visualization: kind is one of signoz/TimeSeriesPanel,
signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel,
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel
or signoz/HeatmapPanel, and spec holds that kind''s options ({} accepts
every default).'
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel,
signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind''s
options ({} accepts every default).'
queries:
description: The queries the panel runs. Use exactly one entry for a data
panel and [] for signoz/TextPanel. To run several named queries or formulas,
@@ -5912,8 +6045,8 @@ components:
- $ref: '#/components/schemas/Querybuildertypesv5RequestType'
description: 'The result shape the panel requests: time_series for time
series, bar, area and histogram panels, scalar for number, table and pie
panels, raw for list panels, heatmap for heatmap panels, trace for trace
panels.'
panels, raw for list panels, heatmap for heatmap panels, distribution
for distribution panels, trace for trace panels.'
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesQuerySpec'
@@ -6070,9 +6203,9 @@ components:
(builder query over AI observability traces), signoz/CompositeQuery (several
named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL
or signoz/TraceOperator, and spec holds that kind''s query. Pie and table
panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery
and signoz/TraceOperator; list panels accept only signoz/BuilderQuery
and signoz/AIBuilderQuery.'
panels reject signoz/PromQLQuery; heatmap and distribution panels reject
signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only
signoz/BuilderQuery and signoz/AIBuilderQuery.'
required:
- plugin
type: object
@@ -13195,8 +13328,8 @@ components:
SpantypesSpanItem:
properties:
matches:
description: Where the query's words were found, up to three places. Omitted
when the query has no words.
description: Where the query's search() text was found, up to three places.
Omitted when the query has no search().
items:
$ref: '#/components/schemas/SpantypesSpanTextMatch'
type: array
@@ -19813,15 +19946,17 @@ paths:
span per same-name sibling group, by the group''s own time. ai_usage:
spans with gen_ai token or cost usage, with those attributes, by cost,
else tokens. links: spans that link to other spans.'
- description: 'Words, a filter expression, or both, for example: worldpay AND
has_error = true. Words match the name, status message, attributes, resource
attributes and events, ignoring case. Applied before view.'
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
= true. search() matches text, ignoring case, in the name, status message,
attributes, resource attributes and events; a second argument limits it
to span, attribute, resource or event. Applied before view.'
in: query
name: query
schema:
description: 'Words, a filter expression, or both, for example: worldpay
AND has_error = true. Words match the name, status message, attributes,
resource attributes and events, ignoring case. Applied before view.'
description: 'A filter expression, for example: search(''worldpay'') AND
has_error = true. search() matches text, ignoring case, in the name, status
message, attributes, resource attributes and events; a second argument
limits it to span, attribute, resource or event. Applied before view.'
type: string
- description: 'Attributes or resource attributes to add to each span, for example
http.route or resource.k8s.pod.name. Default: service.name only.'
@@ -19999,15 +20134,17 @@ paths:
span per same-name sibling group, by the group''s own time. ai_usage:
spans with gen_ai token or cost usage, with those attributes, by cost,
else tokens. links: spans that link to other spans.'
- description: 'Words, a filter expression, or both, for example: worldpay AND
has_error = true. Words match the name, status message, attributes, resource
attributes and events, ignoring case. Applied before view.'
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
= true. search() matches text, ignoring case, in the name, status message,
attributes, resource attributes and events; a second argument limits it
to span, attribute, resource or event. Applied before view.'
in: query
name: query
schema:
description: 'Words, a filter expression, or both, for example: worldpay
AND has_error = true. Words match the name, status message, attributes,
resource attributes and events, ignoring case. Applied before view.'
description: 'A filter expression, for example: search(''worldpay'') AND
has_error = true. search() matches text, ignoring case, in the name, status
message, attributes, resource attributes and events; a second argument
limits it to span, attribute, resource or event. Applied before view.'
type: string
- description: 'Attributes or resource attributes to add to each span, for example
http.route or resource.k8s.pod.name. Default: service.name only.'
@@ -20122,15 +20259,17 @@ paths:
span per same-name sibling group, by the group''s own time. ai_usage:
spans with gen_ai token or cost usage, with those attributes, by cost,
else tokens. links: spans that link to other spans.'
- description: 'Words, a filter expression, or both, for example: worldpay AND
has_error = true. Words match the name, status message, attributes, resource
attributes and events, ignoring case. Applied before view.'
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
= true. search() matches text, ignoring case, in the name, status message,
attributes, resource attributes and events; a second argument limits it
to span, attribute, resource or event. Applied before view.'
in: query
name: query
schema:
description: 'Words, a filter expression, or both, for example: worldpay
AND has_error = true. Words match the name, status message, attributes,
resource attributes and events, ignoring case. Applied before view.'
description: 'A filter expression, for example: search(''worldpay'') AND
has_error = true. search() matches text, ignoring case, in the name, status
message, attributes, resource attributes and events; a second argument
limits it to span, attribute, resource or event. Applied before view.'
type: string
- description: 'Attributes or resource attributes to add to each span, for example
http.route or resource.k8s.pod.name. Default: service.name only.'
@@ -20245,15 +20384,17 @@ paths:
span per same-name sibling group, by the group''s own time. ai_usage:
spans with gen_ai token or cost usage, with those attributes, by cost,
else tokens. links: spans that link to other spans.'
- description: 'Words, a filter expression, or both, for example: worldpay AND
has_error = true. Words match the name, status message, attributes, resource
attributes and events, ignoring case. Applied before view.'
- description: 'A filter expression, for example: search(''worldpay'') AND has_error
= true. search() matches text, ignoring case, in the name, status message,
attributes, resource attributes and events; a second argument limits it
to span, attribute, resource or event. Applied before view.'
in: query
name: query
schema:
description: 'Words, a filter expression, or both, for example: worldpay
AND has_error = true. Words match the name, status message, attributes,
resource attributes and events, ignoring case. Applied before view.'
description: 'A filter expression, for example: search(''worldpay'') AND
has_error = true. search() matches text, ignoring case, in the name, status
message, attributes, resource attributes and events; a second argument
limits it to span, attribute, resource or event. Applied before view.'
type: string
- description: 'Attributes or resource attributes to add to each span, for example
http.route or resource.k8s.pod.name. Default: service.name only.'

View File

@@ -7248,6 +7248,123 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesTopListPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind {
'signoz/DistributionPanel' = 'signoz/DistributionPanel',
}
export interface DashboardtypesDistributionXAxisDTO {
/**
* @type number,null
* @description Buckets wholly above this value are hidden. Null shows them all.
*/
max?: number | null;
/**
* @type number,null
* @description Buckets wholly below this value are hidden. Null shows them all.
*/
min?: number | null;
}
export enum DashboardtypesDistributionYScaleDTO {
linear = 'linear',
log = 'log',
}
export interface DashboardtypesDistributionYAxisDTO {
/**
* @description How counts are spaced: linear (default) or log.
*/
scale: DashboardtypesDistributionYScaleDTO;
}
export interface DashboardtypesDistributionAxesDTO {
/**
* @description The bucket axis.
*/
x?: DashboardtypesDistributionXAxisDTO;
/**
* @description The count axis.
*/
y?: DashboardtypesDistributionYAxisDTO;
}
/**
* @maxItems 5
*/
export type DashboardtypesDistributionPercentileValuesDTO = number[];
export interface DashboardtypesDistributionPercentilesDTO {
/**
* @type boolean,null
* @description Whether percentile markers are drawn. Null draws them.
*/
enabled?: boolean | null;
/**
* @description The percentiles to mark, each greater than 0 and less than 100, at most 5, no repeats. Null or omitted marks 50, 90 and 99; [] marks none.
*/
values: DashboardtypesDistributionPercentileValuesDTO;
}
export interface DashboardtypesDistributionChartAppearanceDTO {
/**
* @description Percentile markers drawn across the bucket axis.
*/
percentiles?: DashboardtypesDistributionPercentilesDTO;
}
export enum DashboardtypesDistributionStackModeDTO {
normal = 'normal',
none = 'none',
percent = 'percent',
}
export interface DashboardtypesDistributionVisualizationDTO {
/**
* @description How groups combine in a bucket: normal (default) stacks them, none draws them side by side, percent stacks them as shares of the bucket.
*/
stack: DashboardtypesDistributionStackModeDTO;
/**
* @description The time range the panel queries: global_time (default) follows the dashboard range; last_5_min, last_15_min, last_30_min, last_1_hr, last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a fixed window.
*/
timePreference?: DashboardtypesTimePreferenceDTO;
}
export interface DashboardtypesDistributionPanelSpecDTO {
/**
* @description The X (bucket) axis range and Y (count) axis scale.
*/
axes?: DashboardtypesDistributionAxesDTO;
/**
* @description Percentile markers.
*/
chartAppearance?: DashboardtypesDistributionChartAppearanceDTO;
/**
* @description Unit and decimal precision of the bucket bounds; counts take no unit.
*/
formatting?: DashboardtypesPanelFormattingDTO;
/**
* @description Legend placement and series colors.
*/
legend?: DashboardtypesLegendDTO;
/**
* @description The time range the bucket counts are summed over, and how groups stack.
*/
visualization?: DashboardtypesDistributionVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO {
/**
* @enum signoz/DistributionPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesDistributionPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7261,7 +7378,8 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -7750,14 +7868,14 @@ export interface DashboardtypesQuerySpecDTO {
*/
name?: string;
/**
* @description The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery.
* @description The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap and distribution panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery.
*/
plugin: DashboardtypesQueryPluginDTO;
}
export interface DashboardtypesQueryDTO {
/**
* @description The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, trace for trace panels.
* @description The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, distribution for distribution panels, trace for trace panels.
*/
kind: Querybuildertypesv5RequestTypeDTO;
/**
@@ -7777,7 +7895,7 @@ export interface DashboardtypesPanelSpecDTO {
*/
links?: DashboardtypesLinkDTO[] | null;
/**
* @description The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel or signoz/HeatmapPanel, and spec holds that kind's options ({} accepts every default).
* @description The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel, signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind's options ({} accepts every default).
*/
plugin: DashboardtypesPanelPluginDTO;
/**
@@ -8550,6 +8668,7 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
'signoz/TopListPanel' = 'signoz/TopListPanel',
'signoz/DistributionPanel' = 'signoz/DistributionPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
@@ -14851,7 +14970,7 @@ export enum SpantypesUnmarkedFailureKindDTO {
export interface SpantypesSpanItemDTO {
/**
* @type array
* @description Where the query's words were found, up to three places. Omitted when the query has no words.
* @description Where the query's search() text was found, up to three places. Omitted when the query has no search().
*/
matches?: SpantypesSpanTextMatchDTO[];
span: SpantypesSpanDTO;
@@ -16437,7 +16556,7 @@ export type ListTraceSpansParams = {
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
*/
query?: string;
/**
@@ -16488,7 +16607,7 @@ export type ListTraceSpanAncestorsParams = {
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
*/
query?: string;
/**
@@ -16527,7 +16646,7 @@ export type ListTraceSpanChildrenParams = {
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
*/
query?: string;
/**
@@ -16566,7 +16685,7 @@ export type ListTraceSpanDescendantsParams = {
view?: SpantypesSpanListViewDTO;
/**
* @type string
* @description Words, a filter expression, or both, for example: worldpay AND has_error = true. Words match the name, status message, attributes, resource attributes and events, ignoring case. Applied before view.
* @description A filter expression, for example: search('worldpay') AND has_error = true. search() matches text, ignoring case, in the name, status message, attributes, resource attributes and events; a second argument limits it to span, attribute, resource or event. Applied before view.
*/
query?: string;
/**

View File

@@ -287,7 +287,7 @@ export function createAggregation(
];
}
// A heatmap buckets the field the user names; count() would be rejected as one.
// A heatmap or distribution buckets the field the user names; count() would be rejected as one.
// Elsewhere a field is not an aggregation, so it falls back to count().
const isDistributionField = aggregatesDistributionField(
panelType,

View File

@@ -292,6 +292,11 @@
box-sizing: border-box;
position: relative;
&.full-row {
grid-column: 1 / -1;
}
.cm-placeholder {
font-size: 12px !important;
}

View File

@@ -5,6 +5,7 @@ import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { Tooltip, TooltipProvider } from '@signozhq/ui/tooltip';
import InputWithLabel from 'components/InputWithLabel/InputWithLabel';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
import { GroupByFilter } from 'container/QueryBuilder/filters/GroupByFilter/GroupByFilter';
import { OrderByFilter } from 'container/QueryBuilder/filters/OrderByFilter/OrderByFilter';
import { ReduceToFilter } from 'container/QueryBuilder/filters/ReduceToFilter/ReduceToFilter';
@@ -102,7 +103,7 @@ function QueryAddOns({
}
if (
panelType === PANEL_TYPES.HEATMAP &&
isBucketPanelType(panelType) &&
!(
query.dataSource === DataSource.METRICS &&
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
@@ -201,13 +202,16 @@ function QueryAddOns({
initializedRef.current = true;
// Initial seeding from query values on mount. A disabled field never opens.
// Bucket options open even when empty: they are what makes a bucket panel.
setSelectedViews(
offeredAddOns.filter((addOn) => {
const resolved = resolvedFields.get(addOn.key);
return (
resolved?.pinned ||
(hasValue(get(query, addOn.queryPath)) && !resolved?.disabled)
((hasValue(get(query, addOn.queryPath)) ||
addOn.key === QueryBuilderField.BucketOptions) &&
!resolved?.disabled)
);
}),
);
@@ -496,7 +500,10 @@ function QueryAddOns({
{selectedViews.find(
(view) => view.key === QueryBuilderField.BucketOptions,
) && (
<div className="add-on-content" data-testid="bucket-options-content">
<div
className="add-on-content full-row"
data-testid="bucket-options-content"
>
<BucketOptions
bucketOptions={query.bucketOptions}
unit={currentQuery.unit}

View File

@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
// other panel type sends one. A histogram metric brings its own buckets.
// Offered only by a heatmap or distribution: the bucket axis is what they plot against,
// and no other panel type sends one. A histogram metric brings its own buckets.
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.HISTOGRAM,
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,

View File

@@ -12,7 +12,7 @@ import { toDistributionFieldOptions } from './distributionFieldOptions';
import Styles from './DistributionFieldSelect.module.scss';
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
/** A logs or traces heatmap or distribution's aggregation: the one numeric field it buckets. */
export default function DistributionFieldSelect({
queryData,
onChange,
@@ -54,6 +54,8 @@ export default function DistributionFieldSelect({
value={selectedField || undefined}
onChange={(field): void => onChange?.(field ?? '')}
allowClear
// Log keys are discovered from ingested data, so a field may not be listed yet.
allowCreate={(field): string => `Use "${field}"`}
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
searchInputProps={{
placeholder: 'Search numeric fields',

View File

@@ -125,10 +125,11 @@ describe('DistributionFieldSelect', () => {
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
});
it('only offers listed fields: typed text is a filter, not a value', async () => {
it('accepts a typed field the keys do not list', async () => {
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
@@ -137,13 +138,12 @@ describe('DistributionFieldSelect', () => {
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'no_such_field',
'attribute.bytes',
);
await screen.findByTestId('distribution-field-select-create');
await user.keyboard('{Enter}');
await screen.findByText('No numeric fields');
expect(
screen.queryByTestId('distribution-field-select-item-no_such_field'),
).not.toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith('attribute.bytes');
});
it('searches the server for typed text, past the listed fields', async () => {

View File

@@ -38,7 +38,7 @@ export function toDistributionFieldText(key: TelemetryFieldKey): string {
/**
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
* aggregates, which a heatmap or distribution cannot bucket. A saved field the keys do not carry
* leads as its own item, so the combobox can still show it.
*/
export function toDistributionFieldOptions(

View File

@@ -499,6 +499,23 @@ describe('QueryAddOns', () => {
).toBeInTheDocument();
});
it('is offered on a metrics distribution too', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.METRICS })}
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.DISTRIBUTION}
index={0}
isForTraceOperator={false}
/>,
);
expect(
screen.getByTestId('query-add-on-bucket_options'),
).toBeInTheDocument();
});
it('is not offered on other panel types', () => {
render(
<QueryAddOns
@@ -554,12 +571,10 @@ describe('QueryAddOns', () => {
);
});
it('shows the server default, log at scale 4, without sending it', async () => {
const user = userEvent.setup();
it('opens empty on the server default, log at scale 4, without sending it', () => {
renderHeatmap();
await user.click(screen.getByTestId('query-add-on-bucket_options'));
expect(screen.getByTestId('bucket-options-content')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Log' })).toHaveAttribute(
'aria-pressed',
'true',

View File

@@ -74,6 +74,8 @@ describe('QueryAggregationOptions on a heatmap', () => {
it.each([
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
[PANEL_TYPES.DISTRIBUTION, DataSource.LOGS, true],
[PANEL_TYPES.DISTRIBUTION, DataSource.METRICS, false],
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
])(
'%s over %s renders the field picker: %s',

View File

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

View File

@@ -313,6 +313,7 @@ export enum PANEL_TYPES {
PIE = 'pie',
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
DISTRIBUTION = 'distribution',
GEO_MAP = 'geo_map',
TOP_LIST = 'top_list',
TEXT = 'text',

View File

@@ -528,11 +528,12 @@ export const metricsHistogramSpaceAggregateOperatorOptions: SelectOption<
];
/**
* A heatmap's Y axis is the `le` labels themselves, so every percentile draws the grid a
* count already draws. Sum is also what the statement builder forces on a histogram
* heatmap whatever is asked for, so it is the only honest option to offer.
* A bucket panel's (heatmap, distribution) axis is the `le` labels themselves, so every
* percentile draws what a count already draws. Sum is also what the statement builder
* forces on a histogram bucket panel whatever is asked for, so it is the only honest
* option to offer.
*/
export const metricsHeatmapHistogramSpaceAggregateOperatorOptions: SelectOption<
export const metricsBucketHistogramSpaceAggregateOperatorOptions: SelectOption<
string,
string
>[] = [

View File

@@ -6,7 +6,7 @@ import InputWithLabel from 'components/InputWithLabel/InputWithLabel';
import BucketOptions from 'components/QueryBuilderV2/QueryV2/QueryAddOns/BucketOptions/BucketOptions';
import { parseLimit, sanitizeLimit } from 'components/QueryBuilderV2/utils';
import { LEGEND } from 'constants/global';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
// ** Hooks
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
@@ -185,9 +185,9 @@ export function Formula({
</div>
</Col>
)}
{/* A heatmap draws its one enabled query, which is the formula when its
inputs are disabled — so the formula states its own bucket axis. */}
{isQBV2 && panelType === PANEL_TYPES.HEATMAP && (
{/* A heatmap or distribution draws its one enabled query, which is the formula
when its inputs are disabled — so the formula states its own bucket axis. */}
{isQBV2 && isBucketPanelType(panelType) && (
<Col span={24} className="formula-item">
<BucketOptions
bucketOptions={formula.bucketOptions}

View File

@@ -9,7 +9,7 @@ export type OrderByFilterProps = {
onChange: (values: OrderByPayload[]) => void;
isRawQuery?: boolean;
placeholder?: string;
/** A logs or traces heatmap aggregates a field, which Order by then offers. */
/** A logs or traces heatmap or distribution aggregates a field, which Order by then offers. */
panelType?: PANEL_TYPES;
};

View File

@@ -13,6 +13,7 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
PIE: false,
HISTOGRAM: false,
HEATMAP: false,
DISTRIBUTION: false,
GEO_MAP: false,
TOP_LIST: false,
TEXT: false,

View File

@@ -24,6 +24,7 @@ export const PanelTypeVsPanelWrapper = {
[PANEL_TYPES.HISTOGRAM]: HistogramPanel,
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.DISTRIBUTION]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
};

View File

@@ -18,7 +18,7 @@ import {
} from 'constants/queryBuilder';
import {
metricsGaugeSpaceAggregateOperatorOptions,
metricsHeatmapHistogramSpaceAggregateOperatorOptions,
metricsBucketHistogramSpaceAggregateOperatorOptions,
metricsHistogramSpaceAggregateOperatorOptions,
metricsSumSpaceAggregateOperatorOptions,
metricsUnknownSpaceAggregateOperatorOptions,
@@ -59,6 +59,7 @@ import {
} from 'types/common/queryBuilder';
import { SelectOption } from 'types/common/select';
import { getFormatedLegend } from 'utils/getFormatedLegend';
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
export const useQueryOperations: UseQueryOperations = ({
query,
@@ -181,10 +182,9 @@ export const useQueryOperations: UseQueryOperations = ({
(aggregateAttribute?.type as ATTRIBUTE_TYPES) || ATTRIBUTE_TYPES.GAUGE,
});
const histogramSpaceAggregationOptions =
panelType === PANEL_TYPES.HEATMAP
? metricsHeatmapHistogramSpaceAggregateOperatorOptions
: metricsHistogramSpaceAggregateOperatorOptions;
const histogramSpaceAggregationOptions = isBucketPanelType(panelType)
? metricsBucketHistogramSpaceAggregateOperatorOptions
: metricsHistogramSpaceAggregateOperatorOptions;
switch (aggregateAttribute?.type) {
case ATTRIBUTE_TYPES.SUM:
@@ -267,13 +267,12 @@ export const useQueryOperations: UseQueryOperations = ({
timeAggregation: '',
metricName: newQuery.aggregateAttribute?.key || '',
temporality: '',
// A heatmap cell holds a count of observations per `le` band, which is
// the one option the kind offers — a percentile default would sit in the
// Heatmap and distribution count observations per `le` band, the one
// option those kinds offer — a percentile default would sit in the
// selector with nothing behind it.
spaceAggregation:
panelType === PANEL_TYPES.HEATMAP
? MetricAggregateOperator.COUNT
: MetricAggregateOperator.P90,
spaceAggregation: isBucketPanelType(panelType)
? MetricAggregateOperator.COUNT
: MetricAggregateOperator.P90,
reduceTo: ReduceOperators.AVG,
},
];

View File

@@ -0,0 +1,13 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { isBucketPanelType } from '../bucketPanelTypes';
describe('isBucketPanelType', () => {
it('is true for heatmap and distribution only', () => {
expect(isBucketPanelType(PANEL_TYPES.HEATMAP)).toBe(true);
expect(isBucketPanelType(PANEL_TYPES.DISTRIBUTION)).toBe(true);
expect(isBucketPanelType(PANEL_TYPES.HISTOGRAM)).toBe(false);
expect(isBucketPanelType(PANEL_TYPES.TIME_SERIES)).toBe(false);
expect(isBucketPanelType(null)).toBe(false);
});
});

View File

@@ -1,8 +1,9 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
aggregatesDistributionField,
getDistributionFieldPlaceholder,
setDistributionField,
toDistributionAggregation,
@@ -17,6 +18,17 @@ const queryOf = (
aggregations: expressions.map((expression) => ({ expression })),
});
describe('aggregatesDistributionField', () => {
it.each([
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
[PANEL_TYPES.DISTRIBUTION, DataSource.LOGS, true],
[PANEL_TYPES.DISTRIBUTION, DataSource.METRICS, false],
[PANEL_TYPES.HISTOGRAM, DataSource.TRACES, false],
])('%s over %s → %s', (panelType, dataSource, expected) => {
expect(aggregatesDistributionField(panelType, dataSource)).toBe(expected);
});
});
describe('getDistributionFieldPlaceholder', () => {
it.each([
[DataSource.TRACES, 'Numeric field to bucket, e.g. duration_nano'],

View File

@@ -49,8 +49,23 @@ describe('handleQueryChange bucket options', () => {
);
});
// The request rejects an axis on any type but heatmap, so a switch has to shed it
// from the query (via the field allowlist) and from the formula (by hand).
it('keeps both axes when a heatmap switches to a distribution', () => {
const result = handleQueryChange(
PANEL_TYPES.DISTRIBUTION,
queryWithFormulaAxis(),
PANEL_TYPES.HEATMAP,
);
expect(result.builder.queryData[0].bucketOptions).toStrictEqual(
bucketOptions,
);
expect(result.builder.queryFormulas[0].bucketOptions).toStrictEqual(
bucketOptions,
);
});
// The request rejects an axis on any type but heatmap and distribution, so a switch
// has to shed it from the query (via the field allowlist) and from the formula (by hand).
it('drops both axes when switching to another panel type', () => {
const result = handleQueryChange(
PANEL_TYPES.TIME_SERIES,
@@ -124,16 +139,19 @@ describe('handleQueryChange trace operator', () => {
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
// A heatmap request takes one builder query and rejects a trace operator.
it('drops the trace operator when switching to a heatmap', () => {
const result = handleQueryChange(
PANEL_TYPES.HEATMAP,
queryWithTraceOperator(),
PANEL_TYPES.TIME_SERIES,
);
// A heatmap or distribution request takes one builder query and rejects a trace operator.
it.each([PANEL_TYPES.HEATMAP, PANEL_TYPES.DISTRIBUTION] as const)(
'drops the trace operator when switching to a %s',
(panelType) => {
const result = handleQueryChange(
panelType,
queryWithTraceOperator(),
PANEL_TYPES.TIME_SERIES,
);
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
expect(result.builder.queryTraceOperator).toStrictEqual([]);
},
);
it('keeps the trace operator when switching to a table', () => {
const result = handleQueryChange(

View File

@@ -5,7 +5,7 @@ export const unquoteAlias = (alias: string): string =>
alias.replace(/^['"]|['"]$/g, '');
/**
* A logs or traces heatmap's aggregation: one field with an optional alias.
* A logs or traces heatmap or distribution's aggregation: one field with an optional alias.
* The field mirrors the querier's HeatmapAggregationField: no call, no whitespace.
*/
export const DISTRIBUTION_FIELD = new RegExp(
@@ -26,7 +26,7 @@ export function parseAggregations(
'g',
);
// With no call at all, the whole expression may be the field a logs/traces
// heatmap buckets, e.g. "duration_nano"
// heatmap or distribution buckets, e.g. "duration_nano"
let match =
regex.exec(expression) ??
(allowDistributionField ? DISTRIBUTION_FIELD.exec(expression) : null);

View File

@@ -0,0 +1,14 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
/**
* Panel types whose request counts observations into buckets (`heatmap`,
* `distribution`): they share the bucket axis, its query-builder options and the
* count aggregation a histogram metric gets.
*/
export function isBucketPanelType(
panelType: string | null | undefined,
): boolean {
return (
panelType === PANEL_TYPES.HEATMAP || panelType === PANEL_TYPES.DISTRIBUTION
);
}

View File

@@ -1,4 +1,3 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import type {
IBuilderQuery,
OrderByPayload,
@@ -6,6 +5,8 @@ import type {
import { DataSource } from 'types/common/queryBuilder';
import type { LogAggregation, TraceAggregation } from 'types/api/v5/queryRange';
import { isBucketPanelType } from './bucketPanelTypes';
import {
ALIAS,
DISTRIBUTION_FIELD,
@@ -20,7 +21,7 @@ const NUMERIC_FIELD_CALL = new RegExp(
`^\\s*(?:avg|sum|min|max|p\\d{2})\\(\\s*([^\\s(),]+)\\s*\\)(?:\\s+as\\s+(${ALIAS}))?\\s*$`,
);
/** The percentile a field or histogram metric gets when it leaves a heatmap. */
/** The percentile a field or histogram metric gets when it leaves a heatmap or distribution. */
export const DEFAULT_PERCENTILE = 'p90';
type FieldAggregation = TraceAggregation | LogAggregation;
@@ -41,7 +42,7 @@ export function aggregatesDistributionField(
panelType: string | null | undefined,
dataSource: DataSource,
): boolean {
return panelType === PANEL_TYPES.HEATMAP && isLogsOrTraces(dataSource);
return isBucketPanelType(panelType) && isLogsOrTraces(dataSource);
}
/**
@@ -78,7 +79,7 @@ export function getDistributionFieldPlaceholder(
}
/**
* Logs and traces heatmaps bucket a field; any function aggregation is
* Logs and traces heatmaps and distributions bucket a field; any function aggregation is
* rejected, so a numeric `fn(field)` keeps its field and anything else leaves
* the field for the user to pick.
*/
@@ -109,7 +110,7 @@ export function toDistributionAggregation(query: IBuilderQuery): IBuilderQuery {
);
}
/** Picks `field` as the heatmap's aggregation; a sort on the old field follows it. */
/** Picks `field` as the aggregation; a sort on the old field follows it. */
export function setDistributionField(
query: IBuilderQuery,
field: string,

View File

@@ -8,6 +8,7 @@ import {
PANEL_TYPES,
} from 'constants/queryBuilder';
import { cloneDeep, isEqual, set, unset } from 'lodash-es';
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
import {
IBuilderFormula,
IBuilderQuery,
@@ -99,13 +100,13 @@ export const getIsQueryModified = (
/**
* Formulas are carried across a panel-type switch whole, not rebuilt from
* `panelTypeDataSourceFormValuesMap` the way `queryData` is, so a bucket axis has to be
* dropped by hand. The request rejects one on any type but heatmap.
* dropped by hand. The request rejects one on any type that does not count buckets.
*/
const withHeatmapBucketOptions = (
const withBucketOptions = (
formulas: IBuilderFormula[],
newPanelType: keyof PartialPanelTypes,
): IBuilderFormula[] => {
if (newPanelType === PANEL_TYPES.HEATMAP) {
if (isBucketPanelType(newPanelType)) {
return formulas;
}
@@ -170,11 +171,11 @@ export function rebuildBuilderForPanelType(
return tempQuery;
}),
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
queryFormulas: withBucketOptions(builder.queryFormulas, newPanelType),
queryTraceOperator:
newPanelType === PANEL_TYPES.LIST ||
newPanelType === PANEL_TYPES.SCATTER ||
newPanelType === PANEL_TYPES.HEATMAP
isBucketPanelType(newPanelType)
? []
: builder.queryTraceOperator,
};

View File

@@ -17,6 +17,7 @@ export type PartialPanelTypes = {
[PANEL_TYPES.SCATTER]: 'scatter';
[PANEL_TYPES.HISTOGRAM]: 'histogram';
[PANEL_TYPES.HEATMAP]: 'heatmap';
[PANEL_TYPES.DISTRIBUTION]: 'distribution';
[PANEL_TYPES.GEO_MAP]: 'geo_map';
[PANEL_TYPES.TOP_LIST]: 'top_list';
};
@@ -149,6 +150,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.BAR]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HISTOGRAM]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP),
[PANEL_TYPES.DISTRIBUTION]: bySource(HEATMAP, HEATMAP),
[PANEL_TYPES.TABLE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),

View File

@@ -11,8 +11,9 @@ const MARKER_IDLE_ALPHA = 0.55;
/** Cap height as a share of the font size. */
const CAP_HEIGHT_RATIO = 0.7;
const MARKER_FONT_SIZE_PX = 9;
/** Space between a badge's name and its diamond's edges. */
const MARKER_BADGE_PADDING_PX = 2;
const MARKER_BADGE_PADDING_X_PX = 5;
const MARKER_BADGE_PADDING_Y_PX = 4;
const MARKER_BADGE_RADIUS_PX = 3;
const MARKER_BADGE_GAP_PX = 2;
const MARKER_VALUE_FONT_SIZE_PX = 11;
/** How far from a marker line the cursor still hovers it, in CSS pixels. */
@@ -81,21 +82,24 @@ export function layoutMarkerLabels(
return rows;
}
/** A square diamond centred on `(x, y)` with half-diagonal `radius`, filled then outlined. */
function drawDiamond(
/** A rounded rectangle centred on `(x, y)`, filled then outlined. */
function drawBadge(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
radius: number,
halfWidth: number,
halfHeight: number,
fill: string,
stroke: string,
): void {
ctx.beginPath();
ctx.moveTo(x, y - radius);
ctx.lineTo(x + radius, y);
ctx.lineTo(x, y + radius);
ctx.lineTo(x - radius, y);
ctx.closePath();
ctx.roundRect(
x - halfWidth,
y - halfHeight,
2 * halfWidth,
2 * halfHeight,
MARKER_BADGE_RADIUS_PX * uPlot.pxRatio,
);
ctx.fillStyle = fill;
ctx.fill();
ctx.strokeStyle = stroke;
@@ -103,7 +107,7 @@ function drawDiamond(
}
/**
* Dashed lines across the plot with a diamond badge at each end naming the
* Dashed lines across the plot with a badge at each end naming the
* percentile, one per group on the same spot; badges stack into rows so none overlap. The hovered marker is
* emphasised and shows its value on the x axis. Returns each marker's hover targets.
*/
@@ -128,33 +132,34 @@ export function drawPercentileMarkers(
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const badgeLabels = markers.map((group) => {
// Cap height stands in for the text's height.
const halfHeight =
(MARKER_FONT_SIZE_PX * pxRatio * CAP_HEIGHT_RATIO) / 2 +
MARKER_BADGE_PADDING_Y_PX * pxRatio;
const badges = markers.map((group) => {
const text = formatPercentileBadge(group);
return { text, width: ctx.measureText(text).width };
return {
text,
x: uPlotInstance.valToPos(group[0].axisValue, 'x', true),
halfWidth:
ctx.measureText(text).width / 2 + MARKER_BADGE_PADDING_X_PX * pxRatio,
};
});
// One square diamond for all, fitting the widest name's box: |dx| + |dy| ≤ radius at
// its corners. Cap height stands in for the text's height.
const radius =
(Math.max(...badgeLabels.map(({ width }) => width)) +
MARKER_FONT_SIZE_PX * pxRatio * CAP_HEIGHT_RATIO) /
2 +
MARKER_BADGE_PADDING_PX * pxRatio;
const badges = markers.map((group, index) => ({
text: badgeLabels[index].text,
x: uPlotInstance.valToPos(group[0].axisValue, 'x', true),
}));
const rows = layoutMarkerLabels(
badges.map(({ x }) => ({ x: x - radius, width: 2 * radius })),
badges.map(({ x, halfWidth }) => ({
x: x - halfWidth,
width: 2 * halfWidth,
})),
MARKER_BADGE_GAP_PX * pxRatio,
);
const rowStep = 2 * radius + MARKER_BADGE_GAP_PX * pxRatio;
const rowStep = 2 * halfHeight + MARKER_BADGE_GAP_PX * pxRatio;
const badgeCentres = (index: number): [number, number] => {
const offset = radius + rows[index] * rowStep;
const offset = halfHeight + rows[index] * rowStep;
return [bbox.top + offset, bottom - offset];
};
const drawMarker = (index: number): void => {
const { text, x } = badges[index];
const { text, x, halfWidth } = badges[index];
const isHovered = index === hovered;
ctx.globalAlpha = isHovered ? 1 : MARKER_IDLE_ALPHA;
@@ -169,7 +174,15 @@ export function drawPercentileMarkers(
ctx.globalAlpha = 1;
ctx.setLineDash([]);
badgeCentres(index).forEach((y) => {
drawDiamond(ctx, x, y, radius, isHovered ? color : background, color);
drawBadge(
ctx,
x,
y,
halfWidth,
halfHeight,
isHovered ? color : background,
color,
);
ctx.fillStyle = isHovered ? background : color;
ctx.fillText(text, x, y);
});
@@ -179,7 +192,7 @@ export function drawPercentileMarkers(
}
// The value sits on the x axis under the line, over the tick labels, in a pill
// whose notch points up at the line.
ctx.font = `500 ${MARKER_VALUE_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
ctx.font = `600 ${MARKER_VALUE_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
const value = formatPercentileValue(markers[index], formatBound);
const pillPaddingX = MARKER_PILL_PADDING_X_PX * pxRatio;
const pillPaddingY = MARKER_PILL_PADDING_Y_PX * pxRatio;
@@ -200,7 +213,8 @@ export function drawPercentileMarkers(
width + 2 * pillPaddingX,
height + 2 * pillPaddingY,
);
ctx.fillStyle = isDarkMode ? Color.BG_SLATE_400 : Color.BG_INK_400;
// The hovered badge's colours, so the value reads as part of the same marker.
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(left, top, width, height, MARKER_PILL_RADIUS_PX * pxRatio);
ctx.moveTo(notchX - pointer, top);
@@ -208,7 +222,7 @@ export function drawPercentileMarkers(
ctx.lineTo(notchX + pointer, top);
ctx.closePath();
ctx.fill();
ctx.fillStyle = Color.BG_VANILLA_100;
ctx.fillStyle = background;
ctx.fillText(value, left + width / 2, top + height / 2);
};
@@ -219,16 +233,16 @@ export function drawPercentileMarkers(
}
ctx.restore();
return badges.map(({ x }, index) => {
return badges.map(({ x, halfWidth }, index) => {
const toPlot = (value: number, origin: number): number =>
(value - origin) / pxRatio;
return {
x: toPlot(x, bbox.left),
badges: badgeCentres(index).map((y) => ({
left: toPlot(x - radius, bbox.left),
right: toPlot(x + radius, bbox.left),
top: toPlot(y - radius, bbox.top),
bottom: toPlot(y + radius, bbox.top),
left: toPlot(x - halfWidth, bbox.left),
right: toPlot(x + halfWidth, bbox.left),
top: toPlot(y - halfHeight, bbox.top),
bottom: toPlot(y + halfHeight, bbox.top),
})),
};
});

View File

@@ -12,7 +12,7 @@ const OPTIONS = [
{ kind: 'signoz/BarChartPanel', displayName: 'Bar Chart' },
{ kind: 'signoz/AreaChartPanel', displayName: 'Area' },
{ kind: 'signoz/PieChartPanel', displayName: 'Pie Chart' },
{ kind: 'signoz/HistogramPanel', displayName: 'Histogram' },
{ kind: 'signoz/HistogramPanel', displayName: 'Histogram', isRetired: true },
{ kind: 'signoz/ListPanel', displayName: 'List' },
{ kind: 'signoz/TextPanel', displayName: 'Text' },
].map((option) => ({ ...option, icon: (): null => null }));
@@ -110,6 +110,22 @@ describe('PanelTypeSwitcher', () => {
expect(onChange).not.toHaveBeenCalled();
});
it('does not offer a retired type to a panel of another type', async () => {
await renderSwitcher();
expect(
screen.queryByTestId('panel-type-signoz/HistogramPanel'),
).not.toBeInTheDocument();
});
it('keeps a retired type on offer to a panel already of it', async () => {
await renderSwitcher({ panelKind: 'signoz/HistogramPanel' });
expect(
screen.getByTestId('panel-type-signoz/HistogramPanel'),
).toBeInTheDocument();
});
it('disables types whose supported signals exclude the current signal', async () => {
const { onChange, user } = await renderSwitcher({
signal: TelemetrytypesSignalDTO.metrics,

View File

@@ -4,11 +4,14 @@ import type { EQueryType } from 'types/common/dashboard';
import { PANEL_OPTIONS } from '../../../Panels/registry';
import type { PanelKind } from '../../../Panels/types/panelKind';
import { isPanelOptionOffered } from '../../../Panels/utils/isPanelOptionOffered';
import type { ConfigSelectItem } from '../controls/ConfigSelect/ConfigSelect';
import { getPanelTypeDisabledReason } from './utils';
interface UsePanelTypeSelectItemsArgs {
/** The panel's kind — the only one a retired kind is still offered to. */
panelKind: PanelKind;
/** Active query type — a kind that can't be authored in it is disabled. */
queryType: EQueryType;
/** Current datasource — also gates the disabled rule (List needs logs/traces, not metrics). */
@@ -21,12 +24,15 @@ interface UsePanelTypeSelectItemsArgs {
* the capabilities guard, the same rule the editor's `PanelTypeSwitcher` applies.
*/
export function usePanelTypeSelectItems({
panelKind,
queryType,
signal,
}: UsePanelTypeSelectItemsArgs): ConfigSelectItem<PanelKind>[] {
return useMemo(
() =>
PANEL_OPTIONS.map(({ kind, displayName, icon: Icon }) => {
PANEL_OPTIONS.filter((option) =>
isPanelOptionOffered(option, panelKind),
).map(({ kind, displayName, icon: Icon }) => {
// One reason drives both the disabled flag and the tooltip, so they can't disagree.
const disabledReason = getPanelTypeDisabledReason({
kind,
@@ -42,6 +48,6 @@ export function usePanelTypeSelectItems({
tooltip: disabledReason,
};
}),
[queryType, signal],
[panelKind, queryType, signal],
);
}

View File

@@ -26,6 +26,13 @@ export const SWITCH_SKETCHES = {
))}
</SketchSvg>
),
percentiles: (
<SketchSvg>
<path d="M3 19 L9 13 L15 7 L21 9 L27 14 L33 17 L37 19" />
<path d="M15 3 V20" strokeDasharray="2 2" />
<path d="M29 3 V20" strokeDasharray="2 2" />
</SketchSvg>
),
rank: (
<SketchSvg>
{[5, 11, 17].map((y, index) => (

View File

@@ -180,6 +180,22 @@ export const TILE_DRAWINGS = {
<rect x={38} y={8} width={11} height={6} {...FILLED} />
</TileSvg>
),
barsSideBySide: (
<TileSvg>
<rect x={10} y={8} width={7} height={14} {...FILLED} opacity={0.5} />
<rect x={18} y={12} width={7} height={10} {...FILLED} />
<rect x={36} y={11} width={7} height={11} {...FILLED} opacity={0.5} />
<rect x={44} y={6} width={7} height={16} {...FILLED} />
</TileSvg>
),
barsPercent: (
<TileSvg>
<rect x={14} y={12} width={11} height={10} {...FILLED} opacity={0.5} />
<rect x={14} y={2} width={11} height={9} {...FILLED} />
<rect x={38} y={8} width={11} height={14} {...FILLED} opacity={0.5} />
<rect x={38} y={2} width={11} height={5} {...FILLED} />
</TileSvg>
),
areaOverlap: (
<TileSvg>
<path d="M4 15 L18 9 L32 13 L46 6 L60 9" />

View File

@@ -1,5 +1,6 @@
import type { ComponentType } from 'react';
import {
type DashboardtypesDistributionAxesDTO,
type DashboardtypesGeoMapChartAppearanceDTO,
DashboardtypesGeoMapLayerDTO,
type DashboardtypesGeoMapLocationDTO,
@@ -32,6 +33,7 @@ import BucketsSection from './sections/BucketsSection/BucketsSection';
import ChartAppearanceSection from './sections/ChartAppearanceSection/ChartAppearanceSection';
import ContextLinksSection from './sections/ContextLinksSection/ContextLinksSection';
import DimensionsSection from './sections/DimensionsSection/DimensionsSection';
import DistributionAxesSection from './sections/DistributionAxesSection/DistributionAxesSection';
import FormattingSection from './sections/FormattingSection/FormattingSection';
import LegendSection from './sections/LegendSection/LegendSection';
import LocationSection from './sections/LocationSection/LocationSection';
@@ -105,6 +107,13 @@ export const SECTION_REGISTRY: {
getPluginSlice<DashboardtypesScatterPlotAxesDTO>(spec, 'axes'),
update: (spec, axes): PanelSpec => updatePluginSlice(spec, 'axes', axes),
},
// Same `axes` key again, in Distribution's bucket-range/count-scale shape.
[SectionKind.DistributionAxes]: {
Component: DistributionAxesSection,
get: (spec): DashboardtypesDistributionAxesDTO | undefined =>
getPluginSlice<DashboardtypesDistributionAxesDTO>(spec, 'axes'),
update: (spec, axes): PanelSpec => updatePluginSlice(spec, 'axes', axes),
},
[SectionKind.Dimensions]: {
Component: DimensionsSection,
get: (spec): DashboardtypesScatterPlotDimensionsDTO | undefined =>

View File

@@ -16,6 +16,7 @@ import { resolveBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Pane
import ConfigRangeSlider from '../../controls/ConfigRangeSlider/ConfigRangeSlider';
import DisconnectValuesField from './DisconnectValuesField';
import DistributionPercentilesField from './DistributionPercentilesField';
import GeoMapColorsField from './GeoMapColorsField';
import HeatmapColorsField from './HeatmapColorsField';
import PointsFields from './PointsFields';
@@ -43,6 +44,7 @@ const BUBBLE_RADIUS_BOUNDS = { min: 1, max: 64 };
*/
function ChartAppearanceSection({
value,
defaultValue,
savedValue,
controls,
onChange,
@@ -59,6 +61,15 @@ function ChartAppearanceSection({
return (
<>
{controls.percentiles && (
<DistributionPercentilesField
value={value?.percentiles}
defaultValue={defaultValue?.percentiles}
savedValue={savedValue?.percentiles}
onChange={(percentiles): void => onChange({ ...value, percentiles })}
/>
)}
{controls.lineStyle && (
<ConfigField label="Line" {...reset('lineStyle')}>
<ConfigTiles

View File

@@ -0,0 +1,73 @@
import type { DashboardtypesDistributionPercentilesDTO } from 'api/generated/services/sigNoz.schemas';
import ConfigField from '../../controls/ConfigField/ConfigField';
import ConfigMultiSelect from '../../controls/ConfigMultiSelect/ConfigMultiSelect';
import ConfigSwitch from '../../controls/ConfigSwitch/ConfigSwitch';
import { SWITCH_SKETCHES } from '../../controls/drawings/switchSketches';
import { createFieldResetter } from '../../utils/changes';
import {
MAX_PERCENTILE_MARKERS,
resolvePercentileItems,
} from './percentileOptions';
interface DistributionPercentilesFieldProps {
value: DashboardtypesDistributionPercentilesDTO | undefined;
/** The new panel's seed: what the server writes for unset percentiles. */
defaultValue?: DashboardtypesDistributionPercentilesDTO;
savedValue?: DashboardtypesDistributionPercentilesDTO;
onChange: (next: DashboardtypesDistributionPercentilesDTO) => void;
}
/** Edits `chartAppearance.percentiles`. */
function DistributionPercentilesField({
value,
defaultValue,
savedValue,
onChange,
}: DistributionPercentilesFieldProps): JSX.Element {
const reset = createFieldResetter(value, savedValue, onChange);
const enabled = value?.enabled ?? defaultValue?.enabled ?? false;
const values = value?.values ?? defaultValue?.values ?? [];
return (
<>
<ConfigSwitch
testId="panel-editor-v2-percentile-markers"
title="Percentile markers"
description="Dashed lines at percentiles estimated from the bucket counts."
sketch={SWITCH_SKETCHES.percentiles}
changed={reset('enabled').changed}
value={enabled}
onChange={(next): void => onChange({ enabled: next, values })}
/>
{enabled && (
<ConfigField
label="Percentiles"
help={
<span data-testid="panel-editor-v2-percentile-limit">
{values.length >= MAX_PERCENTILE_MARKERS
? `Limit of ${MAX_PERCENTILE_MARKERS} reached; remove one to pick another.`
: `Up to ${MAX_PERCENTILE_MARKERS}.`}
</span>
}
{...reset('values')}
>
<ConfigMultiSelect
testId="panel-editor-v2-percentile-values"
placeholder="Pick percentiles"
value={values.map(String)}
items={resolvePercentileItems(values)}
onChange={(picked): void => {
if (picked.length <= MAX_PERCENTILE_MARKERS) {
onChange({ enabled, values: picked.map(Number) });
}
}}
/>
</ConfigField>
)}
</>
);
}
export default DistributionPercentilesField;

View File

@@ -0,0 +1,122 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import DistributionPercentilesField from '../DistributionPercentilesField';
import { resolvePercentileItems } from '../percentileOptions';
describe('DistributionPercentilesField', () => {
it("opens on the new panel's seed, with the values picker shown", () => {
render(
<DistributionPercentilesField
value={undefined}
defaultValue={{ enabled: true, values: [50, 90, 99] }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-percentile-values'),
).toBeInTheDocument();
});
it('turns markers off, keeping the values for when they come back', async () => {
const onChange = jest.fn() as jest.MockedFunction<
ComponentProps<typeof DistributionPercentilesField>['onChange']
>;
render(
<DistributionPercentilesField
value={{ enabled: true, values: [75] }}
onChange={onChange}
/>,
);
await userEvent
.setup()
.click(screen.getByTestId('panel-editor-v2-percentile-markers'));
expect(onChange).toHaveBeenCalledWith({ enabled: false, values: [75] });
});
it('hides the values picker while markers are off', () => {
render(
<DistributionPercentilesField
value={{ enabled: false, values: [75] }}
onChange={jest.fn()}
/>,
);
expect(
screen.queryByTestId('panel-editor-v2-percentile-values'),
).not.toBeInTheDocument();
});
});
describe('DistributionPercentilesField limit', () => {
it('says when the limit is reached', () => {
const { rerender } = render(
<DistributionPercentilesField
value={{ enabled: true, values: [50, 90, 99] }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-percentile-limit'),
).toHaveTextContent('Up to 5.');
rerender(
<DistributionPercentilesField
value={{ enabled: true, values: [50, 75, 90, 95, 99] }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-percentile-limit'),
).toHaveTextContent('Limit of 5 reached; remove one to pick another.');
});
});
describe('resolvePercentileItems', () => {
it('adds a saved value missing from the presets, in order', () => {
expect(resolvePercentileItems([97]).map(({ label }) => label)).toStrictEqual([
'p50',
'p75',
'p90',
'p95',
'p97',
'p99',
'p99.9',
]);
});
it('resets cleared percentiles to the saved ones', async () => {
const onChange = jest.fn() as jest.MockedFunction<
ComponentProps<typeof DistributionPercentilesField>['onChange']
>;
render(
<DistributionPercentilesField
value={{ enabled: true, values: [] }}
savedValue={{ enabled: true, values: [50, 90, 99] }}
onChange={onChange}
/>,
);
await userEvent.setup().click(screen.getByTestId('config-field-reset'));
expect(onChange).toHaveBeenCalledWith({
enabled: true,
values: [50, 90, 99],
});
});
it('offers no Reset when the values match the saved ones', () => {
render(
<DistributionPercentilesField
value={{ enabled: true, values: [50, 90, 99] }}
savedValue={{ enabled: true, values: [50, 90, 99] }}
onChange={jest.fn()}
/>,
);
expect(screen.queryByTestId('config-field-reset')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,18 @@
import type { ConfigMultiSelectItem } from '../../controls/ConfigMultiSelect/ConfigMultiSelect';
/** The save API rejects more. */
export const MAX_PERCENTILE_MARKERS = 5;
const PRESET_PERCENTILES = [50, 75, 90, 95, 99, 99.9];
/** The presets plus any saved value outside them, ascending, so nothing saved is hidden. */
export function resolvePercentileItems(
values: number[],
): ConfigMultiSelectItem[] {
return [...new Set([...PRESET_PERCENTILES, ...values])]
.sort((a, b) => a - b)
.map((percentile) => ({
value: String(percentile),
label: `p${percentile}`,
}));
}

View File

@@ -0,0 +1,10 @@
.axes {
display: flex;
flex-direction: column;
gap: 24px;
}
.axis + .axis {
padding-top: 24px;
border-top: 1px solid var(--l1-border);
}

View File

@@ -0,0 +1,77 @@
import { SolidAlertCircle } from '@signozhq/icons';
import { Callout } from '@signozhq/ui/callout';
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
import ConfigField from '../../controls/ConfigField/ConfigField';
import ConfigRangeInput from '../../controls/ConfigRangeInput/ConfigRangeInput';
import { isRangeInverted } from '../../controls/ConfigRangeInput/utils';
import ConfigTiles from '../../controls/ConfigTiles/ConfigTiles';
import { createFieldResetter } from '../../utils/changes';
import { Y_SCALE_HELP, Y_SCALE_OPTIONS } from './options';
import styles from './DistributionAxesSection.module.scss';
function DistributionAxesSection({
value,
savedValue,
onChange,
}: SectionEditorProps<SectionKind.DistributionAxes>): JSX.Element {
const reset = createFieldResetter(value, savedValue, onChange);
const xMin = value?.x?.min;
const xMax = value?.x?.max;
const yScale = value?.y?.scale ?? DashboardtypesDistributionYScaleDTO.linear;
return (
<div className={styles.axes}>
<div className={styles.axis}>
<ConfigField
label="X-axis range"
help={
isRangeInverted(xMin, xMax) ? (
<Callout color="danger" size="sm" icon={<SolidAlertCircle />}>
Min can&apos;t be greater than max.
</Callout>
) : (
'Hides buckets outside the range. Leave empty to show them all.'
)
}
{...reset('x')}
>
<ConfigRangeInput
minTestId="panel-editor-v2-distribution-x-min"
maxTestId="panel-editor-v2-distribution-x-max"
min={xMin}
max={xMax}
onChangeMin={(min): void =>
onChange({ ...value, x: { ...value?.x, min } })
}
onChangeMax={(max): void =>
onChange({ ...value, x: { ...value?.x, max } })
}
/>
</ConfigField>
</div>
<div className={styles.axis}>
<ConfigField
label="Y-axis scale"
help={Y_SCALE_HELP[yScale]}
{...reset('y')}
>
<ConfigTiles
testId="panel-editor-v2-distribution-y-scale"
aria-label="Y-axis scale"
value={yScale}
items={Y_SCALE_OPTIONS}
onChange={(scale): void => onChange({ ...value, y: { scale } })}
/>
</ConfigField>
</div>
</div>
);
}
export default DistributionAxesSection;

View File

@@ -0,0 +1,71 @@
import type { ComponentProps } from 'react';
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
import { render, screen, userEvent } from 'tests/test-utils';
import DistributionAxesSection from '../DistributionAxesSection';
describe('DistributionAxesSection', () => {
it('opens on the defaults the chart draws: every bucket, linear counts', () => {
render(<DistributionAxesSection value={undefined} onChange={jest.fn()} />);
expect(
screen.getByText(
'Hides buckets outside the range. Leave empty to show them all.',
),
).toBeInTheDocument();
expect(
screen.getByText('Bar heights proportional to counts.'),
).toBeInTheDocument();
});
it('writes the x min without dropping the max or the y scale', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<
ComponentProps<typeof DistributionAxesSection>['onChange']
>;
render(
<DistributionAxesSection
value={{
x: { max: 100 },
y: { scale: DashboardtypesDistributionYScaleDTO.log },
}}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('panel-editor-v2-distribution-x-min'));
await user.paste('10');
expect(onChange).toHaveBeenCalledWith({
x: { min: 10, max: 100 },
y: { scale: DashboardtypesDistributionYScaleDTO.log },
});
});
it('flags a min above the max', () => {
render(
<DistributionAxesSection
value={{ x: { min: 100, max: 10 } }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByText("Min can't be greater than max."),
).toBeInTheDocument();
});
it('writes the y scale', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<
ComponentProps<typeof DistributionAxesSection>['onChange']
>;
render(<DistributionAxesSection value={undefined} onChange={onChange} />);
await user.click(screen.getByText('Logarithmic'));
expect(onChange).toHaveBeenCalledWith({
y: { scale: DashboardtypesDistributionYScaleDTO.log },
});
});
});

View File

@@ -0,0 +1,14 @@
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
import { pickScaleOptions } from '../AxesSection/options';
export const Y_SCALE_OPTIONS = pickScaleOptions([
DashboardtypesDistributionYScaleDTO.linear,
DashboardtypesDistributionYScaleDTO.log,
] as const);
export const Y_SCALE_HELP: Record<DashboardtypesDistributionYScaleDTO, string> =
{
linear: 'Bar heights proportional to counts.',
log: 'Keeps small tail buckets visible next to the bulk.',
};

View File

@@ -17,6 +17,8 @@ import {
BAR_LAYOUT_HELP,
BAR_LAYOUT_OPTIONS,
BarLayout,
BUCKET_STACK_HELP,
BUCKET_STACK_OPTIONS,
STACK_MODE_HELP,
STACK_MODE_OPTIONS,
} from './options';
@@ -35,7 +37,8 @@ type VisualizationSectionProps = SectionEditorProps<SectionKind.Visualization> &
/**
* Edits the `visualization` slice: the panel-type switcher (`switchPanelKind`, every
* kind), the per-panel time preference, bar stacking (`stackedBarChart`, Bar only),
* area stacking (`stack`, Area only) and gap filling (`fillSpans`). Each control is
* area stacking (`stack`, Area only), bucket stacking (`stack`, Distribution only)
* and gap filling (`fillSpans`). Each control is
* gated by its `controls` flag, so a kind only renders — and only writes — the fields
* its spec supports.
*/
@@ -137,6 +140,22 @@ function VisualizationSection({
/>
</ConfigField>
)}
{controls.bucketStack && (
<ConfigField
label="Groups in a bucket"
help={stack && BUCKET_STACK_HELP[stack]}
{...reset('stack')}
>
<ConfigTiles
testId="panel-editor-v2-bucket-stack"
aria-label="Groups in a bucket"
value={stack}
items={BUCKET_STACK_OPTIONS}
onChange={(next): void => onChange({ ...value, stack: next })}
/>
</ConfigField>
)}
</>
);
}

View File

@@ -1,3 +1,4 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent, within } from 'tests/test-utils';
import {
DashboardtypesStackModeDTO,
@@ -162,6 +163,43 @@ describe('VisualizationSection', () => {
).not.toBeInTheDocument();
});
it("opens the bucket stack on the kind's seeded default", () => {
render(
<VisualizationSection
value={undefined}
defaultValue={{ stack: DashboardtypesStackModeDTO.normal }}
controls={{ switchPanelKind: false, bucketStack: true }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByText(
'Groups sit on top of each other, so the height shows the bucket total.',
),
).toBeInTheDocument();
});
it('writes the chosen bucket stack', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<
ComponentProps<typeof VisualizationSection>['onChange']
>;
render(
<VisualizationSection
value={undefined}
controls={{ switchPanelKind: false, bucketStack: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('panel-editor-v2-bucket-stack-none'));
expect(onChange).toHaveBeenCalledWith({
stack: DashboardtypesStackModeDTO.none,
});
});
it('toggles fill spans through onChange', async () => {
const user = userEvent.setup();
const onChange = jest.fn();

View File

@@ -55,3 +55,32 @@ export const STACK_MODE_HELP: Record<DashboardtypesStackModeDTO, string> = {
[DashboardtypesStackModeDTO.percent]:
'Each series shows its share of the total at every point in time.',
};
/** Distribution's layout of groups within a bucket. */
export const BUCKET_STACK_OPTIONS: ConfigTileItem<DashboardtypesStackModeDTO>[] =
[
{
value: DashboardtypesStackModeDTO.normal,
label: 'Stacked',
drawing: TILE_DRAWINGS.barsStacked,
},
{
value: DashboardtypesStackModeDTO.none,
label: 'Side by side',
drawing: TILE_DRAWINGS.barsSideBySide,
},
{
value: DashboardtypesStackModeDTO.percent,
label: '100%',
drawing: TILE_DRAWINGS.barsPercent,
},
];
export const BUCKET_STACK_HELP: Record<DashboardtypesStackModeDTO, string> = {
[DashboardtypesStackModeDTO.normal]:
'Groups sit on top of each other, so the height shows the bucket total.',
[DashboardtypesStackModeDTO.none]:
'Groups share each bucket side by side; hard to read past a few groups.',
[DashboardtypesStackModeDTO.percent]:
"Each group's share of the bucket; the y axis becomes a percentage.",
};

View File

@@ -14,6 +14,8 @@ import { Typography } from '@signozhq/ui/typography';
import PromQLIcon from 'assets/Dashboard/PromQl';
import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
import { clearPreviousQuery } from 'components/QueryBuilderV2/QueryV2/previousQuery.utils';
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import { resolveQueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.utils';
import TextToolTip from 'components/TextToolTip';
import ClickHouseQueryContainer from 'container/QueryBuilder/rawQueryEditors/ClickHouse';
import PromQLQueryContainer from 'container/QueryBuilder/rawQueryEditors/PromQL';
@@ -21,9 +23,10 @@ import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryB
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useSyncQueryBuilderFields } from 'components/QueryBuilderV2/useSyncQueryBuilderFields';
import { DataSource } from 'types/common/queryBuilder';
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
import {
getQueryBuilderFields,
getQueryTypeSignals,
isRawRequest,
} from '../../Panels/types/panelCapabilities';
@@ -31,6 +34,7 @@ import type { RenderableQueryPanelDefinition } from '../../Panels/types/panelDef
import { toPanelType } from '../../Panels/types/panelKind';
import { isBuilderQueryType } from 'lib/query/builderSlot';
import { withSingleBucketQuery } from '../utils/bucketQuery';
import { useQueryTypeChange } from './useQueryTypeChange';
import styles from './PanelEditorQueryBuilder.module.scss';
@@ -44,6 +48,8 @@ interface PanelEditorQueryBuilderProps {
onStageRunQuery: () => void;
/** Abort the in-flight preview fetch (the button's cancel action). */
onCancelQuery: () => void;
/** Optional content above the tabs (e.g. Histogram's pointer to Distribution). */
banner?: ReactNode;
/** Optional content pinned below the builder (e.g. the List columns editor). */
footer?: ReactNode;
/** Pin the tabs + Run Query row to the top of the scroll area. Off in the View modal, which shares a scroll area with its own header. */
@@ -60,6 +66,7 @@ function PanelEditorQueryBuilder({
isLoadingQueries,
onStageRunQuery,
onCancelQuery,
banner,
footer,
stickyHeader = true,
}: PanelEditorQueryBuilderProps): JSX.Element {
@@ -73,10 +80,41 @@ function PanelEditorQueryBuilder({
// Raw rows: the builder drops its aggregation controls, and with them the trace
// operator that combines aggregated trace queries (V1 parity).
const isRawQuery = isRawRequest(panelDefinition.queryCapabilities);
const { currentQuery } = useQueryBuilder();
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
// Every query of a panel shares a signal, so the first one speaks for all.
const signal = currentQuery.builder.queryData[0]?.dataSource;
const queryBuilderFields = useMemo(
() =>
getQueryBuilderFields(
panelDefinition,
signal ? DATA_SOURCE_TO_SIGNAL[signal] : undefined,
),
[panelDefinition, signal],
);
const isDarkMode = useIsDarkMode();
useSyncQueryBuilderFields(panelDefinition.syncedQueryBuilderFields);
// A signal switch can hide the extra queries the panel held under its old signal;
// the request would still carry them, so the stored builder keeps one.
const hidesAdditionalQueries = resolveQueryBuilderField(
QueryBuilderField.AdditionalQueries,
queryBuilderFields,
).hidden;
useEffect(() => {
const { queryData, queryFormulas } = currentQuery.builder;
if (
!hidesAdditionalQueries ||
(queryData.length <= 1 && queryFormulas.length === 0)
) {
return;
}
redirectWithQueryBuilderData({
...currentQuery,
builder: withSingleBucketQuery(currentQuery.builder),
});
}, [hidesAdditionalQueries, currentQuery, redirectWithQueryBuilderData]);
// Cleared here, not in QueryBuilderV2: builder panes unmount on every tab switch.
useEffect(() => {
clearPreviousQuery();
@@ -111,7 +149,7 @@ function PanelEditorQueryBuilder({
<div className="query-builder-v2-container">
<QueryBuilderV2
panelType={panelType}
fieldsConfig={panelDefinition.queryBuilderFields}
fieldsConfig={queryBuilderFields}
allowedDataSources={getQueryTypeSignals(
panelDefinition.supportedQueryTypesKindMap,
EQueryType.QUERY_BUILDER,
@@ -187,7 +225,7 @@ function PanelEditorQueryBuilder({
// QB wants a null data source and AI pins traces: both mounted, they overwrite each other's provider config in a loop.
destroyInactiveTabPane: isBuilderQueryType(queryType),
}));
}, [panelDefinition, panelType, isDarkMode, isRawQuery]);
}, [panelDefinition, queryBuilderFields, panelType, isDarkMode, isRawQuery]);
return (
<div
@@ -197,6 +235,7 @@ function PanelEditorQueryBuilder({
role="presentation"
>
<div className={styles.scrollArea}>
{banner}
<Tabs
type="card"
className={cx(styles.tabsContainer, {

View File

@@ -50,7 +50,7 @@ const mockUseQueryBuilder = useQueryBuilder as unknown as jest.Mock;
const BUILDER_QUERY = {
queryType: EQueryType.QUERY_BUILDER,
builder: { queryData: [{ dataSource: 'traces' }] },
builder: { queryData: [{ dataSource: 'traces' }], queryFormulas: [] },
};
const AI_QUERY = {
queryType: EQueryType.AI_QUERY_BUILDER,
@@ -317,6 +317,42 @@ describe('PanelEditorQueryBuilder field visibility (driven by the capabilities g
});
});
describe('PanelEditorQueryBuilder hidden extra queries', () => {
const redirectWithQueryBuilderData = jest.fn();
function renderWithQueries(dataSource: string): void {
jest.clearAllMocks();
mockUseQueryBuilder.mockReturnValue({
currentQuery: {
queryType: EQueryType.QUERY_BUILDER,
builder: {
queryData: [
{ queryName: 'A', dataSource, disabled: false },
{ queryName: 'B', dataSource, disabled: false },
],
queryFormulas: [],
},
},
redirectWithQueryBuilderData,
});
renderBuilder('signoz/DistributionPanel');
}
it('trims a traces Distribution to its one visible query', () => {
renderWithQueries('traces');
const [next] = redirectWithQueryBuilderData.mock.calls[0];
expect(next.builder.queryData).toHaveLength(1);
expect(next.builder.queryData[0].queryName).toBe('A');
});
it('keeps every query of a metrics Distribution', () => {
renderWithQueries('metrics');
expect(redirectWithQueryBuilderData).not.toHaveBeenCalled();
});
});
describe('PanelEditorQueryBuilder signal dropdown (driven by the capabilities guard)', () => {
beforeEach(() => {
jest.clearAllMocks();

View File

@@ -1,8 +1,10 @@
import { act, renderHook } from '@testing-library/react';
import type { DashboardtypesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
initialClickHouseData,
initialFormulaBuilderFormValues,
initialQueriesMap,
initialQueryAIWithType,
initialQueryPromQLData,
PANEL_TYPES,
} from 'constants/queryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
@@ -11,6 +13,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import { act, renderHook } from 'tests/test-utils';
import { resolveQueryType } from 'pages/DashboardPage/DashboardContainer/Panels/capabilities';
import { getBuilderQueries } from '../../../Panels/utils/getBuilderQueries';
@@ -79,6 +82,21 @@ const tracesBuilder = (expression: string): Query['builder'] => ({
queryFormulas: [],
});
const builderWithQueries = (
queries: { queryName: string; disabled: boolean }[],
formulas: { queryName: string; disabled: boolean }[] = [],
): Query['builder'] => ({
...initialQueriesMap.metrics.builder,
queryData: queries.map((query) => ({
...initialQueriesMap.metrics.builder.queryData[0],
...query,
})),
queryFormulas: formulas.map((formula) => ({
...initialFormulaBuilderFormValues,
...formula,
})),
});
function makeSpec(
kind: string,
pluginSpec: unknown,
@@ -103,7 +121,13 @@ function fakeQuery(
queryType: string,
queryData: Record<string, unknown>[] = [],
): Query {
return { id, queryType, builder: { queryData } } as unknown as Query;
return {
id,
queryType,
builder: { queryData },
promql: [],
clickhouse_sql: [],
} as unknown as Query;
}
function builderState(currentQuery: Query): {
@@ -301,12 +325,117 @@ describe('usePanelKindChange', () => {
expect(persisted.builder.queryFormulas).toStrictEqual([]);
});
it('keeps the field of a traces function aggregation when switching to a Heatmap panel', () => {
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
'keeps the first enabled query, enabled, when switching to %s',
(kind) => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(
builderState(fakeQuery('ts-current', 'builder')),
);
mockRebuildBuilder.mockReturnValue(
builderWithQueries(
[
{ queryName: 'A', disabled: true },
{ queryName: 'B', disabled: true },
],
[{ queryName: 'F1', disabled: false }],
),
);
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.TIME_SERIES,
setSpec,
}),
);
act(() => result.current.onChangePanelKind(kind));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(
persisted.builder.queryData.map(({ queryName, disabled }) => ({
queryName,
disabled,
})),
).toStrictEqual([{ queryName: 'A', disabled: false }]);
},
);
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
'keeps one enabled PromQL and ClickHouse query when switching to %s',
(kind) => {
mockUseQueryBuilder.mockReturnValue(
builderState({
...initialQueriesMap.metrics,
promql: ['A', 'B', 'C'].map((name) => ({
...initialQueryPromQLData,
name,
disabled: name === 'A',
})),
clickhouse_sql: ['A', 'B'].map((name) => ({
...initialClickHouseData,
name,
disabled: true,
})),
}),
);
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.TIME_SERIES,
setSpec: jest.fn(),
}),
);
act(() => result.current.onChangePanelKind(kind));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
const summarize = (
queries: { name: string; disabled: boolean }[],
): { name: string; disabled: boolean }[] =>
queries.map(({ name, disabled }) => ({ name, disabled }));
expect(summarize(persisted.promql)).toStrictEqual([
{ name: 'B', disabled: false },
]);
expect(summarize(persisted.clickhouse_sql)).toStrictEqual([
{ name: 'A', disabled: false },
]);
},
);
it('leaves PromQL queries alone when switching to a non-bucket kind', () => {
const promql = ['A', 'B'].map((name) => ({
...initialQueryPromQLData,
name,
}));
mockUseQueryBuilder.mockReturnValue(
builderState({ ...initialQueriesMap.metrics, promql }),
);
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.TIME_SERIES,
setSpec: jest.fn(),
}),
);
act(() => result.current.onChangePanelKind('signoz/BarChartPanel'));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(persisted.promql).toStrictEqual(promql);
});
it('prefers an enabled query over a disabled one ahead of it', () => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(
builderState(fakeQuery('ts-current', 'builder')),
);
mockRebuildBuilder.mockReturnValue(tracesBuilder('p99(duration_nano)'));
mockRebuildBuilder.mockReturnValue(
builderWithQueries([
{ queryName: 'A', disabled: true },
{ queryName: 'B', disabled: false },
]),
);
const { result } = renderHook(() =>
usePanelKindChange({
@@ -315,14 +444,39 @@ describe('usePanelKindChange', () => {
setSpec,
}),
);
act(() => result.current.onChangePanelKind('signoz/HeatmapPanel'));
act(() => result.current.onChangePanelKind('signoz/DistributionPanel'));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(persisted.builder.queryData[0].aggregations).toMatchObject([
{ expression: 'duration_nano' },
expect(persisted.builder.queryData.map((qd) => qd.queryName)).toStrictEqual([
'B',
]);
});
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
'keeps the field of a traces function aggregation when switching to %s',
(kind) => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(
builderState(fakeQuery('ts-current', 'builder')),
);
mockRebuildBuilder.mockReturnValue(tracesBuilder('p99(duration_nano)'));
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.TIME_SERIES,
setSpec,
}),
);
act(() => result.current.onChangePanelKind(kind));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(persisted.builder.queryData[0].aggregations).toMatchObject([
{ expression: 'duration_nano' },
]);
},
);
it('wraps a traces heatmap field in a function when switching to a TimeSeries panel', () => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(

View File

@@ -14,6 +14,7 @@ import {
toDistributionAggregation,
} from 'lib/query/distributionField';
import { rebuildBuilderForPanelType } from 'lib/query/panelQuery';
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
import type { PartialPanelTypes } from 'lib/query/panelTypeDataSourceFormValuesMap';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
@@ -37,8 +38,9 @@ import {
} from '../getSwitchedPluginSpec';
import {
withPercentileHistogramAggregation,
withSingleHeatmapQuery,
} from '../utils/heatmapQuery';
withSingleBucketQuery,
withSingleEnabledQuery,
} from '../utils/bucketQuery';
// V1's panel-type rebuild clears orderBy for lists; re-seed the fresh-list default (timestamp desc).
const DEFAULT_LIST_ORDER_BY: OrderByPayload[] = [
@@ -186,15 +188,15 @@ export function usePanelKindChange({
: transformed,
newKind,
);
const isHeatmap = newKind === 'signoz/HeatmapPanel';
const isBucketPanel = isBucketPanelType(newPanelType);
const converted = {
...ordered,
queryData: ordered.queryData.map(
isHeatmap ? toDistributionAggregation : fromDistributionAggregation,
isBucketPanel ? toDistributionAggregation : fromDistributionAggregation,
),
};
return isHeatmap
? withSingleHeatmapQuery(converted)
return isBucketPanel
? withSingleBucketQuery(converted)
: withPercentileHistogramAggregation(converted);
};
@@ -257,6 +259,10 @@ export function usePanelKindChange({
...(query.builder_ai_query && {
builder_ai_query: rebuildForNewKind(query.builder_ai_query),
}),
...(isBucketPanelType(newPanelType) && {
promql: withSingleEnabledQuery(query.promql),
clickhouse_sql: withSingleEnabledQuery(query.clickhouse_sql),
}),
};
const signal = getBuilderQueries(currentSpec.queries)[0]
?.signal as TelemetrytypesSignalDTO;

View File

@@ -22,23 +22,25 @@ const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
]);
/** What a heatmap cell holds, and the one space aggregation the kind offers. */
const HEATMAP_HISTOGRAM_SPACE_AGGREGATION = 'count';
/** What a bucket panel's cell or bar holds, and the one space aggregation it offers. */
const BUCKET_HISTOGRAM_SPACE_AGGREGATION = 'count';
/**
* A heatmap draws against one bucket axis, so the request takes exactly one enabled
* query and refuses a formula over the cells. The per-kind cache restores whatever is
* dropped here if the panel switches back.
* A bucket panel (heatmap, distribution) draws against one bucket axis, so the request
* takes exactly one enabled query and refuses a formula over the buckets. It keeps the
* first enabled query (the first when none is) and enables it, since a dropped formula
* may have been the only output. The per-kind cache restores whatever is dropped here
* if the panel switches back.
*
* Percentiles go the same way: a histogram heatmap takes its axis from the `le` labels,
* so a percentile draws the grid a count already draws, and the statement builder sums
* the `le` counts either way.
* Percentiles go the same way: a histogram bucket panel takes its axis from the `le`
* labels, so a percentile draws what a count already draws, and the statement builder
* sums the `le` counts either way.
*/
export function withSingleHeatmapQuery(
export function withSingleBucketQuery(
builder: Query['builder'],
): Query['builder'] {
const [first] = builder.queryData;
if (!first) {
const [kept] = withSingleEnabledQuery(builder.queryData);
if (!kept) {
return builder;
}
@@ -46,9 +48,9 @@ export function withSingleHeatmapQuery(
...builder,
queryData: [
{
...first,
spaceAggregation: withoutPercentile(first.spaceAggregation),
aggregations: first.aggregations?.map((aggregation) => ({
...kept,
spaceAggregation: withoutPercentile(kept.spaceAggregation),
aggregations: kept.aggregations?.map((aggregation) => ({
...aggregation,
spaceAggregation: withoutPercentile(
(aggregation as MetricAggregation).spaceAggregation,
@@ -60,21 +62,33 @@ export function withSingleHeatmapQuery(
};
}
/**
* A bucket panel takes one enabled query on every tab: the first enabled one (the first
* when none is), enabled. The per-kind cache restores the rest.
*/
export function withSingleEnabledQuery<T extends { disabled: boolean }>(
queries: T[],
): T[] {
const kept = queries.find((query) => !query.disabled) ?? queries[0];
return kept ? [{ ...kept, disabled: false }] : queries;
}
/** Cast because the substitute is a `SpaceAggregation` whichever of its callers `T` came from. */
function withoutPercentile<T extends string | undefined>(
spaceAggregation: T,
): T {
return (
PERCENTILE_SPACE_AGGREGATIONS.has(spaceAggregation as SpaceAggregation)
? HEATMAP_HISTOGRAM_SPACE_AGGREGATION
? BUCKET_HISTOGRAM_SPACE_AGGREGATION
: spaceAggregation
) as T;
}
/**
* Undoes the count above: every other kind offers a histogram metric percentiles alone,
* so a count carried out of a heatmap would sit in the selector with no option behind
* it. Other metric types are left alone — count is a real choice for a sum or a gauge.
* so a count carried out of a bucket panel would sit in the selector with no option
* behind it. Other metric types are left alone — count is a real choice for a sum or a
* gauge.
*/
export function withPercentileHistogramAggregation(
builder: Query['builder'],
@@ -104,7 +118,7 @@ export function withPercentileHistogramAggregation(
function withoutCount<T extends string | undefined>(spaceAggregation: T): T {
return (
spaceAggregation === HEATMAP_HISTOGRAM_SPACE_AGGREGATION
spaceAggregation === BUCKET_HISTOGRAM_SPACE_AGGREGATION
? DEFAULT_PERCENTILE
: spaceAggregation
) as T;

View File

@@ -8,7 +8,10 @@ import { EQueryType } from 'types/common/dashboard';
import { UNSUPPORTED_PANEL } from '../kinds/UnsupportedPanel/definition';
import { getPanelDefinition, isPanelKindSupported } from '../registry';
import type { PanelQueryCapabilities } from '../types/panelCapabilities';
import {
getQueryBuilderFields,
type PanelQueryCapabilities,
} from '../types/panelCapabilities';
import { NO_PANEL_ACTIONS } from '../types/panelDefinition';
import {
getQueryPanelDefinition,
@@ -24,7 +27,8 @@ import type { PanelKind } from '../types/panelKind';
const { QUERY_BUILDER, CLICKHOUSE, PROM } = EQueryType;
const { logs, traces, metrics } = TelemetrytypesSignalDTO;
const { time_series, scalar, raw, heatmap } = Querybuildertypesv5RequestTypeDTO;
const { time_series, scalar, raw, heatmap, distribution } =
Querybuildertypesv5RequestTypeDTO;
const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
'signoz/TimeSeriesPanel': [
@@ -58,6 +62,7 @@ const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
EQueryType.AI_QUERY_BUILDER,
],
'signoz/HeatmapPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
'signoz/DistributionPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
'signoz/PieChartPanel': [
QUERY_BUILDER,
CLICKHOUSE,
@@ -78,6 +83,7 @@ const EXPECTED_SIGNALS: Record<PanelKind, TelemetrytypesSignalDTO[]> = {
'signoz/NumberPanel': [metrics, logs, traces],
'signoz/HistogramPanel': [metrics, logs, traces],
'signoz/HeatmapPanel': [metrics, logs, traces],
'signoz/DistributionPanel': [metrics, logs, traces],
'signoz/PieChartPanel': [metrics, logs, traces],
'signoz/GeoMapPanel': [metrics, logs, traces],
'signoz/TopListPanel': [metrics, logs, traces],
@@ -133,6 +139,13 @@ const EXPECTED_QUERY_CAPABILITIES: Partial<
orderTiebreaker: false,
serverPaginated: false,
},
'signoz/DistributionPanel': {
requestType: distribution,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
},
'signoz/NumberPanel': {
requestType: scalar,
formatTableResultForUI: false,
@@ -196,6 +209,7 @@ const HIDES_TRACE_OPERATOR: PanelKind[] = [
'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel',
'signoz/HeatmapPanel',
'signoz/DistributionPanel',
];
describe('panel capabilities guard', () => {
@@ -218,6 +232,24 @@ describe('panel capabilities guard', () => {
});
});
describe('formula', () => {
it.each([
[TelemetrytypesSignalDTO.metrics, false],
[TelemetrytypesSignalDTO.logs, true],
[TelemetrytypesSignalDTO.traces, true],
])('a %s distribution hides it: %s', (signal, hidden) => {
expect(
resolveQueryBuilderField(
QueryBuilderField.Formula,
getQueryBuilderFields(
requireQueryPanelDefinition('signoz/DistributionPanel'),
signal,
),
).hidden,
).toBe(hidden);
});
});
// A dashboard spec written by a newer SigNoz can name a kind this build has no
// definition for. The registry answers with UNSUPPORTED_PANEL rather than nothing, so
// every guard below reads it without first proving a definition exists.

View File

@@ -0,0 +1,136 @@
import { useCallback, useMemo, useRef } from 'react';
import type { DashboardtypesDistributionPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import Distribution from 'lib/visualization/charts/Distribution/Distribution';
import type { DistributionBarClick } from 'lib/visualization/charts/Distribution/types';
import { IRenderTooltipFooterArgs } from 'lib/uPlotV2/components/types';
import TooltipFooter from 'lib/visualization/panels/components/TooltipFooter';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import { getDistributionResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import NoData from '../../components/NoData/NoData';
import PanelStyles from '../../panel.module.scss';
import { PanelRendererProps } from '../../types/rendererProps';
import {
resolveDecimalPrecision,
resolveDistributionPercentiles,
resolveDistributionYScale,
resolveLegendPosition,
resolveStackMode,
} from '../../utils/chartAppearance/resolvers';
import { prepareDistributionClickData } from '../../utils/drilldown/prepareDistributionClickData';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { prepareDistributionData } from './prepareData';
function DistributionPanelRenderer({
panelId,
panel,
data,
isFetching,
refetch,
onClick,
enableDrillDown,
}: PanelRendererProps<'signoz/DistributionPanel'>): JSX.Element {
const graphRef = useRef<HTMLDivElement>(null);
const containerDimensions = useResizeObserver(graphRef);
const isDarkMode = useIsDarkMode();
const spec = useMemo<DashboardtypesDistributionPanelSpecDTO>(
() => panel.spec.plugin.spec,
[panel.spec.plugin.spec],
);
const { buckets, series, queryName } = useMemo(
() =>
prepareDistributionData({
results: getDistributionResults(data.response),
legendMap: data.legendMap ?? {},
}),
[data.response, data.legendMap],
);
const percentiles = useMemo(
() => resolveDistributionPercentiles(spec.chartAppearance?.percentiles),
[spec.chartAppearance?.percentiles],
);
const decimalPrecision = useMemo(
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
[spec.formatting?.decimalPrecision],
);
const builderQueries = useMemo(
() => getBuilderQueries(panel.spec.queries),
[panel.spec.queries],
);
const handleBarClick = useCallback(
(click: DistributionBarClick): void => {
const payload = prepareDistributionClickData({
click,
queryName,
builderQueries,
timeRange: getPanelTimeRange(data.requestPayload),
});
if (payload) {
onClick?.(payload);
}
},
[onClick, queryName, builderQueries, data.requestPayload],
);
const renderTooltipFooter = useCallback(
({ isPinned, dismiss }: IRenderTooltipFooterArgs) => (
<TooltipFooter
id={panelId}
isPinned={isPinned}
canDrilldown={!!enableDrillDown}
dismiss={dismiss}
/>
),
[panelId, enableDrillDown],
);
const hasBars = buckets.length > 0 && series.length > 0;
return (
<div
ref={graphRef}
data-testid="distribution-panel-renderer"
className={PanelStyles.panelContainer}
>
{!hasBars && (
<NoData isFetching={isFetching} onRetry={refetch} panel={panel} />
)}
{hasBars &&
containerDimensions.width > 0 &&
containerDimensions.height > 0 && (
<Distribution
key={panelId}
id={panelId}
buckets={buckets}
series={series}
xMin={spec.axes?.x?.min ?? undefined}
xMax={spec.axes?.x?.max ?? undefined}
yScale={resolveDistributionYScale(spec.axes?.y?.scale)}
stack={resolveStackMode(spec.visualization?.stack)}
xAxisUnit={spec.formatting?.unit}
decimalPrecision={decimalPrecision}
customColors={spec.legend?.customColors ?? undefined}
percentiles={percentiles}
canPinTooltip
renderTooltipFooter={renderTooltipFooter}
onBarClick={enableDrillDown && onClick ? handleBarClick : undefined}
legendPosition={resolveLegendPosition(spec.legend?.position)}
isDarkMode={isDarkMode}
width={containerDimensions.width}
height={containerDimensions.height}
/>
)}
</div>
);
}
export default DistributionPanelRenderer;

View File

@@ -0,0 +1,152 @@
import type {
Querybuildertypesv5DistributionDataDTO,
Querybuildertypesv5DistributionDTO,
} from 'api/generated/services/sigNoz.schemas';
import { prepareDistributionData } from '../prepareData';
function result({
queryName = 'A',
buckets = [1, 2, 4],
distributions = [],
}: {
queryName?: string;
buckets?: number[];
distributions?: Querybuildertypesv5DistributionDTO[];
} = {}): Querybuildertypesv5DistributionDataDTO {
return {
queryName,
aggregations: [
{ alias: '__result_0', index: 0, meta: { buckets }, distributions },
],
};
}
describe('prepareDistributionData', () => {
it('reads the bucket bounds and one count array per group', () => {
const { buckets, series, queryName } = prepareDistributionData({
results: [
result({
distributions: [
{
labels: [{ key: { name: 'service' }, value: 'redis' }],
counts: [5, 12, 3, 1],
},
{
labels: [{ key: { name: 'service' }, value: 'cart' }],
counts: [0, 4, 8, 0],
},
],
}),
],
legendMap: {},
});
expect(buckets).toStrictEqual([1, 2, 4]);
expect(queryName).toBe('A');
expect(series).toStrictEqual([
{
label: '{service="redis"}',
groupLabels: { service: 'redis' },
counts: [5, 12, 3, 1],
},
{
label: '{service="cart"}',
groupLabels: { service: 'cart' },
counts: [0, 4, 8, 0],
},
]);
});
it('names an ungrouped distribution after its query', () => {
const { series } = prepareDistributionData({
results: [result({ distributions: [{ counts: [1, 0, 0, 0] }] })],
legendMap: { A: '' },
});
expect(series).toHaveLength(1);
expect(series[0].label).toBe('A');
});
it('applies the query legend as the group label template', () => {
const { series } = prepareDistributionData({
results: [
result({
distributions: [
{
labels: [{ key: { name: 'service' }, value: 'redis' }],
counts: [1, 0, 0, 0],
},
],
}),
],
legendMap: { A: '{{service}} latency' },
});
expect(series[0].label).toBe('redis latency');
});
it('pads missing counts with zero and trims extras, keeping the overflow slot', () => {
const { series } = prepareDistributionData({
results: [
result({
distributions: [
{ counts: [1, 2] },
{ counts: [1, 2, 3, 4, 5] },
{ counts: null },
],
}),
],
legendMap: {},
});
expect(series.map(({ counts }) => counts)).toStrictEqual([
[1, 2, 0, 0],
[1, 2, 3, 4],
[0, 0, 0, 0],
]);
});
it('skips aggregations without bounds and reads the first that has them', () => {
const { buckets } = prepareDistributionData({
results: [
{
queryName: 'A',
aggregations: [
{
alias: '__result_0',
index: 0,
meta: {},
distributions: [{ counts: [1] }],
},
{
alias: '__result_1',
index: 1,
meta: { buckets: [10, 20] },
distributions: [],
},
],
},
],
legendMap: {},
});
expect(buckets).toStrictEqual([10, 20]);
});
it('returns no buckets when nothing carries bounds', () => {
expect(
prepareDistributionData({
results: [result({ buckets: [] })],
legendMap: {},
}),
).toStrictEqual({ buckets: [], series: [], queryName: '' });
expect(prepareDistributionData({ results: [], legendMap: {} })).toStrictEqual(
{
buckets: [],
series: [],
queryName: '',
},
);
});
});

View File

@@ -0,0 +1,70 @@
import {
DashboardtypesPanelKindDTO,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
type DashboardtypesDistributionPanelSpecDTO,
type Querybuildertypesv5DistributionDataDTO,
Querybuildertypesv5RequestTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { PanelOfKind } from '../../../types/rendererProps';
import { getDistributionDataWarning } from '../warning';
function dataWith(buckets: number[], counts: number[][]): PanelQueryData {
const result: Querybuildertypesv5DistributionDataDTO = {
queryName: 'A',
aggregations: [
{
alias: '__result_0',
index: 0,
meta: { buckets },
distributions: counts.map((entry) => ({ counts: entry })),
},
],
};
return {
response: {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.distribution,
data: { results: [result] },
},
},
requestPayload: undefined,
legendMap: {},
};
}
function panelWith(
spec: Partial<DashboardtypesDistributionPanelSpecDTO> = {},
): PanelOfKind<'signoz/DistributionPanel'> {
return {
kind: DashboardtypesPanelKindDTO.Panel,
spec: {
display: { name: '' },
plugin: { kind: DistributionKind['signoz/DistributionPanel'], spec },
queries: [],
},
};
}
describe('getDistributionDataWarning', () => {
it('warns when more than 10% of observations overflow', () => {
const warning = getDistributionDataWarning(
panelWith({ formatting: { unit: 's' } }),
dataWith([1, 10], [[10, 50, 40]]),
);
expect(warning?.message).toMatch(/^40% of observations are above 10/);
});
it('says nothing at or under 10%', () => {
expect(
getDistributionDataWarning(panelWith(), dataWith([1, 10], [[40, 50, 10]])),
).toBeNull();
});
it('says nothing without bounds', () => {
expect(getDistributionDataWarning(panelWith(), dataWith([], []))).toBeNull();
});
});

View File

@@ -0,0 +1,75 @@
import { EQueryType } from 'types/common/dashboard';
import { ChartColumnBig } from '@signozhq/icons';
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import type { PanelDefinition } from '../../types/panelDefinition';
import { QueryTypeKind } from '../../types/panelCapabilities';
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
import Renderer from './Renderer';
import { sections } from './sections';
import { getDistributionDataWarning } from './warning';
import {
Querybuildertypesv5RequestTypeDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
export const definition: PanelDefinition<'signoz/DistributionPanel'> = {
kind: 'signoz/DistributionPanel',
displayName: 'Distribution',
mode: 'query',
icon: ChartColumnBig,
Renderer,
EditorPane: QueryBuilderEditorPane,
sections,
supportedQueryTypesKindMap: {
// Logs and traces bucket the field named as the aggregation.
[EQueryType.QUERY_BUILDER]: {
kind: QueryTypeKind.SIGNAL,
signals: [
TelemetrytypesSignalDTO.metrics,
TelemetrytypesSignalDTO.logs,
TelemetrytypesSignalDTO.traces,
],
},
[EQueryType.CLICKHOUSE]: { kind: QueryTypeKind.SIGNAL_LESS },
[EQueryType.PROM]: { kind: QueryTypeKind.SIGNAL_LESS },
},
// The request rejects both, as for heatmap: a point is a count per bucket.
queryBuilderFields: {
[QueryBuilderField.Functions]: { state: 'hidden' },
[QueryBuilderField.Having]: { state: 'hidden' },
// The request takes one builder query and has no case for a trace operator.
[QueryBuilderField.TraceOperator]: { state: 'hidden' },
},
// Logs and traces bucket the one field the query names; a formula has none.
queryBuilderFieldsBySignal: {
[TelemetrytypesSignalDTO.logs]: {
[QueryBuilderField.Formula]: { state: 'hidden' },
[QueryBuilderField.AdditionalQueries]: { state: 'hidden' },
},
[TelemetrytypesSignalDTO.traces]: {
[QueryBuilderField.Formula]: { state: 'hidden' },
[QueryBuilderField.AdditionalQueries]: { state: 'hidden' },
},
},
// No width-derived step: there is no time axis, and a histogram's counts do not
// depend on the step.
queryCapabilities: {
requestType: Querybuildertypesv5RequestTypeDTO.distribution,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
},
getDataWarning: getDistributionDataWarning,
actions: {
view: true,
edit: true,
clone: true,
download: { csv: false, png: true, svg: true },
createAlert: false,
search: false,
drilldown: true,
},
};

View File

@@ -0,0 +1,82 @@
import type {
Querybuildertypesv5DistributionDataDTO,
Querybuildertypesv5DistributionDTO,
} from 'api/generated/services/sigNoz.schemas';
import getLabelName from 'lib/getLabelName';
import type { DistributionSeries } from 'lib/visualization/charts/Distribution/types';
export interface DistributionPanelData {
/** Ascending bucket upper bounds shared by every group; empty means no chart. */
buckets: number[];
series: DistributionSeries[];
/** The query the series came from, for drilldown. */
queryName: string;
}
const EMPTY_DATA: DistributionPanelData = {
buckets: [],
series: [],
queryName: '',
};
/**
* V5 distribution results → the chart's `buckets` + `series`. Only the first
* aggregation carrying bounds is read: each has its own bucket axis, and the chart
* has one.
*/
export function prepareDistributionData({
results,
legendMap,
}: {
results: Querybuildertypesv5DistributionDataDTO[];
legendMap: Record<string, string>;
}): DistributionPanelData {
for (const result of results) {
const { queryName } = result;
for (const aggregation of result.aggregations ?? []) {
const buckets = aggregation.meta?.buckets;
if (!buckets?.length) {
continue;
}
return {
buckets,
queryName,
series: (aggregation.distributions ?? []).map((distribution) =>
toDistributionSeries(
distribution,
buckets.length + 1,
queryName,
legendMap[queryName] ?? '',
),
),
};
}
}
return EMPTY_DATA;
}
/** Pads or trims to `length` so every series lines up with the bucket axis. */
function toDistributionSeries(
distribution: Querybuildertypesv5DistributionDTO,
length: number,
queryName: string,
legend: string,
): DistributionSeries {
const record: Record<string, string> = {};
(distribution.labels ?? []).forEach((label) => {
if (label.key?.name) {
record[label.key.name] = String(label.value);
}
});
const counts = distribution.counts ?? [];
return {
label: getLabelName(record, queryName, legend),
groupLabels: record,
counts: Array.from({ length }, (_, index) => {
const count = counts[index];
return Number.isFinite(count) ? count : 0;
}),
};
}

View File

@@ -0,0 +1,21 @@
import { SectionKind, type SectionConfig } from '../../types/sections';
import { resolveDistributionLegendSeries } from '../../utils/legendSeries';
export const sections: SectionConfig[] = [
{
kind: SectionKind.Visualization,
controls: { switchPanelKind: true, timePreference: true, bucketStack: true },
},
{
kind: SectionKind.ChartAppearance,
controls: { percentiles: true },
},
// Formats the bucket bounds; counts are plain integers and take no unit.
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
{ kind: SectionKind.DistributionAxes },
{
kind: SectionKind.Legend,
controls: { position: true, colors: resolveDistributionLegendSeries },
},
{ kind: SectionKind.ContextLinks },
];

View File

@@ -0,0 +1,48 @@
import { getToolTipValue } from 'components/Graph/yAxisConfig';
import type { PanelStatusDetail } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { getDistributionResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import type { PanelOfKind } from '../../types/rendererProps';
import { prepareDistributionData } from './prepareData';
/** Above this share in overflow, the bucket bounds probably stop short. */
export const OVERFLOW_WARNING_SHARE = 0.1;
/**
* Bounds that stop short, over every group regardless of the legend: too much
* landing in overflow.
*/
export function getDistributionDataWarning(
panel: PanelOfKind<'signoz/DistributionPanel'>,
data: PanelQueryData,
): PanelStatusDetail | null {
const { buckets, series } = prepareDistributionData({
results: getDistributionResults(data.response),
legendMap: data.legendMap ?? {},
});
if (buckets.length === 0) {
return null;
}
const spec = panel.spec.plugin.spec;
const lastBound = buckets[buckets.length - 1];
let total = 0;
let overflow = 0;
series.forEach(({ counts }) => {
counts.forEach((count) => {
total += count;
});
overflow += counts[buckets.length] ?? 0;
});
const overflowShare = total > 0 ? overflow / total : 0;
if (overflowShare <= OVERFLOW_WARNING_SHARE) {
return null;
}
const bound = getToolTipValue(String(lastBound), spec.formatting?.unit);
return {
message: `${Math.round(overflowShare * 100)}% of observations are above ${bound}. The bucket bounds may be too low.`,
messages: [],
};
}

View File

@@ -0,0 +1,3 @@
.banner {
margin: var(--spacing-4) var(--spacing-6) 0;
}

View File

@@ -0,0 +1,44 @@
import { SolidInfoCircle } from '@signozhq/icons';
import { Callout } from '@signozhq/ui/callout';
import type { QueryEditorPaneProps } from '../../types/panelDefinition';
import PanelEditorQueryBuilder from '../../../PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder';
import styles from './HistogramEditorPane.module.scss';
/**
* Histogram bins the query's values in the browser: percentiles or rates of a
* histogram metric, or per-interval aggregates of logs and traces, not the bucket
* counts Distribution reads.
*/
function HistogramEditorPane({
panelDefinition,
isLoadingQueries,
onStageRunQuery,
onCancelQuery,
stickyHeader,
}: QueryEditorPaneProps): JSX.Element {
return (
<PanelEditorQueryBuilder
panelDefinition={panelDefinition}
isLoadingQueries={isLoadingQueries}
onStageRunQuery={onStageRunQuery}
onCancelQuery={onCancelQuery}
stickyHeader={stickyHeader}
banner={
<div className={styles.banner}>
<Callout
color="primary"
size="sm"
icon={<SolidInfoCircle />}
testId="histogram-distribution-banner"
>
For bucket counts over the time range, use the Distribution panel.
</Callout>
</div>
}
/>
);
}
export default HistogramEditorPane;

View File

@@ -3,7 +3,7 @@ import { BarChart } from '@signozhq/icons';
import type { PanelDefinition } from '../../types/panelDefinition';
import { QueryTypeKind } from '../../types/panelCapabilities';
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
import HistogramEditorPane from './HistogramEditorPane';
import Renderer from './Renderer';
import { sections } from './sections';
import {
@@ -16,8 +16,9 @@ export const definition: PanelDefinition<'signoz/HistogramPanel'> = {
displayName: 'Histogram',
mode: 'query',
icon: BarChart,
isRetired: true,
Renderer,
EditorPane: QueryBuilderEditorPane,
EditorPane: HistogramEditorPane,
sections,
supportedQueryTypesKindMap: {
[EQueryType.QUERY_BUILDER]: {

View File

@@ -1,5 +1,6 @@
import { definition as AreaChart } from './kinds/AreaChartPanel/definition';
import { definition as BarChart } from './kinds/BarChartPanel/definition';
import { definition as Distribution } from './kinds/DistributionPanel/definition';
import { definition as Heatmap } from './kinds/HeatmapPanel/definition';
import { definition as Histogram } from './kinds/HistogramPanel/definition';
import { definition as NumberValue } from './kinds/NumberPanel/definition';
@@ -33,13 +34,14 @@ export const PANELS: PanelRegistry = {
[TopList.kind]: TopList,
[Histogram.kind]: Histogram,
[Heatmap.kind]: Heatmap,
[Distribution.kind]: Distribution,
[List.kind]: List,
[Text.kind]: Text,
};
export type PanelOption = Pick<
PanelDefinition,
'kind' | 'displayName' | 'icon'
'kind' | 'displayName' | 'icon' | 'isRetired'
>;
// Backs both the new-panel picker and the editor's kind switcher; derived from PANELS

View File

@@ -37,6 +37,9 @@ export type PanelInteractionMap = Record<PanelKind, object> & {
'signoz/HeatmapPanel': { onDragSelect?: DragSelect };
'signoz/TablePanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/PieChartPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/DistributionPanel': {
onClick?: (event: DrilldownClickPayload) => void;
};
'signoz/TopListPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/NumberPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/ScatterPlotPanel': {

View File

@@ -4,7 +4,32 @@ import {
type TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
export type { QueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.types';
import type { QueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.types';
import { mergeQueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.utils';
export type { QueryBuilderFieldsConfig };
/** Narrowing applied over a kind's `queryBuilderFields` while the builder points at that signal. */
export type QueryBuilderFieldsBySignal = Partial<
Record<TelemetrytypesSignalDTO, QueryBuilderFieldsConfig>
>;
/** A kind's builder narrowing with its `signal` overrides on top. */
export function getQueryBuilderFields(
{
queryBuilderFields,
queryBuilderFieldsBySignal,
}: {
queryBuilderFields: QueryBuilderFieldsConfig;
queryBuilderFieldsBySignal?: QueryBuilderFieldsBySignal;
},
signal?: TelemetrytypesSignalDTO,
): QueryBuilderFieldsConfig | undefined {
return mergeQueryBuilderFieldsConfig(
queryBuilderFields,
signal ? queryBuilderFieldsBySignal?.[signal] : undefined,
);
}
/**
* How a kind's query-range request is shaped. Declared per-kind in

View File

@@ -13,6 +13,7 @@ import type { PanelKind } from './panelKind';
import type { SyncedQueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import type {
PanelQueryCapabilities,
QueryBuilderFieldsBySignal,
QueryBuilderFieldsConfig,
SupportedQueryTypesKindMap,
} from './panelCapabilities';
@@ -80,6 +81,8 @@ export interface PanelDefinitionBase<K extends PanelKind = PanelKind> {
kind: K;
displayName: string;
icon: PanelIcon;
/** Still renders saved panels, but is offered only to a panel already of this kind. */
isRetired?: boolean;
sections: SectionConfig[];
actions: PanelActionCapabilities;
}
@@ -128,6 +131,7 @@ export interface QueryPanelDefinition<
/** Authoring modes (Query Builder / ClickHouse / PromQL / AI) and the signals each accepts. */
supportedQueryTypesKindMap: SupportedQueryTypesKindMap;
queryBuilderFields: QueryBuilderFieldsConfig;
queryBuilderFieldsBySignal?: QueryBuilderFieldsBySignal;
/** How this kind's query-range request is shaped (request type, paging, result formatting). */
queryCapabilities: PanelQueryCapabilities;
/** Builder fields kept equal across queries: an edit to one query copies to the rest. */

View File

@@ -29,6 +29,7 @@ export const PANEL_KIND_TO_PANEL_TYPE: Record<PanelKind, PANEL_TYPES> = {
'signoz/TopListPanel': PANEL_TYPES.TOP_LIST,
'signoz/TextPanel': PANEL_TYPES.TEXT,
'signoz/ScatterPlotPanel': PANEL_TYPES.SCATTER,
'signoz/DistributionPanel': PANEL_TYPES.DISTRIBUTION,
};
/**

View File

@@ -2,6 +2,8 @@ import type {
DashboardtypesLinkDTO,
DashboardtypesAxesDTO,
DashboardtypesComparisonThresholdDTO,
DashboardtypesDistributionAxesDTO,
DashboardtypesDistributionPercentilesDTO,
DashboardtypesFillModeDTO,
DashboardtypesFillOpacityDTO,
DashboardtypesGeoMapBubblesDTO,
@@ -78,6 +80,8 @@ export enum SectionKind {
Dimensions = 'dimensions',
/** Scatter Plot's per-axis `axes` shape; `Axes` is the single y-axis shape. */
ScatterAxes = 'scatterAxes',
/** Distribution's `axes` shape: the bucket-axis range and count-axis scale. */
DistributionAxes = 'distributionAxes',
/** Geo Map's placement: what a row is, its columns, the area, the layer and the value columns. */
Location = 'location',
/** Top List's row display, for a kind with no chart to style. */
@@ -129,6 +133,8 @@ export interface PanelChartAppearanceSlice {
colors?: DashboardtypesHeatmapColorsDTO & DashboardtypesGeoMapColorsDTO;
/** Scatter Plot's dot size and opacity. */
points?: DashboardtypesScatterPlotPointsDTO;
/** Distribution's percentile markers. */
percentiles?: DashboardtypesDistributionPercentilesDTO;
/** Geo Map's circle radius range. */
bubbles?: DashboardtypesGeoMapBubblesDTO;
/** Geo Map's shape names; unset shows them. */
@@ -146,7 +152,7 @@ export interface PanelVisualizationSlice {
timePreference?: DashboardtypesTimePreferenceDTO;
/** Bar stacking; a kind declares this or `stack`, never both. */
stackedBarChart?: boolean;
/** Area stacking. */
/** Area or Distribution stacking; Distribution's wire enum is nominally distinct with the same members. */
stack?: DashboardtypesStackModeDTO;
fillSpans?: boolean;
}
@@ -171,6 +177,7 @@ export interface SectionSpecMap {
[SectionKind.PanelHeader]: DashboardtypesHeaderOptionsDTO; // spec.plugin.spec.headerOptions (Text)
[SectionKind.Dimensions]: DashboardtypesScatterPlotDimensionsDTO; // spec.plugin.spec.dimensions (Scatter Plot)
[SectionKind.ScatterAxes]: DashboardtypesScatterPlotAxesDTO; // spec.plugin.spec.axes (Scatter Plot)
[SectionKind.DistributionAxes]: DashboardtypesDistributionAxesDTO; // spec.plugin.spec.axes (Distribution)
[SectionKind.Location]: GeoMapPlacementSlice; // spec.plugin.spec.location + .map (Geo Map)
[SectionKind.Appearance]: DashboardtypesTopListAppearanceDTO; // spec.plugin.spec.appearance (Top List)
}
@@ -213,6 +220,8 @@ export interface SectionControls {
colors?: boolean;
/** Scatter Plot's dots: one size, or a min/max range when a size column is bound. */
points?: boolean;
/** Distribution's percentile markers: on/off and which ones. */
percentiles?: boolean;
/** Geo Map's value ramp: palette, scale, steps and a value range. */
mapColors?: boolean;
/** Geo Map's circle radius range. */
@@ -227,12 +236,14 @@ export interface SectionControls {
};
// switchPanelKind → the visualization-type switcher (every kind, so you can switch
// away from any panel); stacking → stackedBarChart (Bar); stackMode → stack
// (Area); fillSpans → fill gaps with 0 (TimeSeries / Area).
// (Area); bucketStack → stack (Distribution); fillSpans → fill gaps with 0
// (TimeSeries / Area).
[SectionKind.Visualization]: {
switchPanelKind: boolean;
timePreference?: boolean;
stacking?: boolean;
stackMode?: boolean;
bucketStack?: boolean;
fillSpans?: boolean;
};
// Editor discriminator (not a spec field): which threshold variant a kind edits.
@@ -255,6 +266,7 @@ export type AtomicSectionKind =
| SectionKind.PanelHeader
| SectionKind.Dimensions
| SectionKind.ScatterAxes
| SectionKind.DistributionAxes
| SectionKind.Location;
/** Predicate to hide a section from the current spec; returning true removes it. */
@@ -292,6 +304,7 @@ export const SECTION_METADATA = {
[SectionKind.PanelHeader]: { title: 'Panel header', icon: PanelTop },
[SectionKind.Dimensions]: { title: 'Dimensions', icon: Crosshair },
[SectionKind.ScatterAxes]: { title: 'Axes', icon: Scale3D },
[SectionKind.DistributionAxes]: { title: 'Axes', icon: Scale3D },
[SectionKind.Location]: { title: 'Location', icon: MapPin },
[SectionKind.Appearance]: { title: 'Appearance', icon: Palette },
} as const satisfies Record<SectionKind, SectionMetadata>;

View File

@@ -16,6 +16,7 @@ import {
import { DEFAULT_BAR_COLOR } from '../../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
import { defaultColumnsForSignal } from '../../../PanelEditor/ListColumnsEditor/selectFields';
import { sections as areaSections } from '../../kinds/AreaChartPanel/sections';
import { sections as distributionSections } from '../../kinds/DistributionPanel/sections';
import { sections as geoMapSections } from '../../kinds/GeoMapPanel/sections';
import { sections as heatmapSections } from '../../kinds/HeatmapPanel/sections';
import { sections as listSections } from '../../kinds/ListPanel/sections';
@@ -371,6 +372,25 @@ describe('buildPluginSpec', () => {
});
describe('chartAppearance seed', () => {
it('seeds a new distribution with the stack and percentiles the server writes', () => {
const spec = buildPluginSpec(distributionSections);
expect(spec.visualization?.stack).toBe(DashboardtypesStackModeDTO.normal);
expect(spec.chartAppearance?.percentiles).toStrictEqual({
enabled: true,
values: [50, 90, 99],
});
});
it("carries a distribution's percentiles across a switch", () => {
const percentiles = { enabled: false, values: [75] };
const spec = buildPluginSpec(distributionSections, {
oldSpec: oldSpecWith({ chartAppearance: { percentiles } }),
});
expect(spec.chartAppearance?.percentiles).toStrictEqual(percentiles);
});
it('seeds only the declared defaulting controls', () => {
const sections: SectionConfig[] = [
{

View File

@@ -0,0 +1,58 @@
import {
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
type DashboardtypesPanelSpecDTO,
type Querybuildertypesv5DistributionDataDTO,
Querybuildertypesv5RequestTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { resolveSeriesColor } from 'lib/visualization/charts/Distribution/colors';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { resolveDistributionLegendSeries } from '../legendSeries';
describe('resolveDistributionLegendSeries', () => {
it('keys each group by the label and default colour the chart draws it with', () => {
const result: Querybuildertypesv5DistributionDataDTO = {
queryName: 'A',
aggregations: [
{
alias: '__result_0',
index: 0,
meta: { buckets: [1] },
distributions: [
{
labels: [{ key: { name: 'service' }, value: 'cart' }],
counts: [1, 2],
},
],
},
],
};
const data: PanelQueryData = {
response: {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.distribution,
data: { results: [result] },
},
},
requestPayload: undefined,
legendMap: { A: '{{service}}' },
};
const spec: DashboardtypesPanelSpecDTO = {
display: { name: '' },
plugin: { kind: DistributionKind['signoz/DistributionPanel'], spec: {} },
queries: [],
};
expect(
resolveDistributionLegendSeries({
spec,
queries: [],
data,
isDarkMode: true,
}),
).toStrictEqual([
{ label: 'cart', defaultColor: resolveSeriesColor('cart', true) },
]);
});
});

View File

@@ -32,6 +32,9 @@ import {
import { DEFAULT_BAR_COLOR } from '../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
import { getTableColumnKeys } from './getTableColumnKeys';
/** Matches what the server writes for unset `chartAppearance.percentiles.values`. */
const DEFAULT_DISTRIBUTION_PERCENTILES = [50, 90, 99];
/** Cross-section of the per-kind spec union; assigned to `plugin.spec` (unknown) at the boundary. */
export interface SeededPluginSpec {
visualization?: SectionSpecMap[SectionKind.Visualization];
@@ -157,7 +160,7 @@ function translateStackingForKind(
}
return {};
}
if (controls.stackMode) {
if (controls.stackMode || controls.bucketStack) {
if (old?.stack !== undefined) {
return { stack: old.stack };
}
@@ -326,6 +329,7 @@ const SECTION_SEEDS: SectionSeeds = {
colors,
bubbles,
labels,
percentiles,
} = oldPluginSpec?.chartAppearance ?? {};
const appearance: SectionSpecMap[SectionKind.ChartAppearance] = {};
if (controls.lineStyle) {
@@ -352,6 +356,13 @@ const SECTION_SEEDS: SectionSeeds = {
if (controls.spanGaps && spanGaps !== undefined) {
appearance.spanGaps = spanGaps;
}
// The server's default for unset percentiles, so a new panel previews the same.
if (controls.percentiles) {
appearance.percentiles = percentiles ?? {
enabled: true,
values: DEFAULT_DISTRIBUTION_PERCENTILES,
};
}
// Seeded so the controls open on the ramp the grid is drawn with; the
// count bounds and step count stay unset, which reads as derived.
const seededColors = seedColors(controls, colors);

View File

@@ -1,5 +1,6 @@
import {
DashboardtypesAreaFillModeDTO,
DashboardtypesDistributionYScaleDTO,
DashboardtypesHeatmapColorModeDTO,
DashboardtypesHeatmapColorScaleDTO,
DashboardtypesHeatmapPaletteDTO,
@@ -15,9 +16,12 @@ import {
ColorRampPalette,
ColorRampScale,
} from 'lib/visualization/colorRamp/types';
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
import {
resolveAreaFillMode,
resolveDistributionPercentiles,
resolveDistributionYScale,
resolveHeatmapAxisScale,
resolveHeatmapColors,
resolveSpanGaps,
@@ -190,3 +194,27 @@ describe('resolveHeatmapColors', () => {
expect(resolveHeatmapColors({ steps: 0 })).toStrictEqual({});
});
});
describe('resolveDistributionYScale', () => {
it('defaults to linear', () => {
expect(resolveDistributionYScale(undefined)).toBe(DistributionYScale.Linear);
expect(
resolveDistributionYScale(DashboardtypesDistributionYScaleDTO.log),
).toBe(DistributionYScale.Log);
});
});
describe('resolveDistributionPercentiles', () => {
it('marks nothing without percentiles; the server always writes them', () => {
expect(resolveDistributionPercentiles(undefined)).toStrictEqual([]);
});
it('marks the configured percentiles, or none when turned off', () => {
expect(
resolveDistributionPercentiles({ enabled: true, values: [75, 99.9] }),
).toStrictEqual([75, 99.9]);
expect(
resolveDistributionPercentiles({ enabled: false, values: [75] }),
).toStrictEqual([]);
});
});

View File

@@ -1,5 +1,6 @@
import {
DashboardtypesAreaFillModeDTO,
DashboardtypesDistributionYScaleDTO,
DashboardtypesFillModeDTO,
DashboardtypesHeatmapColorModeDTO,
DashboardtypesHeatmapColorScaleDTO,
@@ -24,6 +25,7 @@ import {
ColorRampPalette,
ColorRampScale,
} from 'lib/visualization/colorRamp/types';
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
/**
* Bridges the V2 wire-format enums to the uPlotV2 chart enums. String values
@@ -58,7 +60,11 @@ export const AREA_FILL_MODE_MAP: Record<
FillMode
> = omit(FILL_MODE_MAP, DashboardtypesFillModeDTO.none);
export const STACK_MODE_MAP: Record<DashboardtypesStackModeDTO, StackMode> = {
// Keyed by the wire strings, so Distribution's same-valued enum resolves through it too.
export const STACK_MODE_MAP: Record<
`${DashboardtypesStackModeDTO}`,
StackMode
> = {
[DashboardtypesStackModeDTO.none]: StackMode.None,
[DashboardtypesStackModeDTO.normal]: StackMode.Normal,
[DashboardtypesStackModeDTO.percent]: StackMode.Percent,
@@ -114,3 +120,11 @@ export const HEATMAP_Y_SCALE_MAP: Record<
[DashboardtypesHeatmapYScaleDTO.log]: HeatmapAxisScale.Log,
[DashboardtypesHeatmapYScaleDTO.symlog]: HeatmapAxisScale.Symlog,
};
export const DISTRIBUTION_Y_SCALE_MAP: Record<
DashboardtypesDistributionYScaleDTO,
DistributionYScale
> = {
[DashboardtypesDistributionYScaleDTO.linear]: DistributionYScale.Linear,
[DashboardtypesDistributionYScaleDTO.log]: DistributionYScale.Log,
};

View File

@@ -1,6 +1,9 @@
import { rangeUtil } from '@grafana/data';
import {
type DashboardtypesAreaFillModeDTO,
type DashboardtypesDistributionPercentilesDTO,
type DashboardtypesDistributionStackModeDTO,
type DashboardtypesDistributionYScaleDTO,
DashboardtypesHeatmapYScaleDTO,
DashboardtypesLegendPositionDTO,
DashboardtypesPrecisionOptionDTO,
@@ -16,9 +19,11 @@ import { FillMode, StackMode } from 'lib/uPlotV2/config/types';
import { clampColorSteps } from 'lib/visualization/colorRamp/colorScale';
import { HeatmapAxisScale } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
import type { ColorRampOptions } from 'lib/visualization/colorRamp/types';
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
import {
AREA_FILL_MODE_MAP,
DISTRIBUTION_Y_SCALE_MAP,
HEATMAP_COLOR_MODE_MAP,
HEATMAP_COLOR_SCALE_MAP,
HEATMAP_PALETTE_MAP,
@@ -96,7 +101,10 @@ export function resolveAreaFillMode(
/** Missing/unknown falls back to `None` — series drawn independently. */
export function resolveStackMode(
stack: DashboardtypesStackModeDTO | undefined,
stack:
| DashboardtypesStackModeDTO
| DashboardtypesDistributionStackModeDTO
| undefined,
): StackMode {
if (stack && stack in STACK_MODE_MAP) {
return STACK_MODE_MAP[stack];
@@ -104,6 +112,23 @@ export function resolveStackMode(
return StackMode.None;
}
export function resolveDistributionPercentiles(
percentiles: DashboardtypesDistributionPercentilesDTO | undefined,
): number[] {
if (percentiles?.enabled === false) {
return [];
}
return percentiles?.values ?? [];
}
export function resolveDistributionYScale(
scale: DashboardtypesDistributionYScaleDTO | undefined,
): DistributionYScale {
return scale && scale in DISTRIBUTION_Y_SCALE_MAP
? DISTRIBUTION_Y_SCALE_MAP[scale]
: DistributionYScale.Linear;
}
/**
* Row-height distribution of a heatmap's bucket axis. Missing/unknown resolves to
* `auto`, the one option that reads the bucket bounds rather than overriding them.

View File

@@ -11,6 +11,7 @@ import { buildAggregateData } from '../buildAggregateData';
import { stepClickTimeRange } from '../chartClickTimeRange';
import { enrichChartClick } from '../enrichChartClick';
import { enrichNumberClick } from '../enrichNumberClick';
import { prepareDistributionClickData } from '../prepareDistributionClickData';
import { enrichPieClick } from '../enrichPieClick';
import { enrichTableClick } from '../enrichTableClick';
import { getDataLinks } from '../getDataLinks';
@@ -416,6 +417,53 @@ describe('enrichPieClick', () => {
});
});
describe('prepareDistributionClickData', () => {
const click = {
series: {
label: 'cart',
groupLabels: { 'service.name': 'cart' },
counts: [1, 2],
},
color: '#abc',
coordinates: { x: 7, y: 8 },
};
it("filters to the clicked group over the panel's whole window", () => {
const payload = prepareDistributionClickData({
click,
queryName: 'A',
builderQueries: [
builderQuery({
name: 'A',
signal: 'metrics',
groupBy: [{ name: 'service.name' }],
}),
],
timeRange: { startTime: 1, endTime: 2 },
});
expect(payload).toStrictEqual({
coordinates: { x: 7, y: 8 },
context: {
queryName: 'A',
signal: 'metrics',
filters: [
{ filterKey: 'service.name', filterValue: 'cart', operator: '=' },
],
timeRange: { startTime: 1, endTime: 2 },
label: 'cart',
seriesColor: '#abc',
},
});
});
it('returns null without a drillable query', () => {
expect(
prepareDistributionClickData({ click, queryName: '', builderQueries: [] }),
).toBeNull();
});
});
describe('resolvePanelContextLinks', () => {
it('substitutes the clicked field value (_-prefixed) into the label and URL', () => {
const resolved = resolvePanelContextLinks(

View File

@@ -0,0 +1,46 @@
import { isValidQueryName } from 'container/QueryTable/Drilldown/drilldownUtils';
import type { DistributionBarClick } from 'lib/visualization/charts/Distribution/types';
import type { BuilderQuery } from 'types/api/v5/queryRange';
import type { DrilldownClickPayload } from '../../types/drilldown';
import { getGroupByFilters } from './getGroupByFilters';
import { resolveDrilldownSignal } from './signal';
interface PrepareDistributionClickDataArgs {
click: DistributionBarClick;
queryName: string;
builderQueries: BuilderQuery[];
/** The fetched window: a bar sums the whole range, not one step. */
timeRange?: { startTime: number; endTime: number };
}
/**
* Turns a bar click into a drilldown payload, filtered to the clicked group. `null`
* when the bar has no drillable query.
*/
export function prepareDistributionClickData({
click,
queryName,
builderQueries,
timeRange,
}: PrepareDistributionClickDataArgs): DrilldownClickPayload | null {
if (!isValidQueryName(queryName)) {
return null;
}
const builderQuery = builderQueries.find((query) => query.name === queryName);
return {
coordinates: click.coordinates,
context: {
queryName,
signal: resolveDrilldownSignal(builderQuery),
filters: builderQuery
? getGroupByFilters(click.series.groupLabels ?? {}, builderQuery)
: [],
timeRange,
label: click.series.label,
seriesColor: click.color,
},
};
}

View File

@@ -0,0 +1,10 @@
import type { PanelOption } from '../registry';
import type { PanelKind } from '../types/panelKind';
/** A retired kind is offered only to the panel already of it, so it can stay put. */
export function isPanelOptionOffered(
option: PanelOption,
currentKind: PanelKind,
): boolean {
return !option.isRetired || option.kind === currentKind;
}

View File

@@ -5,6 +5,8 @@ import type {
import { themeColors } from 'constants/theme';
import getLabelName from 'lib/getLabelName';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
import { resolveSeriesColor } from 'lib/visualization/charts/Distribution/colors';
import { prepareDistributionData } from '../kinds/DistributionPanel/prepareData';
import { preparePieData } from '../kinds/PieChartPanel/prepareData';
import { getColorGroupLabels } from '../kinds/ScatterPlotPanel/utils/prepareData';
import { getJoinedScalarTable } from './getJoinedScalarTable';
@@ -14,6 +16,7 @@ import { prepareScalarTables } from 'pages/DashboardPage/DashboardContainer/quer
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
flattenTimeSeries,
getDistributionResults,
getScalarResults,
getTimeSeriesResults,
} from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
@@ -59,6 +62,21 @@ function buildLegendSeries(
}));
}
/** One entry per group, labelled and coloured as the Distribution chart draws it. */
export function resolveDistributionLegendSeries({
data,
isDarkMode,
}: LegendSeriesArgs): LegendSeries[] {
const { series } = prepareDistributionData({
results: getDistributionResults(data.response),
legendMap: data.legendMap ?? {},
});
return buildLegendSeries(
series.map((entry) => entry.label),
(label) => resolveSeriesColor(label, isDarkMode),
);
}
/**
* Pie is fed by scalar results, not time series. Reuse the exact slices the renderer
* draws (without overrides, so their colors are the defaults) so the color control keys

View File

@@ -30,7 +30,10 @@ function PanelTypeBrowser({
const [query, setQuery] = useState('');
const [category, setCategory] = useState<CategoryId>('all');
const matched = useMemo(() => filterPanelTypeGroups(query), [query]);
const matched = useMemo(
() => filterPanelTypeGroups(query, selectedKind),
[query, selectedKind],
);
const categories = useMemo(
() => [

View File

@@ -3,6 +3,7 @@ import {
type PanelOption,
} from '../../../../../Panels/registry';
import type { PanelKind } from '../../../../../Panels/types/panelKind';
import { isPanelOptionOffered } from '../../../../../Panels/utils/isPanelOptionOffered';
export type PanelTypeGroupId =
| 'trends'
@@ -60,13 +61,18 @@ const PANEL_TYPE_META: Record<PanelKind, PanelTypeMeta> = {
},
'signoz/HistogramPanel': {
group: 'distributions',
description: 'Distribution of values into buckets',
description: 'Bins query results in the browser',
},
'signoz/HeatmapPanel': {
group: 'distributions',
description: 'Bucket density over time',
isNew: true,
},
'signoz/DistributionPanel': {
group: 'distributions',
description: 'Bucket counts over the time range',
isNew: true,
},
'signoz/NumberPanel': {
group: 'single',
description: 'One aggregate value, large',
@@ -92,12 +98,19 @@ export interface PanelTypeGroup {
}
/** Every group with the items matching `query` (name, description or group label); empty groups included. */
export function filterPanelTypeGroups(query: string): PanelTypeGroup[] {
export function filterPanelTypeGroups(
query: string,
currentKind: PanelKind,
): PanelTypeGroup[] {
const q = query.trim().toLowerCase();
return PANEL_TYPE_GROUPS.map(({ id, label }) => ({
id,
label,
items: PANEL_OPTIONS.filter(({ kind }) => PANEL_TYPE_META[kind].group === id)
items: PANEL_OPTIONS.filter(
(option) =>
PANEL_TYPE_META[option.kind].group === id &&
isPanelOptionOffered(option, currentKind),
)
.map((option) => ({ ...option, ...PANEL_TYPE_META[option.kind] }))
.filter(
(item) =>

View File

@@ -58,6 +58,23 @@ const HEATMAP_CELLS = [
[0.4, 0.85, 0.7, 0.2],
[0.3, 0.65, 0.9, 0.45],
];
// `[lower, upper]` heights (0–44) of two stacked groups per bucket, skewed right.
const DISTRIBUTION_STACKS = [
[6, 3],
[14, 6],
[26, 10],
[20, 12],
[12, 9],
[7, 6],
[4, 3],
[2, 2],
];
const DISTRIBUTION_UPPER = { fill: 'var(--bg-robin-400)', fillOpacity: 0.55 };
const PERCENTILE_MARKER = {
stroke: 'var(--l1-foreground)',
strokeOpacity: 0.6,
};
// Bar lengths (% of the track) for the top-list sketch, longest first.
const TOP_LIST_BARS = [100, 76, 54, 34];
const TEXT_ROWS = [45, 100, 92, 64].map((width, i) => [
@@ -155,6 +172,39 @@ export const PANEL_TYPE_PREVIEWS: Record<PanelKind, JSX.Element> = {
)}
</svg>
),
'signoz/DistributionPanel': (
<svg viewBox="0 0 120 44" preserveAspectRatio="none" className={styles.svg}>
{DISTRIBUTION_STACKS.map(([lower, upper], i) => (
// eslint-disable-next-line react/no-array-index-key
<g key={i}>
<rect
x={i * 15 + 1}
y={44 - lower}
width={13}
height={lower}
style={AREA_FILL}
/>
<rect
x={i * 15 + 1}
y={44 - lower - upper}
width={13}
height={upper}
style={DISTRIBUTION_UPPER}
/>
</g>
))}
<line
x1={88}
x2={88}
y1={2}
y2={44}
strokeWidth={1}
strokeDasharray="3 2"
vectorEffect="non-scaling-stroke"
style={PERCENTILE_MARKER}
/>
</svg>
),
'signoz/ScatterPlotPanel': (
<svg viewBox="0 0 120 44" className={styles.svg}>
{SCATTER_DOTS.map(([cx, cy, r]) => (

View File

@@ -73,6 +73,7 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
const panelTypeItems = usePanelTypeSelectItems({
panelKind,
queryType: query?.queryType ?? EQueryType.QUERY_BUILDER,
signal: query?.signal,
});

View File

@@ -477,25 +477,28 @@ describe('extractLegendMap', () => {
});
describe('hasRunnableQueries', () => {
const heatmapQuery = (
const bucketQuery = (
kind: 'heatmap' | 'distribution',
signal: string,
aggregations: Record<string, unknown>[],
): DashboardtypesQueryDTO[] =>
compositeQuery([
{ type: 'builder_query', spec: { name: 'A', signal, aggregations } },
]).map((query) => ({ ...query, kind: 'heatmap' }) as DashboardtypesQueryDTO);
]).map((query) => ({ ...query, kind }) as DashboardtypesQueryDTO);
it.each([
['logs', [], false],
['traces', [{ expression: ' ' }], false],
['traces', [{ expression: 'duration_nano' }], true],
['metrics', [{ metricName: 'http_latency' }], true],
])(
'%s heatmap with aggregations %j is runnable: %s',
(signal, aggregations, runnable) => {
expect(hasRunnableQueries(heatmapQuery(signal, aggregations))).toBe(
runnable,
);
['heatmap', 'logs', [], false],
['heatmap', 'traces', [{ expression: ' ' }], false],
['heatmap', 'traces', [{ expression: 'duration_nano' }], true],
['heatmap', 'metrics', [{ metricName: 'http_latency' }], true],
['distribution', 'logs', [], false],
['distribution', 'traces', [{ expression: 'duration_nano' }], true],
] as const)(
'%s over %s with aggregations %j is runnable: %s',
(kind, signal, aggregations, runnable) => {
expect(
hasRunnableQueries(bucketQuery(kind, signal, [...aggregations])),
).toBe(runnable);
},
);

View File

@@ -329,7 +329,7 @@ export function extractLegendMap(
/**
* Fetch gate. False with no queries, when every metrics builder query lacks a metric name —
* skipping a guaranteed 400 (V1 parity: `validateMetricNameForMetricsDataSource`) — or when a
* logs/traces heatmap names no field to bucket.
* logs/traces heatmap or distribution names no field to bucket.
*/
export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
const envelopes = toQueryEnvelopes(queries);
@@ -342,7 +342,8 @@ export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
.map((envelope) => envelope.spec as QuerySpecView);
if (
queries[0].kind === Querybuildertypesv5RequestTypeDTO.heatmap &&
(queries[0].kind === Querybuildertypesv5RequestTypeDTO.heatmap ||
queries[0].kind === Querybuildertypesv5RequestTypeDTO.distribution) &&
builderSpecs.some(
(spec) =>
!spec.disabled &&

View File

@@ -123,6 +123,8 @@ export function panelTypeToRequestType(
return Querybuildertypesv5RequestTypeDTO.raw;
case PANEL_TYPES.HEATMAP:
return Querybuildertypesv5RequestTypeDTO.heatmap;
case PANEL_TYPES.DISTRIBUTION:
return Querybuildertypesv5RequestTypeDTO.distribution;
case PANEL_TYPES.TRACE:
return Querybuildertypesv5RequestTypeDTO.trace;
default:

View File

@@ -1,5 +1,6 @@
import type {
Querybuildertypesv5AggregationBucketDTO,
Querybuildertypesv5DistributionDataDTO,
Querybuildertypesv5ExecStatsDTO,
Querybuildertypesv5RawDataDTO,
Querybuildertypesv5RequestTypeDTO,
@@ -36,6 +37,17 @@ export function getHeatmapResults(
[]) as Querybuildertypesv5TimeSeriesDataDTO[];
}
/** One summed count array per group, positional against each aggregation's `meta.buckets`. */
export function getDistributionResults(
response: QueryRangeV5200 | undefined,
): Querybuildertypesv5DistributionDataDTO[] {
if (response?.data?.type !== 'distribution') {
return [];
}
return (response.data.data?.results ??
[]) as Querybuildertypesv5DistributionDataDTO[];
}
export function getScalarResults(
response: QueryRangeV5200 | undefined,
): Querybuildertypesv5ScalarDataDTO[] {

View File

@@ -209,6 +209,12 @@ export const HeatmapTracesField: Story = {
play: pickHeatmapTracesField,
};
/** A new distribution panel's config pane, every section expanded. */
export const ConfigDistribution: Story = {
args: { panel: 'new', newPanelKind: 'distribution' },
play: expandConfigSections,
};
/** A new list panel's config pane, every section expanded. */
export const ConfigList: Story = {
args: { panel: 'new', newPanelKind: 'list' },

View File

@@ -33,6 +33,7 @@ export const NEW_PANEL_KINDS = [
'pie-chart',
'histogram',
'heatmap',
'distribution',
'list',
'text',
'top-list',
@@ -49,6 +50,7 @@ const KIND_BY_OPTION: Record<NewPanelKind, PanelKind> = {
table: 'signoz/TablePanel',
histogram: 'signoz/HistogramPanel',
heatmap: 'signoz/HeatmapPanel',
distribution: 'signoz/DistributionPanel',
list: 'signoz/ListPanel',
text: 'signoz/TextPanel',
'top-list': 'signoz/TopListPanel',

View File

@@ -27,15 +27,17 @@ import { publicDashboardMeta } from '../__story_mockdata__/publicDashboard';
import {
BUCKET_WIDTHS,
DISTRIBUTION_OVERFLOWS,
DISTRIBUTION_X_RANGES,
GAPS,
HEATMAP_COUNT_RANGES,
HEATMAP_FIXED_COUNTS,
HEATMAP_PALETTES,
HEATMAP_SOURCES,
BUCKET_SOURCES,
HEATMAP_Y_SCALES,
LEGEND_POSITIONS,
LINE_STYLES,
MAX_SERIES,
MAX_SERIES_CONTROL,
PANEL_KINDS,
PANEL_RESULTS,
PANELS_DASHBOARD_ID,
@@ -60,9 +62,11 @@ import {
} from './__story_mockdata__/panelResponses';
import type {
BucketWidth,
DistributionOverflow,
DistributionXRange,
Gaps,
HeatmapCountRange,
HeatmapSource,
BucketSource,
PanelArgs,
PanelKind,
PanelResult,
@@ -115,7 +119,7 @@ export const panelsMocks = defineStoryMocks({
stack: choiceControl<StackMode>('Stack', {
group: PANEL,
description:
'Area stacks `normal` or to `percent`; Bar stacks on anything but `none`. No effect on other kinds.',
'Area and Distribution stack `normal` or to `percent`, and Distribution draws `none` side by side; Bar stacks on anything but `none`. No effect on other kinds.',
options: STACK_MODES,
value: StackMode.none,
}),
@@ -137,11 +141,27 @@ export const panelsMocks = defineStoryMocks({
options: HEATMAP_COUNT_RANGES,
value: 'auto',
}),
heatmapSource: choiceControl<HeatmapSource>('Heatmap source', {
distributionXRange: choiceControl<DistributionXRange>(
'Distribution x range',
{
group: PANEL,
description:
'Bucket axis range: `all` shows every bucket, `clamped` hides those outside 10–1000.',
options: DISTRIBUTION_X_RANGES,
value: 'all',
},
),
percentiles: toggleControl('Distribution percentiles', {
group: PANEL,
description:
'The signal the heatmap buckets: a metric, a log field (`attribute.queue_depth`), a span field (`duration_nano`), or a traces query whose field was cleared, which the panel does not run.',
options: HEATMAP_SOURCES,
'Dashed p50, p90 and p99 markers across the Distribution panel.',
value: true,
}),
bucketSource: choiceControl<BucketSource>('Bucket source', {
group: PANEL,
description:
'The signal the Heatmap and Distribution panels bucket: a metric, a log field (`attribute.queue_depth`), a span field (`duration_nano`), or a traces query whose field was cleared, which the panel does not run.',
options: BUCKET_SOURCES,
value: 'metrics',
}),
bucketWidth: choiceControl<BucketWidth>('Histogram bucket width', {
@@ -171,7 +191,8 @@ export const panelsMocks = defineStoryMocks({
}),
yScale: choiceControl<YScale>('Y scale', {
group: PANEL,
description: 'The y axis of Time Series, Bar and Area.',
description:
'The y axis of Time Series, Bar and Area, and the count axis of Distribution.',
options: Y_SCALES,
value: 'linear',
}),
@@ -228,9 +249,9 @@ export const panelsMocks = defineStoryMocks({
series: countControl('Series', {
group: DATA,
description:
'Series on the charts, groups on the heatmap, slices on the pie, rows on the table and the top list.',
'Series on the charts, groups on the heatmap and distribution, slices on the pie, rows on the table and the top list. Side by side, a distribution draws at most 10 and sums the rest into Other.',
value: 4,
max: MAX_SERIES,
max: MAX_SERIES_CONTROL,
}),
pieSlices: choiceControl<PieSlices>('Pie slices', {
group: DATA,
@@ -246,6 +267,13 @@ export const panelsMocks = defineStoryMocks({
options: GAPS,
value: 'none',
}),
overflow: choiceControl<DistributionOverflow>('Distribution overflow', {
group: DATA,
description:
'Observations past the last bucket bound: `low` 2%, `high` 25%, which the panel header flags.',
options: DISTRIBUTION_OVERFLOWS,
value: 'low',
}),
listRows: countControl('List rows', {
group: DATA,
description:
@@ -315,6 +343,7 @@ export const panelsMocks = defineStoryMocks({
listWideRows: values.listWideRows,
gaps: values.gaps,
pieSlices: values.pieSlices,
overflow: values.overflow,
});
}),
),

View File

@@ -16,6 +16,7 @@ import DashboardPage from '../../DashboardPage';
import { panelsMocks } from './Panels.stories.mocks';
import {
playDistributionTooltip,
playLegendRight,
playListJsonBody,
playListPaginated,
@@ -114,19 +115,19 @@ export const HeatmapLog: Story = {
/** A traces heatmap bucketing each span's `duration_nano`. */
export const HeatmapTraces: Story = {
args: { kind: 'Heatmap', heatmapSource: 'traces' },
args: { kind: 'Heatmap', bucketSource: 'traces' },
play: playPanel,
};
/** A logs heatmap bucketing the `attribute.queue_depth` log field. */
export const HeatmapLogs: Story = {
args: { kind: 'Heatmap', heatmapSource: 'logs' },
args: { kind: 'Heatmap', bucketSource: 'logs' },
play: playPanel,
};
/** A traces heatmap with no field to bucket: the panel waits for one instead of querying. */
export const HeatmapNoField: Story = {
args: { kind: 'Heatmap', heatmapSource: 'no field' },
args: { kind: 'Heatmap', bucketSource: 'no field' },
play: playPanel,
};
@@ -136,6 +137,97 @@ export const HeatmapCountRange: Story = {
play: playPanel,
};
/**
* Latency bucket counts over the whole range, one stacked bar per bucket on a log
* bucket axis, with p50, p90 and p99 marked and the overflow bucket hatched.
*/
export const Distribution: Story = {
args: { kind: 'Distribution', stack: StackMode.normal },
play: playPanel,
};
/** Each bucket split between the services, their bars side by side. */
export const DistributionSideBySide: Story = {
args: { kind: 'Distribution', stack: StackMode.none },
play: playPanel,
};
/** Each bucket stacked to 100%, every band its service's share of that bucket. */
export const DistributionPercent: Story = {
args: { kind: 'Distribution', stack: StackMode.percent },
play: playPanel,
};
/** Buckets outside 10–1000 hidden, counts on a log axis. */
export const DistributionClampedLog: Story = {
args: {
kind: 'Distribution',
stack: StackMode.normal,
distributionXRange: 'clamped',
yScale: 'log',
},
play: playPanel,
};
/** A traces distribution bucketing each span's `duration_nano`. */
export const DistributionTraces: Story = {
args: {
kind: 'Distribution',
stack: StackMode.normal,
bucketSource: 'traces',
},
play: playPanel,
};
/** A logs distribution bucketing the `attribute.queue_depth` log field. */
export const DistributionLogs: Story = {
args: { kind: 'Distribution', stack: StackMode.normal, bucketSource: 'logs' },
play: playPanel,
};
/** A traces distribution with no field to bucket: the panel waits for one instead of querying. */
export const DistributionNoField: Story = {
args: {
kind: 'Distribution',
stack: StackMode.normal,
bucketSource: 'no field',
},
play: playPanel,
};
/**
* The tooltip over a bucket: its total, then each service's count and share of its
* own total.
*/
export const DistributionTooltip: Story = {
args: { kind: 'Distribution', stack: StackMode.normal },
play: playDistributionTooltip,
};
/** Fourteen services stacked: every one drawn, with no Other. */
export const DistributionManyGroups: Story = {
args: { kind: 'Distribution', stack: StackMode.normal, series: 14 },
play: playPanel,
};
/**
* Fourteen services side by side: as many as keep every bar 3 px wide in the
* narrowest bucket are drawn, and the rest summed into Other.
*/
export const DistributionSideBySideOther: Story = {
args: { kind: 'Distribution', stack: StackMode.none, series: 14 },
play: playPanel,
};
/**
* A quarter of observations past the last bound: the overflow bar dominates, p99
* reads `> 5 s`, and the header warns that the bounds may be too low.
*/
export const DistributionOverflow: Story = {
args: { kind: 'Distribution', stack: StackMode.normal, overflow: 'high' },
play: playPanel,
};
/** Each service's share of traffic as a donut, with the total in the middle. */
export const Pie: Story = {
args: { kind: 'Pie' },

View File

@@ -25,6 +25,7 @@ export const PANEL_KINDS = [
'Area',
'Histogram',
'Heatmap',
'Distribution',
'Pie',
'Number',
'Table',
@@ -54,15 +55,15 @@ export const HEATMAP_Y_SCALES = Object.values(HeatmapYScale);
export const HEATMAP_COUNT_RANGES = ['auto', 'fixed'] as const;
export const HEATMAP_SOURCES = [
export const BUCKET_SOURCES = [
'metrics',
'logs',
'traces',
'no field',
] as const;
/** The field a logs or traces heatmap buckets. */
export const HEATMAP_FIELDS = {
/** The field a logs or traces heatmap or distribution buckets. */
export const BUCKET_FIELDS = {
logs: 'attribute.queue_depth',
traces: 'duration_nano',
} as const;
@@ -101,6 +102,7 @@ export const PANEL_NAME: Record<PanelKind, string> = {
Area: 'Request rate by service',
Histogram: 'Latency distribution',
Heatmap: 'Latency heatmap',
Distribution: 'Latency buckets',
Pie: 'Traffic share',
Number: 'p99 latency',
Table: 'Calls by service',
@@ -144,6 +146,21 @@ export const HEATMAP_BUCKETS = [
export const HEATMAP_COLUMNS = 30;
/** Exponential, as a latency histogram's `le` bounds are, so `auto` picks log. */
export const DISTRIBUTION_BUCKETS = [
5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000,
];
/** `clamped` hides buckets outside 10–1000. */
export const DISTRIBUTION_X_RANGES = ['all', 'clamped'] as const;
export const DISTRIBUTION_CLAMP = { min: 10, max: 1000 };
/** `high` puts a quarter of each group past the last bound, over the warning's 10%. */
export const DISTRIBUTION_OVERFLOWS = ['low', 'high'] as const;
/** Groups the series control allows: past the 10 a side-by-side distribution draws. */
export const MAX_SERIES_CONTROL = 14;
export const SERVICES = [
'checkout',
'payments',

View File

@@ -6,6 +6,8 @@
import {
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpecDTOKind as AreaChartKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
DashboardtypesDistributionYScaleDTO as DistributionYScale,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTOKind as HeatmapKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpecDTOKind as HistogramKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTOKind as ListKind,
@@ -16,6 +18,7 @@ import {
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind as TopListKind,
MetrictypesSpaceAggregationDTO as SpaceAggregation,
DashboardtypesDistributionStackModeDTO as DistributionStackMode,
DashboardtypesStackModeDTO as StackMode,
DashboardtypesTextModeDTO as TextMode,
Querybuildertypesv5RequestTypeDTO as RequestType,
@@ -24,6 +27,7 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import {
DISTRIBUTION_CLAMP,
HEATMAP_FIXED_COUNTS,
TABLE_SECOND_COLUMN,
TABLE_THRESHOLD_VALUE,
@@ -33,7 +37,7 @@ import {
import {
comparisonThresholds,
labelThresholds,
eventHeatmapQuery,
bucketQuery,
logQuery,
metricQuery,
tableThresholds,
@@ -133,9 +137,39 @@ export const panelShape = (args: PanelArgs): PanelShape => {
},
},
queries: [
args.heatmapSource === 'metrics'
? metricQuery(RequestType.heatmap, { grouped: true, heatmap: true })
: eventHeatmapQuery(args.heatmapSource),
bucketQuery(args.bucketSource, RequestType.heatmap, {
grouped: true,
heatmap: true,
}),
],
};
case 'Distribution':
return {
plugin: {
kind: DistributionKind['signoz/DistributionPanel'],
spec: {
visualization: { stack: DistributionStackMode[args.stack] },
formatting,
legend,
axes: {
x: args.distributionXRange === 'clamped' ? DISTRIBUTION_CLAMP : {},
y: {
scale:
args.yScale === 'log'
? DistributionYScale.log
: DistributionYScale.linear,
},
},
chartAppearance: {
percentiles: { enabled: args.percentiles, values: [50, 90, 99] },
},
},
},
queries: [
bucketQuery(args.bucketSource, RequestType.distribution, {
grouped: true,
histogram: true,
}),
],
};
case 'Pie':

View File

@@ -26,14 +26,14 @@ import {
import {
CHART_THRESHOLD_VALUE,
HEATMAP_FIELDS,
BUCKET_FIELDS,
NUMBER_THRESHOLD_VALUE,
QUERY_NAME,
TABLE_THRESHOLD_VALUE,
TABLE_VALUE_COLUMN,
THRESHOLD_COLOR,
} from './constants';
import type { HeatmapSource, TextSample } from './types';
import type { BucketSource, TextSample } from './types';
export const labelThresholds = (
on: boolean,
@@ -93,6 +93,8 @@ export const TEXT_BODIES: Record<TextSample, string> = {
interface MetricQueryOptions {
grouped: boolean;
heatmap?: boolean;
/** A histogram metric, whose `le` bounds are the bucket axis: no bucket options. */
histogram?: boolean;
name?: string;
metricName?: string;
spaceAggregation?: SpaceAggregation;
@@ -103,6 +105,7 @@ export const metricQuery = (
{
grouped,
heatmap,
histogram,
name = QUERY_NAME,
metricName = 'signoz_latency',
spaceAggregation = SpaceAggregation.p99,
@@ -113,9 +116,10 @@ export const metricQuery = (
signal: MetricSignal.metrics,
aggregations: [
{
metricName: heatmap ? `${metricName}_bucket` : metricName,
spaceAggregation: heatmap ? undefined : spaceAggregation,
timeAggregation: heatmap ? TimeAggregation.increase : TimeAggregation.avg,
metricName: heatmap || histogram ? `${metricName}_bucket` : metricName,
spaceAggregation: heatmap || histogram ? undefined : spaceAggregation,
timeAggregation:
heatmap || histogram ? TimeAggregation.increase : TimeAggregation.avg,
},
],
groupBy: grouped ? [{ name: 'service.name' }] : undefined,
@@ -153,9 +157,10 @@ export const logQuery = (): DashboardtypesQueryDTO => {
};
};
/** `no field` is a traces heatmap whose field was cleared: it saves with no aggregation. */
export const eventHeatmapQuery = (
source: Exclude<HeatmapSource, 'metrics'>,
/** `no field` is a traces query whose field was cleared: it saves with no aggregation. */
export const eventBucketQuery = (
source: Exclude<BucketSource, 'metrics'>,
requestType: typeof RequestType.heatmap | typeof RequestType.distribution,
): DashboardtypesQueryDTO => {
const groupBy = [{ name: 'service.name' }];
const legend = '{{service.name}}';
@@ -168,7 +173,7 @@ export const eventHeatmapQuery = (
? {
name: QUERY_NAME,
signal: LogSignal.logs,
aggregations: [{ expression: HEATMAP_FIELDS.logs }],
aggregations: [{ expression: BUCKET_FIELDS.logs }],
groupBy,
legend,
bucketOptions,
@@ -177,17 +182,27 @@ export const eventHeatmapQuery = (
name: QUERY_NAME,
signal: TraceSignal.traces,
aggregations:
source === 'traces' ? [{ expression: HEATMAP_FIELDS.traces }] : [],
source === 'traces' ? [{ expression: BUCKET_FIELDS.traces }] : [],
groupBy,
legend,
bucketOptions,
};
return {
kind: RequestType.heatmap,
kind: requestType,
spec: {
name: QUERY_NAME,
plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },
},
};
};
/** A heatmap or distribution query over the chosen source. */
export const bucketQuery = (
source: BucketSource,
requestType: typeof RequestType.heatmap | typeof RequestType.distribution,
metricOptions: MetricQueryOptions,
): DashboardtypesQueryDTO =>
source === 'metrics'
? metricQuery(requestType, metricOptions)
: eventBucketQuery(source, requestType);

View File

@@ -8,6 +8,7 @@ import type { Warning } from 'types/api';
import type { MetricRangePayloadV5, RawRow } from 'types/api/v5/queryRange';
import {
queryRangeV5DistributionResponse,
queryRangeV5EmptyResponse,
queryRangeV5HeatmapResponse,
queryRangeV5RawResponse,
@@ -23,17 +24,25 @@ import {
} from '../../__story_mockdata__/panelData';
import {
DISTRIBUTION_BUCKETS,
HEATMAP_BUCKETS,
HEATMAP_COLUMNS,
HOLE,
LONG_TAIL_SLICES,
MAX_SERIES,
MAX_SERIES_CONTROL,
NUMBER_VALUE,
QUERY_NAME,
SERVICES,
TABLE_SECOND_COLUMN,
} from './constants';
import type { Gaps, PanelRequest, PanelResponseArgs, PieSlices } from './types';
import type {
DistributionOverflow,
Gaps,
PanelRequest,
PanelResponseArgs,
PieSlices,
} from './types';
export const serviceAt = (index: number): string =>
index < SERVICES.length
@@ -86,7 +95,7 @@ export const latencyPoints = (
/** The series index a service label was generated from. */
export const serviceIndex = (label: string): number =>
Array.from({ length: MAX_SERIES }, (_unused, index) =>
Array.from({ length: MAX_SERIES_CONTROL }, (_unused, index) =>
serviceAt(index),
).indexOf(label);
@@ -194,6 +203,38 @@ const wideAttributes = (index: number): Record<string, string> =>
]),
);
/**
* A latency-shaped hump per group, peaking a bucket further right every third
* group, plus the overflow count `overflow` asks for.
*/
export const distributionCounts = (
group: number,
overflow: DistributionOverflow,
): number[] => {
const peak = 3 + (group % 3);
const scale = 1 + (group % 4) * 0.4;
const finite = DISTRIBUTION_BUCKETS.map((_bound, index) =>
Math.round(scale * 120 * Math.exp(-((index - peak) ** 2) / 3)),
);
const total = finite.reduce((sum, count) => sum + count, 0);
const share = overflow === 'high' ? 0.25 : 0.02;
return [...finite, Math.round((total * share) / (1 - share))];
};
const distributionResponse = (
count: number,
overflow: DistributionOverflow,
warning: Warning | undefined,
): QueryRangeV5200 =>
queryRangeV5DistributionResponse({
buckets: DISTRIBUTION_BUCKETS,
warning,
distributions: Array.from({ length: count }, (_unused, group) => ({
labels: [{ key: { name: 'service.name' }, value: serviceAt(group) }],
counts: distributionCounts(group, overflow),
})),
});
/** Spaced by the window, newest first, as the `timestamp desc` order asks for. */
const logRows = (
{ start, end }: PanelWindow,
@@ -237,6 +278,7 @@ export const panelQueryResponse = ({
listWideRows,
gaps,
pieSlices,
overflow,
window,
offset,
limit,
@@ -250,6 +292,8 @@ export const panelQueryResponse = ({
switch (kind) {
case 'Heatmap':
return heatmapResponse(window, series, warning);
case 'Distribution':
return distributionResponse(series, overflow, warning);
case 'Pie':
return queryRangeV5ScalarTableResponse({
groupBy: ['service.name'],

View File

@@ -16,9 +16,11 @@ import type { PanelWindow } from '../../__story_mockdata__/panelData';
import type {
BUCKET_WIDTHS,
DISTRIBUTION_OVERFLOWS,
DISTRIBUTION_X_RANGES,
GAPS,
HEATMAP_COUNT_RANGES,
HEATMAP_SOURCES,
BUCKET_SOURCES,
PANEL_KINDS,
PANEL_RESULTS,
PIE_SLICES,
@@ -37,7 +39,7 @@ export type PanelUnit = (typeof UNITS)[number];
export type HeatmapCountRange = (typeof HEATMAP_COUNT_RANGES)[number];
export type HeatmapSource = (typeof HEATMAP_SOURCES)[number];
export type BucketSource = (typeof BUCKET_SOURCES)[number];
export type BucketWidth = (typeof BUCKET_WIDTHS)[number];
@@ -52,6 +54,9 @@ export type SpanGaps = (typeof SPAN_GAPS)[number];
export type TopListAggregation = (typeof TOP_LIST_AGGREGATIONS)[number];
export type PieSlices = (typeof PIE_SLICES)[number];
export type DistributionOverflow = (typeof DISTRIBUTION_OVERFLOWS)[number];
export type DistributionXRange = (typeof DISTRIBUTION_X_RANGES)[number];
/** The controls that shape the dashboard document. */
export interface PanelArgs {
@@ -63,7 +68,7 @@ export interface PanelArgs {
palette: HeatmapPalette;
heatmapScale: HeatmapYScale;
heatmapCounts: HeatmapCountRange;
heatmapSource: HeatmapSource;
bucketSource: BucketSource;
bucketWidth: BucketWidth;
textSample: TextSample;
textAlign: TextAlign;
@@ -73,6 +78,8 @@ export interface PanelArgs {
showPoints: boolean;
spanGaps: SpanGaps;
columnUnits: boolean;
distributionXRange: DistributionXRange;
percentiles: boolean;
showRank: boolean;
showShare: boolean;
topListAggregation: TopListAggregation;
@@ -94,4 +101,5 @@ export interface PanelResponseArgs extends PanelRequest {
listWideRows: boolean;
gaps: Gaps;
pieSlices: PieSlices;
overflow: DistributionOverflow;
}

View File

@@ -1,4 +1,8 @@
import { DashboardtypesHeatmapYScaleDTO as HeatmapYScale } from 'api/generated/services/sigNoz.schemas';
import {
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
DashboardtypesStackModeDTO as StackMode,
} from 'api/generated/services/sigNoz.schemas';
import { MAX_SIDE_BY_SIDE_GROUPS } from 'lib/visualization/charts/Distribution/topGroups';
import {
DEFAULT_COLOR_RAMP_OPTIONS,
getRampBottom,
@@ -10,12 +14,16 @@ import { expect, waitFor, within } from 'storybook/test';
import type uPlot from 'uplot';
import {
DISTRIBUTION_BUCKETS,
HEATMAP_BUCKETS,
HEATMAP_FIXED_COUNTS,
} from '../__story_mockdata__/constants';
import { heatmapCellCounts } from '../__story_mockdata__/panelResponses';
import {
distributionCounts,
heatmapCellCounts,
} from '../__story_mockdata__/panelResponses';
import { PANEL_LOAD, type PanelPlayArgs } from './args';
import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
import { findPlot, toRgb, waitForPlot } from './plot';
const isMultipleOf = (value: number, width: number): boolean =>
@@ -98,3 +106,166 @@ export const expectHeatmap = async (
);
}
};
export const expectDistribution = async (
root: HTMLElement,
args: PanelPlayArgs,
): Promise<void> => {
const isStacked = args.stack !== StackMode.none;
let plot: uPlot | undefined;
await waitFor(async () => {
plot = findPlot(root);
await expect(plot).toBeDefined();
}, PANEL_LOAD);
const drawn = plot as uPlot;
// A stack draws every group. Side by side fits as many as the panel's width allows,
// up to the cap, and sums the rest into Other.
const notice = within(root).queryByTestId('distribution-other-notice');
if (isStacked) {
await expect(notice).not.toBeInTheDocument();
await expect(drawn.series.length - 1).toBe(args.series);
} else {
if (args.series > MAX_SIDE_BY_SIDE_GROUPS) {
await expect(notice).toHaveTextContent(
`of ${args.series} groups; the rest are summed into Other.`,
);
}
await expect(drawn.series.length - 1).toBeLessThanOrEqual(
MAX_SIDE_BY_SIDE_GROUPS,
);
}
// One slot a bucket. Clamped to 10–1000: (10, 25] is slot 2, (500, 1000] slot 7.
if (args.distributionXRange === 'clamped') {
await expect(drawn.scales.x.min).toBe(2);
await expect(drawn.scales.x.max).toBe(8);
} else {
await expect(drawn.scales.x.max ?? 0).toBeLessThanOrEqual(
DISTRIBUTION_BUCKETS.length + 1,
);
}
if (args.stack === StackMode.percent) {
await expect(drawn.scales.y.max ?? 0).toBeGreaterThanOrEqual(100);
} else {
await expect(drawn.scales.y.distr).toBe(args.yScale === 'log' ? 3 : 1);
}
};
/** Rows the tooltip list's 300 px window always holds. */
const TOOLTIP_ROWS_IN_VIEW = 7;
/** Moves uPlot's cursor over `bucket`, low in its column, as a real pointer would. */
const hoverBucket = (plot: uPlot, bucket: number): void => {
const rect = plot.over.getBoundingClientRect();
const init = {
bubbles: true,
clientX: rect.left + plot.valToPos(bucket + 0.5, 'x'),
clientY: rect.top + rect.height - 2,
};
plot.over.dispatchEvent(new MouseEvent('mouseenter', init));
plot.over.dispatchEvent(new MouseEvent('mousemove', init));
};
const bucketCounts = (args: PanelPlayArgs, bucket: number): number[] =>
Array.from(
{ length: args.series },
(_, group) => distributionCounts(group, args.overflow)[bucket],
);
const expectTooltipFor = async (
plot: uPlot,
args: PanelPlayArgs,
bucket: number,
): Promise<void> => {
const drawnGroups = plot.series.length - 1;
hoverBucket(plot, bucket);
const total = bucketCounts(args, bucket).reduce(
(sum, count) => sum + count,
0,
);
const tooltip = await within(document.body).findByTestId(
'distribution-tooltip',
{},
PANEL_LOAD,
);
await waitFor(
async () =>
expect(
within(tooltip).getByTestId('distribution-tooltip-total'),
).toHaveTextContent(total.toLocaleString()),
PANEL_LOAD,
);
// The hovered group sits above the divider. The list below runs largest first, one row
// a drawn group, or over Other the groups Other sums.
const active = within(tooltip).getByTestId('distribution-tooltip-active');
const isOverOther = (active.textContent ?? '').startsWith('Other');
// A lone group collapses into the row above the divider, as in the time-series tooltip.
const list = within(tooltip).queryByTestId('uplot-tooltip-list');
if (!list) {
await expect(drawnGroups).toBe(1);
return;
}
const listed = isOverOther ? args.series - (drawnGroups - 1) : drawnGroups;
// The list renders only the rows in view, so a longer one is checked in part.
const isWhollyRendered = listed <= TOOLTIP_ROWS_IN_VIEW;
// Virtuoso draws one row, measures it, then the rest.
let rows: HTMLElement[] = [];
await waitFor(async () => {
rows = within(list).getAllByTestId('uplot-tooltip-item-content');
if (isWhollyRendered) {
await expect(rows).toHaveLength(listed);
}
}, PANEL_LOAD);
// The label span carries the full label as its title; the count follows it.
const rowLabels = rows.map(
(row) => row.querySelector('[title]')?.getAttribute('title') ?? '',
);
const rowCounts = rows.map((row, index) =>
Number(
(row.textContent ?? '').slice(rowLabels[index].length).replace(/,/g, ''),
),
);
await expect(rowCounts).toStrictEqual([...rowCounts].sort((a, b) => b - a));
// Rows carry each series' full label, as the legend and time-series tooltip do.
if (isWhollyRendered && !isOverOther) {
await expect([...rowLabels].sort()).toStrictEqual(
plot.series
.slice(1)
.map((series) => String(series.label))
.sort(),
);
}
};
/**
* Hovers the (100 ms, 250 ms] bucket, then the overflow one. Only a drawn
* Distribution has a tooltip to check.
*/
export const expectDistributionTooltip = async (
root: HTMLElement,
args: PanelPlayArgs,
): Promise<void> => {
if (
args.kind !== 'Distribution' ||
args.dataState !== 'loaded' ||
args.bucketSource === 'no field' ||
!hasData(args)
) {
return;
}
let plot: uPlot | undefined;
await waitFor(async () => {
plot = findPlot(root);
await expect(plot).toBeDefined();
}, PANEL_LOAD);
const drawn = plot as uPlot;
await expectTooltipFor(drawn, args, DISTRIBUTION_BUCKETS.indexOf(250));
// A clamped range ends at 1000 ms, before the overflow bucket.
if (args.distributionXRange !== 'clamped') {
await expectTooltipFor(drawn, args, DISTRIBUTION_BUCKETS.length);
}
};

View File

@@ -3,7 +3,11 @@ import { expect, within } from 'storybook/test';
import { PANEL_NAME } from '../__story_mockdata__/constants';
import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
import { expectHeatmap, expectHistogram } from './distributions';
import {
expectDistribution,
expectHeatmap,
expectHistogram,
} from './distributions';
import { expectLineChart } from './lineChart';
import { expectListPage } from './list';
import { findPlot } from './plot';
@@ -32,6 +36,7 @@ const KIND_EXPECTATIONS: Record<
Area: expectLineChart,
Histogram: expectHistogram,
Heatmap: expectHeatmap,
Distribution: expectDistribution,
Pie: expectPie,
Number: expectNumber,
Table: expectTable,
@@ -58,7 +63,10 @@ export const expectPanel = async (
await within(root).findByText(PANEL_NAME[args.kind], {}, PANEL_LOAD);
if (args.kind === 'Heatmap' && args.heatmapSource === 'no field') {
if (
(args.kind === 'Heatmap' || args.kind === 'Distribution') &&
args.bucketSource === 'no field'
) {
await within(root).findByTestId('panel-no-query', {}, PANEL_LOAD);
await expect(findPlot(root)).toBeUndefined();
return;
@@ -81,7 +89,11 @@ export const expectPanel = async (
within(root).queryByTestId('panel-status-warning'),
).not.toBeInTheDocument();
}
// The panel's own read of the data, apart from the response's warning.
await expect(
Boolean(within(root).queryByTestId('panel-status-data-warning')),
).toBe(expectsTopListWarning(args));
).toBe(
expectsTopListWarning(args) ||
(args.kind === 'Distribution' && args.overflow === 'high'),
);
};

View File

@@ -1,6 +1,7 @@
import { expect, within } from 'storybook/test';
import type { PanelPlayArgs } from './args';
import { expectDistributionTooltip } from './distributions';
import { expectPanel } from './expectPanel';
import { filterLegend, searchTable } from './interactions';
import { walkListPages } from './list';
@@ -40,3 +41,11 @@ export const playLegendRight: PanelPlay = async ({ canvasElement, args }) => {
await expectPanel(canvasElement, args);
await filterLegend(canvasElement, args);
};
export const playDistributionTooltip: PanelPlay = async ({
canvasElement,
args,
}) => {
await expectPanel(canvasElement, args);
await expectDistributionTooltip(canvasElement, args);
};

View File

@@ -9,6 +9,7 @@ import {
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
type Querybuildertypesv5DistributionDTO,
type Querybuildertypesv5ColumnDescriptorDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
type Querybuildertypesv5TimeSeriesDTO,
@@ -17,6 +18,7 @@ import type { Warning } from 'types/api';
import type {
ColumnDescriptor,
MetricRangePayloadV5,
RawRow,
RequestType,
TimeSeries,
TimeSeriesValue,
@@ -134,7 +136,7 @@ export const queryRangeV5EmptyResponse = (
},
});
export const queryRangeV5RawResponse = <T>(
export const queryRangeV5RawResponse = <T extends RawRow['data']>(
rows: Array<{ timestamp: string; data: T }>,
options: ResponseOptions & {
hasMore?: boolean;
@@ -325,6 +327,37 @@ export const queryRangeV5HeatmapResponse = ({
},
});
interface DistributionResponseSpec {
/** Ascending bucket upper bounds; each distribution carries one count per bound plus the overflow. */
buckets: number[];
distributions: Querybuildertypesv5DistributionDTO[];
queryName?: string;
warning?: Warning;
}
/** A distribution panel's answer: per-group counts summed over the range. */
export const queryRangeV5DistributionResponse = ({
buckets,
distributions,
queryName = 'A',
warning,
}: DistributionResponseSpec): QueryRangeV5200 => ({
status: 'success',
data: {
warning,
type: Querybuildertypesv5RequestTypeDTO.distribution,
data: {
results: [
{
queryName,
aggregations: [{ index: 0, meta: { buckets }, distributions }],
},
],
},
meta: { rowsScanned: 0, bytesScanned: 0, durationMs: 0 },
},
});
/** The v5 request's builder queries and formulas in the shape `keysFor` reads them. */
const v5QueryShapes = (
body: Querybuildertypesv5QueryRangeRequestDTO,

View File

@@ -82,6 +82,7 @@ export const panelTypeToExplorerView: Record<PANEL_TYPES, ExplorerViews> = {
[PANEL_TYPES.PIE]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.HISTOGRAM]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.HEATMAP]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.DISTRIBUTION]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.GEO_MAP]: ExplorerViews.TABLE,
[PANEL_TYPES.TOP_LIST]: ExplorerViews.TABLE,
// Dashboard-only visualisation; explorers never offer it.

View File

@@ -326,18 +326,26 @@ func (m *module) ListTraceSpans(ctx context.Context, orgID valuer.UUID, traceID
if err != nil {
return nil, err
}
// The search runs before the tree is loaded, so that a query that cannot be parsed fails early.
var search *spantypes.SpanSearch
if query.Query != "" {
search, err = m.store.SearchTraceSpans(ctx, orgID, traceID, bounds, query.Query)
if err != nil {
return nil, err
}
}
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
if err != nil {
return nil, err
}
page, err := spantypes.NewSpanListPage(skeleton, query)
page, err := spantypes.NewSpanListPage(skeleton, query, search)
if err != nil {
return nil, err
}
// The attributes of the page's spans are read only when the response shows some of them.
// The full rows of the page's spans are read only for selected fields and for search() snippets.
var rows []spantypes.StorableSpan
if len(query.SelectFields) > 0 {
if page.ReadsAttributes() {
rows, err = m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, page.SpanIDs())
if err != nil {
return nil, err

View File

@@ -72,6 +72,10 @@ type spanDurationRow struct {
TotalNs uint64 `ch:"total_ns"`
}
type spanIDRow struct {
SpanID string `ch:"span_id"`
}
type traceStore struct {
telemetryStore telemetrystore.TelemetryStore
metadataStore telemetrytypes.MetadataStore
@@ -88,7 +92,7 @@ func NewTraceStore(ts telemetrystore.TelemetryStore, metadataStore telemetrytype
}
}
func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spantypes.TraceBounds, error) {
func (store *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spantypes.TraceBounds, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select("trace_id", "min(start) AS start", "max(end) AS end", "sum(num_spans) AS num_spans")
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceSummaryTable))
@@ -97,7 +101,7 @@ func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spant
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var bounds spantypes.TraceBounds
err := s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
&bounds.TraceID, &bounds.Start, &bounds.End, &bounds.NumSpans,
)
if err != nil {
@@ -109,11 +113,11 @@ func (s *traceStore) GetTraceBounds(ctx context.Context, traceID string) (*spant
return &bounds, nil
}
func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceStats, error) {
func (store *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceStats, error) {
table := fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable)
spans := sqlbuilder.NewSelectBuilder()
genAIColumns, err := s.genAISpanColumns(ctx, orgID, bounds, spans)
genAIColumns, err := store.genAISpanColumns(ctx, orgID, bounds, spans)
if err != nil {
return nil, err
}
@@ -175,7 +179,7 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var stats spantypes.TraceStats
err = s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
err = store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(
&stats.StartNs, &stats.EndNs, &stats.TotalSpans, &stats.TotalErrorSpans, &stats.HasMissingSpans,
&stats.RootServiceName, &stats.RootEntryPoint, &stats.RootSpanStatusCode, &stats.GenAISpanCount, &stats.LLMCallCount, &stats.ToolCallCount,
&stats.Tokens.Input, &stats.Tokens.Output, &stats.Tokens.CacheRead, &stats.Tokens.CacheWrite, &stats.Tokens.Reasoning,
@@ -188,30 +192,30 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
}
// genAISpanColumns returns the gen_ai columns aggregated per span, resolved across attribute evolutions.
func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
func (store *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
names := slices.Clone(aiobservabilitytypes.GenAISpanGateKeys)
for _, value := range genAIUsageValues {
names = append(names, value.key)
}
keys, err := s.genAIFieldKeys(ctx, orgID, names)
keys, err := store.genAIFieldKeys(ctx, orgID, names)
if err != nil {
return nil, err
}
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
isGenAI, err := s.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
isGenAI, err := store.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
if err != nil {
return nil, err
}
isLLMCall, err := s.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIRequestModel}, keys, sb)
isLLMCall, err := store.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIRequestModel}, keys, sb)
if err != nil {
return nil, err
}
isToolCall, err := s.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIToolName}, keys, sb)
isToolCall, err := store.anyExistsCondition(ctx, q, []string{aiobservabilitytypes.GenAIToolName}, keys, sb)
if err != nil {
return nil, err
}
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
usageColumns, err := store.genAIUsageColumns(ctx, q, keys)
if err != nil {
return nil, err
}
@@ -219,12 +223,12 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
}
// genAIUsageColumns returns the token and cost columns of a span, resolved across attribute evolutions.
func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
func (store *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
columns := make([]string, 0, len(genAIUsageValues))
for _, value := range genAIUsageValues {
// lookup by number, the type metadata stores numeric attributes under; float64 is only the output cast
// fixed gen_ai keys that many traces lack, so a not-found warning means nothing here
expr, _, err := querybuilder.ResolveColumn(ctx, q, s.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
expr, _, err := querybuilder.ResolveColumn(ctx, q, store.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
if err != nil {
return nil, err
}
@@ -234,7 +238,7 @@ func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo,
return columns, nil
}
func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
func (store *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
sb := selectStorableSpans()
sb.Where(
sb.E("trace_id", traceID),
@@ -246,13 +250,13 @@ func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.StorableSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans")
}
return spans, nil
}
func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]spantypes.MinimalSpan, error) {
func (store *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]spantypes.MinimalSpan, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select(
"DISTINCT ON (span_id) span_id",
@@ -270,13 +274,13 @@ func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start,
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.MinimalSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying minimal spans")
}
return spans, nil
}
func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
func (store *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
if len(spanIDs) == 0 {
return []spantypes.StorableSpan{}, nil
}
@@ -296,7 +300,7 @@ func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, sta
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.StorableSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans by IDs")
}
return spans, nil
@@ -310,8 +314,8 @@ func selectStorableSpans() *sqlbuilder.SelectBuilder {
return sb
}
func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, page spantypes.ThreadPage) ([]spantypes.StorableSpan, error) {
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
func (store *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, page spantypes.ThreadPage) ([]spantypes.StorableSpan, error) {
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
sb := sqlbuilder.NewSelectBuilder()
sb.Select(
"DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "parent_span_id", "has_error", "name", "kind_string",
@@ -320,11 +324,11 @@ func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, trac
"events", "links as references",
)
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
keys, err := s.genAIFieldKeys(ctx, orgID, aiobservabilitytypes.GenAISpanGateKeys)
keys, err := store.genAIFieldKeys(ctx, orgID, aiobservabilitytypes.GenAISpanGateKeys)
if err != nil {
return nil, err
}
isThreadSpan, err := s.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
isThreadSpan, err := store.anyExistsCondition(ctx, q, aiobservabilitytypes.GenAISpanGateKeys, keys, sb)
if err != nil {
return nil, err
}
@@ -363,13 +367,13 @@ func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, trac
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.StorableSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying thread spans")
}
return spans, nil
}
func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, spanID string) (*spantypes.ThreadCursor, error) {
func (store *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, spanID string) (*spantypes.ThreadCursor, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select("toUnixTimestamp64Nano(timestamp)")
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
@@ -383,7 +387,7 @@ func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var timeUnixNano int64
if err := s.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(&timeUnixNano); err != nil {
if err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, args...).Scan(&timeUnixNano); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errors.NewNotFoundf(spantypes.ErrCodeThreadSpanNotFound, "span %s not found in trace %s", spanID, traceID)
}
@@ -392,7 +396,7 @@ func (s *traceStore) GetThreadCursor(ctx context.Context, traceID string, bounds
return &spantypes.ThreadCursor{TimeUnixNano: uint64(timeUnixNano), SpanID: spanID}, nil
}
func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
func (store *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select(
"span_id",
@@ -429,13 +433,13 @@ func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, sta
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var spans []spantypes.StorableSpan
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying flamegraph spans")
}
return spans, nil
}
func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
func (store *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
fieldExpr, err := buildFieldExpr(fieldKey)
if err != nil {
return nil, err
@@ -453,7 +457,7 @@ func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bo
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var rows []spanCountRow
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying span count by field")
}
result := make(map[string]uint64, len(rows))
@@ -463,7 +467,7 @@ func (s *traceStore) GetSpanCountByField(ctx context.Context, traceID string, bo
return result, nil
}
func (s *traceStore) GetSpanDurationByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
func (store *traceStore) GetSpanDurationByField(ctx context.Context, traceID string, bounds *spantypes.TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error) {
fieldExpr, err := buildFieldExpr(fieldKey)
if err != nil {
return nil, err
@@ -507,7 +511,7 @@ func (s *traceStore) GetSpanDurationByField(ctx context.Context, traceID string,
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var rows []spanDurationRow
if err := s.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &rows, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying span duration by field")
}
result := make(map[string]uint64, len(rows))
@@ -522,12 +526,12 @@ func attributeKey(name string, dataType telemetrytypes.FieldDataType) *telemetry
}
// genAIFieldKeys fetches the metadata keys for the attribute names, expanded across semconv families.
func (s *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, names []string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
func (store *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, names []string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
selectors := make([]*telemetrytypes.FieldKeySelector, 0, len(names))
for _, name := range names {
selectors = append(selectors, &telemetrytypes.FieldKeySelector{Name: name, Signal: telemetrytypes.SignalTraces, FieldContext: telemetrytypes.FieldContextAttribute, SelectorMatchType: telemetrytypes.FieldSelectorMatchTypeExact})
}
keys, _, err := s.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, s.flagger, selectors))
keys, _, err := store.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, store.flagger, selectors))
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error fetching gen_ai field keys")
}
@@ -536,10 +540,10 @@ func (s *traceStore) genAIFieldKeys(ctx context.Context, orgID valuer.UUID, name
// anyExistsCondition ORs an EXISTS test per attribute name, resolved across attribute evolutions
// and the use_trace_attributes_json flag so the filter reads the same columns the query builder does.
func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo, names []string, keys map[string][]*telemetrytypes.TelemetryFieldKey, sb *sqlbuilder.SelectBuilder) (string, error) {
func (store *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo, names []string, keys map[string][]*telemetrytypes.TelemetryFieldKey, sb *sqlbuilder.SelectBuilder) (string, error) {
conds := make([]string, 0, len(names))
for _, name := range names {
keyConds, _, err := querybuilder.Conditions(ctx, q, s.storage, attributeKey(name, telemetrytypes.FieldDataTypeString), qbtypes.FilterOperatorExists, nil, keys, false, sb)
keyConds, _, err := querybuilder.Conditions(ctx, q, store.storage, attributeKey(name, telemetrytypes.FieldDataTypeString), qbtypes.FilterOperatorExists, nil, keys, false, sb)
if err != nil {
return "", err
}
@@ -548,17 +552,17 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
return sb.Or(conds...), nil
}
func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
func (store *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
names := make([]string, 0, len(genAIUsageValues))
for _, value := range genAIUsageValues {
names = append(names, value.key)
}
keys, err := s.genAIFieldKeys(ctx, orgID, names)
keys, err := store.genAIFieldKeys(ctx, orgID, names)
if err != nil {
return nil, err
}
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
q := querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
usageColumns, err := store.genAIUsageColumns(ctx, q, keys)
if err != nil {
return nil, err
}
@@ -584,7 +588,7 @@ func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, tr
sb.OrderByAsc("span_id")
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := s.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
rows, err := store.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace skeleton")
}
@@ -618,3 +622,53 @@ func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, tr
}
return builder.Build(), nil
}
func (store *traceStore) SearchTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, query string) (*spantypes.SpanSearch, error) {
selectors := querybuilder.QueryStringToKeysSelectors(query)
for _, selector := range selectors {
selector.Signal = telemetrytypes.SignalTraces
selector.SelectorMatchType = telemetrytypes.FieldSelectorMatchTypeExact
}
keys, _, err := store.metadataStore.GetKeysMulti(ctx, orgID, querybuilder.ExpandKeySelectorsForFamilies(ctx, orgID, store.flagger, selectors))
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error fetching query field keys")
}
search := &spantypes.SpanSearch{}
sb := sqlbuilder.NewSelectBuilder()
sb.Select("DISTINCT span_id")
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
sb.Where(
sb.E("trace_id", traceID),
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
sb.LE("ts_bucket_start", bounds.End.Unix()),
)
prepared, err := querybuilder.PrepareWhereClause(query, querybuilder.FilterExprVisitorOpts{
Context: ctx,
Query: querybuilder.NewQueryInfo(ctx, orgID, store.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano())),
Storage: store.storage,
FieldKeys: keys,
Builder: sb,
})
if err != nil {
return nil, err
}
if !prepared.IsEmpty() {
sb.AddWhereClause(prepared.WhereClause)
}
for _, term := range prepared.SearchTerms {
search.Words = append(search.Words, spantypes.SearchWord{Text: term.Text, Contexts: term.Contexts})
}
search.Warnings = prepared.Warnings
stmt, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
var rows []spanIDRow
if err := store.telemetryStore.ClickhouseDB().Select(ctx, &rows, stmt, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error searching trace spans")
}
search.SpanIDs = make([]string, len(rows))
for i, row := range rows {
search.SpanIDs[i] = row.SpanID
}
return search, nil
}

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