Compare commits

...

42 Commits

Author SHA1 Message Date
Abhi Kumar
398b1222fb refactor(dashboard): reuse the single-query helper and name the default percentiles 2026-11-25 18:53:14 +05:30
Abhi Kumar
29fde6be19 refactor(dashboard): call heatmap and distribution bucket panels throughout
isBucketPanelType (bucketPanelTypes.ts) and prepareDistributionClickData, matching the other
prepare*ClickData helpers.
2026-11-25 18:53:14 +05:30
Abhi Kumar
27e18b7a31 test(storybook): wait for the distribution tooltip list to finish drawing 2026-11-25 18:53:14 +05:30
Abhi Kumar
701eac5364 test(dashboard): follow the jest rules in the distribution editor tests 2026-11-25 18:53:14 +05:30
Abhi Kumar
3eb014ac3f test(storybook): check distribution tooltip rows against the series labels 2026-11-25 18:53:14 +05:30
Abhi Kumar
74a82a31a1 fix(dashboard): keep one enabled PromQL and ClickHouse query on a bucket panel switch 2026-11-25 18:53:14 +05:30
Abhi Kumar
7003813175 refactor(dashboard): take distribution stack and percentile defaults from the server
The server writes both now; a new panel seeds the same values, as Area seeds its stack.
2026-11-25 18:53:14 +05:30
Abhi Kumar
b60750c393 test(storybook): expect stacked distributions to draw every group 2026-11-25 18:53:14 +05:30
Abhi Kumar
c1b2107b9e refactor(dashboard): move the percentile resolver out of its field component 2026-11-25 18:53:14 +05:30
Abhi Kumar
836f59becc test(storybook): look up every generated service name in panel plays 2026-11-25 18:53:14 +05:30
Abhi Kumar
4d7af6a20c refactor(dashboard): name the bucket panel query helpers generically 2026-11-25 18:53:14 +05:30
Abhi Kumar
e9177dd8ea test(dashboard): type the bucket-switch query fixtures 2026-11-25 18:53:14 +05:30
Abhi Kumar
295b837a78 fix(dashboard): show percentile Reset against the saved defaults 2026-11-25 18:53:14 +05:30
Abhi Kumar
1996cdb1fb test(storybook): cover the distribution editor's config pane 2026-11-25 18:53:14 +05:30
Abhi Kumar
26a5ac3507 refactor(dashboard): read the distribution query name as the API types it 2026-11-25 18:53:14 +05:30
Abhi Kumar
0717c0b5ba feat(dashboard): configure context links on distribution panels 2026-11-25 18:53:14 +05:30
Abhi Kumar
eefb1837fb feat(dashboard): let histogram and distribution panels switch directly 2026-11-25 18:53:14 +05:30
Abhi Kumar
307408634f fix(dashboard): keep one enabled query when switching to a bucket panel 2026-11-25 18:53:14 +05:30
Abhi Kumar
c2983f34d5 refactor(dashboard): keep distribution stacking under visualization
Matches the area chart, which keeps its stack mode there. The enum stays
separate: distribution defaults to normal, area to none.
2026-11-25 18:53:14 +05:30
Abhi Kumar
5d7e250e02 feat(dashboard): drop the cumulative share column from the distribution tooltip 2026-11-25 18:53:14 +05:30
Abhi Kumar
a5773dcddc feat(dashboard): support logs and traces in the distribution panel 2026-11-25 18:53:14 +05:30
Abhi Kumar
b5f5387246 fix(dashboard): adapt the distribution panel to the reworked ui and query types 2026-11-25 18:53:14 +05:30
Abhi Kumar
49a025243b test(dashboard): keep the distribution tooltip play passing for every control 2026-11-25 18:53:14 +05:30
Abhi Kumar
83803e020a test(dashboard): type distribution panel fixtures and use the test harness 2026-11-25 18:53:14 +05:30
Abhi Kumar
7d25dc40ad test(dashboard): add distribution panel stories 2026-11-25 18:53:14 +05:30
Abhi Kumar
c24be2d17c feat(dashboard): point metric histograms at the distribution panel 2026-11-25 18:53:14 +05:30
Abhi Kumar
d054046688 feat(dashboard): keep histogram and distribution panels from switching into each other
Histogram bins raw values; Distribution reads histogram buckets. Neither query converts.
2026-11-25 18:53:14 +05:30
Abhi Kumar
04bdb49abd feat(dashboard): add distribution editor controls 2026-11-25 18:53:14 +05:30
Abhi Kumar
59f8fbecfc feat(dashboard): add the distribution panel kind
Regenerates the API types here: the new kind widens the panel kind union, which the
exhaustive panel registry only satisfies once the kind is registered.
2026-11-25 18:53:14 +05:30
Abhi Kumar
20dda1d872 feat(dashboard): read distribution query results 2026-11-25 18:53:14 +05:30
Abhi Kumar
479238cb40 feat(query-builder): treat distribution like heatmap for bucket options 2026-11-25 18:53:14 +05:30
Abhi Kumar
08d7bbc32f refactor(dashboard): name the default distribution percentiles 2026-11-25 18:53:13 +05:30
Abhi Kumar
542fd1432d chore(api): regenerate the frontend api clients 2026-11-25 18:53:13 +05:30
Abhi Kumar
f0b805ce21 chore(api): regenerate openapi spec 2026-11-25 18:53:13 +05:30
Abhi Kumar
e802abaf74 test(dashboard): decode the distribution dashboard without copying its spec 2026-11-25 18:53:13 +05:30
Abhi Kumar
0cd4b05cc3 refactor(dashboard): resolve distribution stack and percentile defaults on the backend
Distribution reuses StackMode, defaulting to normal when written. Unset percentiles are written
as enabled at [50, 90, 99], so both fields are required and the frontend stops knowing them.
2026-11-25 18:53:13 +05:30
Abhi Kumar
2733421a05 refactor(dashboard): keep distribution stacking under visualization
Matches the area chart, which keeps its stack mode there. The enum stays
separate: distribution defaults to normal, area to none.
2026-11-25 18:53:13 +05:30
Naman Verma
be0baa98fa chore: follow established pattern for validations 2026-11-25 18:53:13 +05:30
Naman Verma
3f4a28f86d chore: move validations to the correct types 2026-11-25 18:53:13 +05:30
Abhi Kumar
53887f9788 refactor(dashboard): name distribution spec receivers by role 2026-11-25 18:53:13 +05:30
Abhi Kumar
0fef6d1a6f chore: regenerate openapi specs 2026-11-25 18:53:13 +05:30
Abhi Kumar
5eb5a23269 feat(dashboard): add distribution panel spec 2026-11-25 18:53:13 +05:30
92 changed files with 3159 additions and 214 deletions

View File

@@ -4523,6 +4523,109 @@ 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
DashboardtypesDistributionPercentiles:
properties:
enabled:
description: Whether percentile markers are drawn. Defaults to true.
type: boolean
values:
description: The percentiles to mark, each in (0, 100), at most 5, no duplicates.
Defaults to [50, 90, 99]; [] marks none.
items:
format: double
type: number
type: array
required:
- enabled
- values
type: object
DashboardtypesDistributionVisualization:
properties:
stack:
allOf:
- $ref: '#/components/schemas/DashboardtypesStackMode'
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 +5621,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 +5648,7 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5560,6 +5665,7 @@ components:
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
- signoz/DistributionPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5591,6 +5697,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 +5895,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 +6033,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 +6191,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

View File

@@ -7248,6 +7248,114 @@ 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;
}
export interface DashboardtypesDistributionPercentilesDTO {
/**
* @type boolean
* @description Whether percentile markers are drawn. Defaults to true.
*/
enabled: boolean;
/**
* @type array
* @description The percentiles to mark, each in (0, 100), at most 5, no duplicates. Defaults to [50, 90, 99]; [] marks none.
*/
values: number[];
}
export interface DashboardtypesDistributionChartAppearanceDTO {
/**
* @description Percentile markers drawn across the bucket axis.
*/
percentiles?: DashboardtypesDistributionPercentilesDTO;
}
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: DashboardtypesStackModeDTO;
/**
* @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 +7369,8 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -7750,14 +7859,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 +7886,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 +8659,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.

View File

@@ -286,7 +286,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

@@ -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';
@@ -105,7 +106,7 @@ function QueryAddOns({
}
if (
panelType === PANEL_TYPES.HEATMAP &&
isBucketPanelType(panelType) &&
!(
query.dataSource === DataSource.METRICS &&
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')

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,

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

@@ -514,6 +514,24 @@ describe('QueryAddOns', () => {
).toBeInTheDocument();
});
it('is offered on a metrics distribution too', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.METRICS })}
version="v5"
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

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

@@ -336,6 +336,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';
@@ -186,9 +186,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

@@ -11,7 +11,7 @@ export type OrderByFilterProps = {
entityVersion?: string;
isNewQueryV2?: 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

@@ -32,6 +32,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

@@ -19,7 +19,7 @@ import {
} from 'constants/queryBuilder';
import {
metricsGaugeSpaceAggregateOperatorOptions,
metricsHeatmapHistogramSpaceAggregateOperatorOptions,
metricsBucketHistogramSpaceAggregateOperatorOptions,
metricsHistogramSpaceAggregateOperatorOptions,
metricsSumSpaceAggregateOperatorOptions,
metricsUnknownSpaceAggregateOperatorOptions,
@@ -60,6 +60,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,
@@ -183,10 +184,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:
@@ -310,13 +310,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,
@@ -102,13 +103,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;
}
@@ -173,11 +174,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

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

@@ -44,6 +44,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 +62,7 @@ function PanelEditorQueryBuilder({
isLoadingQueries,
onStageRunQuery,
onCancelQuery,
banner,
footer,
stickyHeader = true,
}: PanelEditorQueryBuilderProps): JSX.Element {
@@ -199,6 +202,7 @@ function PanelEditorQueryBuilder({
role="presentation"
>
<div className={styles.scrollArea}>
{banner}
<Tabs
type="card"
className={cx(styles.tabsContainer, {

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(
};
}
/**
* The PromQL and ClickHouse tabs take one enabled query on a bucket panel too: 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

@@ -24,7 +24,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 +59,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 +80,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 +136,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 +206,7 @@ const HIDES_TRACE_OPERATOR: PanelKind[] = [
'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel',
'signoz/HeatmapPanel',
'signoz/DistributionPanel',
];
describe('panel capabilities guard', () => {

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,64 @@
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' },
},
// 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 {
@@ -17,7 +17,7 @@ export const definition: PanelDefinition<'signoz/HistogramPanel'> = {
mode: 'query',
icon: BarChart,
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,6 +34,7 @@ export const PANELS: PanelRegistry = {
[TopList.kind]: TopList,
[Histogram.kind]: Histogram,
[Heatmap.kind]: Heatmap,
[Distribution.kind]: Distribution,
[List.kind]: List,
[Text.kind]: Text,
};

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

@@ -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
@@ -114,3 +116,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,8 @@
import { rangeUtil } from '@grafana/data';
import {
type DashboardtypesAreaFillModeDTO,
type DashboardtypesDistributionPercentilesDTO,
type DashboardtypesDistributionYScaleDTO,
DashboardtypesHeatmapYScaleDTO,
DashboardtypesLegendPositionDTO,
DashboardtypesPrecisionOptionDTO,
@@ -16,9 +18,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,
@@ -104,6 +108,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 EnrichDistributionClickArgs {
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,
}: EnrichDistributionClickArgs): 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

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

@@ -60,13 +60,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',

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

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

@@ -198,6 +198,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,
DashboardtypesStackModeDTO 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,
@@ -18,6 +19,7 @@ import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
import type {
ColumnDescriptor,
MetricRangePayloadV5,
RawRow,
RequestType,
TimeSeries,
TimeSeriesValue,
@@ -136,7 +138,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;
@@ -417,6 +419,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

@@ -669,6 +669,237 @@ func TestValidateHeatmapDashboard(t *testing.T) {
assert.Equal(t, request, rereadRequest)
}
func TestValidateDistributionDashboard(t *testing.T) {
data, err := os.ReadFile("testdata/perses_distribution_panel.json")
require.NoError(t, err, "reading example file")
dashboard := &DashboardV2{}
require.NoError(t, json.Unmarshal(data, &dashboard.Spec), "unmarshal and validate failed")
spec := &dashboard.Spec
require.IsType(t, &DistributionPanelSpec{}, spec.Panels["p1"].Spec.Plugin.Spec)
panelSpec := spec.Panels["p1"].Spec.Plugin.Spec.(*DistributionPanelSpec)
require.NotNil(t, panelSpec.Axes.X.Min)
assert.Equal(t, 10.0, *panelSpec.Axes.X.Min)
assert.Nil(t, panelSpec.Axes.X.Max)
assert.Equal(t, "log", panelSpec.Axes.Y.Scale.ValueOrDefault())
assert.Equal(t, "none", panelSpec.Visualization.Stack.ValueOrDefault())
require.NotNil(t, panelSpec.ChartAppearance.Percentiles.Enabled)
assert.True(t, *panelSpec.ChartAppearance.Percentiles.Enabled)
assert.Equal(t, []float64{75, 99.9}, panelSpec.ChartAppearance.Percentiles.Values)
request, err := dashboard.GetPanelQuery(1, 2, "p1")
require.NoError(t, err, "building the panel's query failed")
assert.Equal(t, qb.RequestTypeDistribution, request.RequestType)
require.NoError(t, request.Validate(), "the request built from the panel is not a valid distribution request")
stored, err := json.Marshal(spec)
require.NoError(t, err, "marshal dashboard failed")
reread, err := unmarshalDashboard(stored)
require.NoError(t, err, "the stored dashboard does not validate")
assert.Equal(t, panelSpec, reread.Panels["p1"].Spec.Plugin.Spec)
}
func TestDistributionPanelSpecDefaults(t *testing.T) {
testCases := []struct {
name string
spec string
}{
{name: "EmptySpec", spec: `{}`},
{name: "EmptyVisualization", spec: `{"visualization": {}}`},
{name: "EmptyChartAppearance", spec: `{"chartAppearance": {}}`},
{name: "EmptyPercentiles", spec: `{"chartAppearance": {"percentiles": {}}}`},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
assert.Nil(t, spec.Axes.X.Min)
assert.Nil(t, spec.Axes.X.Max)
assert.Equal(t, "linear", spec.Axes.Y.Scale.ValueOrDefault())
assert.Nil(t, spec.ChartAppearance.Percentiles.Enabled)
assert.Nil(t, spec.ChartAppearance.Percentiles.Values)
storedVisualization, err := json.Marshal(spec.Visualization)
require.NoError(t, err)
assert.Contains(t, string(storedVisualization), `"stack":"normal"`)
stored, err := json.Marshal(spec.ChartAppearance)
require.NoError(t, err)
assert.Equal(t, `{"percentiles":{"enabled":true,"values":[50,90,99]}}`, string(stored))
})
}
}
func TestDistributionPanelSpecPercentileValues(t *testing.T) {
testCases := []struct {
name string
spec string
expectedPercentilesJSON string
}{
{name: "Disabled_ValuesDefaulted", spec: `{"chartAppearance": {"percentiles": {"enabled": false}}}`, expectedPercentilesJSON: `{"enabled":false,"values":[50,90,99]}`},
{name: "EmptyValues_MarksNone", spec: `{"chartAppearance": {"percentiles": {"values": []}}}`, expectedPercentilesJSON: `{"enabled":true,"values":[]}`},
{name: "NullValues_Defaulted", spec: `{"chartAppearance": {"percentiles": {"enabled": null, "values": null}}}`, expectedPercentilesJSON: `{"enabled":true,"values":[50,90,99]}`},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
stored, err := json.Marshal(spec.ChartAppearance.Percentiles)
require.NoError(t, err)
assert.Equal(t, testCase.expectedPercentilesJSON, string(stored))
})
}
}
func TestDistributionPanelSpecXMinEqualsMax(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": {"axes": {"x": {"min": 10, "max": 10}}}}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
require.NotNil(t, spec.Axes.X.Min)
require.NotNil(t, spec.Axes.X.Max)
assert.Equal(t, 10.0, *spec.Axes.X.Min)
assert.Equal(t, 10.0, *spec.Axes.X.Max)
}
func TestDistributionPanelSpecRejections(t *testing.T) {
testCases := []struct {
name string
spec string
expectedMessage string
}{
{
name: "XMin_AboveMax",
spec: `{"axes": {"x": {"min": 20, "max": 10}}}`,
expectedMessage: "axes.x.min 20 is greater than axes.x.max 10",
},
{
name: "YScale_Unknown",
spec: `{"axes": {"y": {"scale": "symlog"}}}`,
expectedMessage: "invalid distribution y scale",
},
{
name: "UnknownField",
spec: `{"axes": {"y": {"softMax": 10}}}`,
expectedMessage: "unknown field \"softMax\"",
},
{
name: "Percentile_Zero",
spec: `{"chartAppearance": {"percentiles": {"values": [0, 50]}}}`,
expectedMessage: "0 is not in (0, 100)",
},
{
name: "Percentile_Hundred",
spec: `{"chartAppearance": {"percentiles": {"values": [100]}}}`,
expectedMessage: "100 is not in (0, 100)",
},
{
name: "Percentile_Duplicate",
spec: `{"chartAppearance": {"percentiles": {"values": [90, 90]}}}`,
expectedMessage: "90 is listed more than once",
},
{
name: "Stack_Empty",
spec: `{"visualization": {"stack": ""}}`,
expectedMessage: "invalid stack mode",
},
{
name: "Percentiles_UnknownField",
spec: `{"chartAppearance": {"percentiles": {"show": true}}}`,
expectedMessage: "unknown field \"show\"",
},
{
name: "XAxis_UnknownField",
spec: `{"axes": {"x": {"softMin": 0}}}`,
expectedMessage: "unknown field \"softMin\"",
},
{
name: "Percentiles_MoreThanFive",
spec: `{"chartAppearance": {"percentiles": {"values": [10, 25, 50, 75, 90, 99]}}}`,
expectedMessage: "at most 5 percentiles",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
err := json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin)
require.Error(t, err)
assert.Contains(t, err.Error(), testCase.expectedMessage)
})
}
}
func TestDistributionPanelQueryKinds(t *testing.T) {
testCases := []struct {
name string
queryPluginKind string
queryPluginSpec string
expectedAllowed bool
}{
{
name: "PromQL_Allowed",
queryPluginKind: "signoz/PromQLQuery",
queryPluginSpec: `{"name": "A", "query": "sum by (le) (increase(signoz_latency_bucket[5m]))"}`,
expectedAllowed: true,
},
{
name: "ClickHouseSQL_Allowed",
queryPluginKind: "signoz/ClickHouseSQL",
queryPluginSpec: `{"name": "A", "query": "SELECT ts, bucket, value FROM cells"}`,
expectedAllowed: true,
},
{
name: "TraceOperator_Refused",
queryPluginKind: "signoz/TraceOperator",
queryPluginSpec: `{"name": "T1", "expression": "A => B"}`,
expectedAllowed: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
data := fmt.Sprintf(`{
"variables": [],
"panels": {
"p1": {
"kind": "Panel",
"spec": {
"links": [],
"plugin": {"kind": "signoz/DistributionPanel", "spec": {}},
"queries": [{
"kind": "distribution",
"spec": {
"plugin": {"kind": %q, "spec": %s}
}
}]
}
}
},
"links": [],
"layouts": []
}`, testCase.queryPluginKind, testCase.queryPluginSpec)
_, err := unmarshalDashboard([]byte(data))
if testCase.expectedAllowed {
require.NoError(t, err)
return
}
require.Error(t, err)
assert.Contains(t, err.Error(), "is not supported by panel kind")
})
}
}
func TestInvalidateOneInvalidPanel(t *testing.T) {
data := []byte(`{
"variables": [],

View File

@@ -28,19 +28,20 @@ type PanelPlugin struct {
// (and strips the duplicate parent properties) after reflection.
func (PanelPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
return markDiscriminator(s, "kind", map[string]string{
string(PanelKindTimeSeries): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec"),
string(PanelKindBarChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec"),
string(PanelKindAreaChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec"),
string(PanelKindNumber): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec"),
string(PanelKindPieChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec"),
string(PanelKindTable): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec"),
string(PanelKindHistogram): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec"),
string(PanelKindList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec"),
string(PanelKindText): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec"),
string(PanelKindHeatmap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec"),
string(PanelKindScatterPlot): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec"),
string(PanelKindGeoMap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec"),
string(PanelKindTopList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec"),
string(PanelKindTimeSeries): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec"),
string(PanelKindBarChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec"),
string(PanelKindAreaChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec"),
string(PanelKindNumber): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec"),
string(PanelKindPieChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec"),
string(PanelKindTable): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec"),
string(PanelKindHistogram): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec"),
string(PanelKindList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec"),
string(PanelKindText): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec"),
string(PanelKindHeatmap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec"),
string(PanelKindScatterPlot): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec"),
string(PanelKindGeoMap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec"),
string(PanelKindTopList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec"),
string(PanelKindDistribution): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec"),
})
}
@@ -77,6 +78,7 @@ func (PanelPlugin) JSONSchemaOneOf() []any {
PanelPluginVariant[ScatterPlotPanelSpec]{Kind: string(PanelKindScatterPlot)},
PanelPluginVariant[GeoMapPanelSpec]{Kind: string(PanelKindGeoMap)},
PanelPluginVariant[TopListPanelSpec]{Kind: string(PanelKindTopList)},
PanelPluginVariant[DistributionPanelSpec]{Kind: string(PanelKindDistribution)},
}
}
@@ -240,19 +242,20 @@ func (v VariablePluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error
var (
panelPluginSpecs = map[PanelPluginKind]func() any{
PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
PanelKindAreaChart: func() any { return new(AreaChartPanelSpec) },
PanelKindNumber: func() any { return new(NumberPanelSpec) },
PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
PanelKindTable: func() any { return new(TablePanelSpec) },
PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
PanelKindList: func() any { return new(ListPanelSpec) },
PanelKindText: func() any { return new(TextPanelSpec) },
PanelKindHeatmap: func() any { return new(HeatmapPanelSpec) },
PanelKindScatterPlot: func() any { return new(ScatterPlotPanelSpec) },
PanelKindGeoMap: func() any { return new(GeoMapPanelSpec) },
PanelKindTopList: func() any { return new(TopListPanelSpec) },
PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
PanelKindAreaChart: func() any { return new(AreaChartPanelSpec) },
PanelKindNumber: func() any { return new(NumberPanelSpec) },
PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
PanelKindTable: func() any { return new(TablePanelSpec) },
PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
PanelKindList: func() any { return new(ListPanelSpec) },
PanelKindText: func() any { return new(TextPanelSpec) },
PanelKindHeatmap: func() any { return new(HeatmapPanelSpec) },
PanelKindScatterPlot: func() any { return new(ScatterPlotPanelSpec) },
PanelKindGeoMap: func() any { return new(GeoMapPanelSpec) },
PanelKindTopList: func() any { return new(TopListPanelSpec) },
PanelKindDistribution: func() any { return new(DistributionPanelSpec) },
}
queryPluginSpecs = map[QueryPluginKind]func() any{
QueryKindBuilder: func() any { return new(BuilderQuerySpec) },
@@ -269,19 +272,20 @@ var (
VariableKindCustom: func() any { return new(CustomVariableSpec) },
}
allowedQueryKinds = map[PanelPluginKind][]QueryPluginKind{
PanelKindTimeSeries: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindBarChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindAreaChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindNumber: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindHistogram: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindPieChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindTable: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindList: {QueryKindBuilder, QueryKindAIBuilder},
PanelKindText: {},
PanelKindHeatmap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindScatterPlot: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindGeoMap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindTopList: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindTimeSeries: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindBarChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindAreaChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindNumber: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindHistogram: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindPieChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindTable: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindList: {QueryKindBuilder, QueryKindAIBuilder},
PanelKindText: {},
PanelKindHeatmap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindScatterPlot: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindGeoMap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindTopList: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindDistribution: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
}
)

View File

@@ -70,7 +70,7 @@ func (k *PanelKind) UnmarshalJSON(data []byte) error {
type PanelSpec struct {
Display Display `json:"display" required:"true" description:"The panel title and description."`
Plugin PanelPlugin `json:"plugin" required:"true" 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)."`
Plugin PanelPlugin `json:"plugin" required:"true" 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)."`
Queries []Query `json:"queries" required:"true" nullable:"false" 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, use one entry whose spec.plugin.kind is signoz/CompositeQuery and put the constituent queries in its plugin spec."`
Links []Link `json:"links,omitzero" description:"Context links offered in the data point drilldown menu of the panel, with dashboard variables resolved in the URL."`
}
@@ -92,13 +92,13 @@ type Link struct {
// ══════════════════════════════════════════════
type Query struct {
Kind qb.RequestType `json:"kind" required:"true" 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."`
Kind qb.RequestType `json:"kind" required:"true" 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."`
Spec QuerySpec `json:"spec" required:"true" description:"The query content: an optional name and the query plugin."`
}
type QuerySpec struct {
Name string `json:"name,omitempty" description:"An optional label for the query. The name queries refer to each other by lives in the plugin spec."`
Plugin QueryPlugin `json:"plugin" required:"true" 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."`
Plugin QueryPlugin `json:"plugin" required:"true" 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."`
}
// ══════════════════════════════════════════════

View File

@@ -16,6 +16,11 @@ import (
"github.com/swaggest/jsonschema-go"
)
const maxDistributionPercentiles = 5
// What an unset chartAppearance.percentiles.values is written as.
var defaultDistributionPercentiles = []float64{50, 90, 99}
// ══════════════════════════════════════════════
// SigNoz variable plugin specs
// ══════════════════════════════════════════════
@@ -190,23 +195,24 @@ func (AIBuilderQuerySpec) PrepareJSONSchema(s *jsonschema.Schema) error {
type PanelPluginKind string
const (
PanelKindTimeSeries PanelPluginKind = "signoz/TimeSeriesPanel"
PanelKindBarChart PanelPluginKind = "signoz/BarChartPanel"
PanelKindAreaChart PanelPluginKind = "signoz/AreaChartPanel"
PanelKindNumber PanelPluginKind = "signoz/NumberPanel"
PanelKindPieChart PanelPluginKind = "signoz/PieChartPanel"
PanelKindTable PanelPluginKind = "signoz/TablePanel"
PanelKindHistogram PanelPluginKind = "signoz/HistogramPanel"
PanelKindList PanelPluginKind = "signoz/ListPanel"
PanelKindText PanelPluginKind = "signoz/TextPanel"
PanelKindHeatmap PanelPluginKind = "signoz/HeatmapPanel"
PanelKindScatterPlot PanelPluginKind = "signoz/ScatterPlotPanel"
PanelKindGeoMap PanelPluginKind = "signoz/GeoMapPanel"
PanelKindTopList PanelPluginKind = "signoz/TopListPanel"
PanelKindTimeSeries PanelPluginKind = "signoz/TimeSeriesPanel"
PanelKindBarChart PanelPluginKind = "signoz/BarChartPanel"
PanelKindAreaChart PanelPluginKind = "signoz/AreaChartPanel"
PanelKindNumber PanelPluginKind = "signoz/NumberPanel"
PanelKindPieChart PanelPluginKind = "signoz/PieChartPanel"
PanelKindTable PanelPluginKind = "signoz/TablePanel"
PanelKindHistogram PanelPluginKind = "signoz/HistogramPanel"
PanelKindList PanelPluginKind = "signoz/ListPanel"
PanelKindText PanelPluginKind = "signoz/TextPanel"
PanelKindHeatmap PanelPluginKind = "signoz/HeatmapPanel"
PanelKindScatterPlot PanelPluginKind = "signoz/ScatterPlotPanel"
PanelKindGeoMap PanelPluginKind = "signoz/GeoMapPanel"
PanelKindTopList PanelPluginKind = "signoz/TopListPanel"
PanelKindDistribution PanelPluginKind = "signoz/DistributionPanel"
)
func (PanelPluginKind) Enum() []any {
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap, PanelKindTopList}
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap, PanelKindTopList, PanelKindDistribution}
}
func (k PanelPluginKind) rendersWithoutQuery() bool {
@@ -396,6 +402,99 @@ func (c HeatmapColors) validate() error {
return nil
}
type DistributionPanelSpec struct {
Visualization DistributionVisualization `json:"visualization" description:"The time range the bucket counts are summed over, and how groups stack."`
Formatting PanelFormatting `json:"formatting" description:"Unit and decimal precision of the bucket bounds; counts take no unit."`
Axes DistributionAxes `json:"axes" description:"The X (bucket) axis range and Y (count) axis scale."`
Legend Legend `json:"legend" description:"Legend placement and series colors."`
ChartAppearance DistributionChartAppearance `json:"chartAppearance" description:"Percentile markers."`
}
type DistributionAxes struct {
X DistributionXAxis `json:"x" description:"The bucket axis."`
Y DistributionYAxis `json:"y" description:"The count axis."`
}
// DistributionXAxis draws every bucket equally wide, whatever its bounds.
type DistributionXAxis struct {
Min *float64 `json:"min" description:"Buckets wholly below this value are hidden. Null shows them all."`
Max *float64 `json:"max" description:"Buckets wholly above this value are hidden. Null shows them all."`
}
func (axis *DistributionXAxis) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
type alias DistributionXAxis
var tmp alias
if err := dec.Decode(&tmp); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid axes.x")
}
*axis = DistributionXAxis(tmp)
return axis.validate()
}
func (axis DistributionXAxis) validate() error {
if axis.Min != nil && axis.Max != nil && *axis.Min > *axis.Max {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "axes.x.min %v is greater than axes.x.max %v", *axis.Min, *axis.Max)
}
return nil
}
type DistributionYAxis struct {
Scale DistributionYScale `json:"scale" required:"true" description:"How counts are spaced: linear (default) or log."`
}
type DistributionChartAppearance struct {
Percentiles DistributionPercentiles `json:"percentiles" description:"Percentile markers drawn across the bucket axis."`
}
type DistributionPercentiles struct {
Enabled *bool `json:"enabled" required:"true" nullable:"false" description:"Whether percentile markers are drawn. Defaults to true."`
Values []float64 `json:"values" required:"true" nullable:"false" description:"The percentiles to mark, each in (0, 100), at most 5, no duplicates. Defaults to [50, 90, 99]; [] marks none."`
}
// MarshalJSON writes the defaults for whatever was left unset.
func (percentiles DistributionPercentiles) MarshalJSON() ([]byte, error) {
type alias DistributionPercentiles
if percentiles.Enabled == nil {
enabled := true
percentiles.Enabled = &enabled
}
if percentiles.Values == nil {
percentiles.Values = slices.Clone(defaultDistributionPercentiles)
}
return json.Marshal(alias(percentiles))
}
func (percentiles *DistributionPercentiles) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
type alias DistributionPercentiles
var tmp alias
if err := dec.Decode(&tmp); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid chartAppearance.percentiles")
}
*percentiles = DistributionPercentiles(tmp)
return percentiles.validate()
}
func (percentiles DistributionPercentiles) validate() error {
if len(percentiles.Values) > maxDistributionPercentiles {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: at most %d percentiles, got %d", maxDistributionPercentiles, len(percentiles.Values))
}
seen := make(map[float64]struct{}, len(percentiles.Values))
for _, value := range percentiles.Values {
if value <= 0 || value >= 100 {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: %v is not in (0, 100)", value)
}
if _, ok := seen[value]; ok {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: %v is listed more than once", value)
}
seen[value] = struct{}{}
}
return nil
}
type TextPanelSpec struct {
Mode TextMode `json:"mode" description:"How text is interpreted. Only markdown is supported."`
Text string `json:"text" description:"The content to render."`
@@ -713,6 +812,20 @@ type BarChartVisualization struct {
StackedBarChart bool `json:"stackedBarChart" description:"Whether the series are stacked on top of each other."`
}
type DistributionVisualization struct {
BasicVisualization
Stack StackMode `json:"stack" required:"true" 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."`
}
// MarshalJSON writes Distribution's own stack default, normal, where StackMode's is none.
func (visualization DistributionVisualization) MarshalJSON() ([]byte, error) {
type alias DistributionVisualization
if visualization.Stack.IsZero() {
visualization.Stack = StackModeNormal
}
return json.Marshal(alias(visualization))
}
type AreaChartVisualization struct {
BasicVisualization
FillSpans bool `json:"fillSpans" description:"Whether intervals with no data are drawn as zero instead of a gap."`
@@ -1683,6 +1796,43 @@ func (s *HeatmapYScale) UnmarshalJSON(data []byte) error {
}
}
type DistributionYScale struct{ valuer.String }
var (
DistributionYScaleLinear = DistributionYScale{valuer.NewString("linear")} // default
DistributionYScaleLog = DistributionYScale{valuer.NewString("log")}
)
func (DistributionYScale) Enum() []any {
return []any{DistributionYScaleLinear, DistributionYScaleLog}
}
func (scale DistributionYScale) ValueOrDefault() string {
if scale.IsZero() {
return DistributionYScaleLinear.StringValue()
}
return scale.StringValue()
}
func (scale DistributionYScale) MarshalJSON() ([]byte, error) {
return json.Marshal(scale.ValueOrDefault())
}
func (scale *DistributionYScale) UnmarshalJSON(data []byte) error {
var v string
if err := json.Unmarshal(data, &v); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid distribution y scale: must be a string, one of `linear` or `log`")
}
parsed := DistributionYScale{valuer.NewString(v)}
switch parsed {
case DistributionYScaleLinear, DistributionYScaleLog:
*scale = parsed
return nil
default:
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid distribution y scale %q: must be `linear` or `log`", v)
}
}
type HeatmapColorScale struct{ valuer.String }
var (

View File

@@ -0,0 +1,95 @@
{
"display": {
"name": "latency",
"description": "how request duration is distributed over the range"
},
"variables": [],
"panels": {
"p1": {
"kind": "Panel",
"spec": {
"display": {
"name": "request duration",
"description": ""
},
"plugin": {
"kind": "signoz/DistributionPanel",
"spec": {
"visualization": {
"timePreference": "global_time",
"stack": "none"
},
"formatting": {
"unit": "s",
"decimalPrecision": "3"
},
"axes": {
"x": {
"min": 10
},
"y": {
"scale": "log"
}
},
"legend": {
"position": "right",
"mode": "list"
},
"chartAppearance": {
"percentiles": {
"enabled": true,
"values": [75, 99.9]
}
}
}
},
"links": [],
"queries": [
{
"kind": "distribution",
"spec": {
"plugin": {
"kind": "signoz/BuilderQuery",
"spec": {
"name": "A",
"signal": "metrics",
"aggregations": [
{
"metricName": "http.server.request.duration",
"timeAggregation": "increase",
"spaceAggregation": "sum"
}
],
"groupBy": [
{
"name": "service.name"
}
]
}
}
}
}
]
}
}
},
"links": [],
"layouts": [
{
"kind": "Grid",
"spec": {
"items": [
{
"x": 0,
"y": 0,
"width": 12,
"height": 8,
"content": {
"$ref": "#/spec/panels/p1"
}
}
]
}
}
]
}