SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat: added custom stepIntervals to bar chart for better visibilty (#8023)
SagarRajput-7fb1f320346ea
diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsxindex e8e9b484a2..89a1fa5105 100644--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx@@ -142,6 +142,7 @@ function ChartPreview({params: {allowSelectedIntervalForStepGen,},+ originalGraphType: graphType,},alertDef?.version || DEFAULT_ENTITY_VERSION,{diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsxindex 9a87c228c0..dd91469d63 100644--- a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx@@ -94,6 +94,7 @@ function FullView({variables: getDashboardVariables(selectedDashboard?.data.variables),fillGaps: widget.fillSpans,formatForWeb: widget.panelTypes === PANEL_TYPES.TABLE,+ originalGraphType: widget?.panelTypes,};}updatedQuery.builder.queryData[0].pageSize = 10;diff --git a/frontend/src/container/GridCardLayout/GridCard/index.tsx b/frontend/src/container/GridCardLayout/GridCard/index.tsxindex c29050ca6b..a9d58a13bc 100644--- a/frontend/src/container/GridCardLayout/GridCard/index.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/index.tsx@@ -208,6 +208,7 @@ function GridCardGraph({: globalSelectedInterval,start: customTimeRange?.startTime || start,end: customTimeRange?.endTime || end,+ originalGraphType: widget?.panelTypes,},version || DEFAULT_ENTITY_VERSION,{diff --git a/frontend/src/container/GridCardLayout/__tests__/utils.test.ts b/frontend/src/container/GridCardLayout/__tests__/utils.test.tsnew file mode 100644index 0000000000..84904064f5--- /dev/null+++ b/frontend/src/container/GridCardLayout/__tests__/utils.test.ts@@ -0,0 +1,228 @@+import { Query } from 'types/api/queryBuilder/queryBuilderData';+import { EQueryType } from 'types/common/dashboard';+import { DataSource } from 'types/common/queryBuilder';++import { getStepIntervalPoints, updateStepInterval } from '../utils';++describe('GridCardLayout Utils', () => {+ describe('getStepIntervalPoints', () => {+ it('should return 60 points for duration <= 1 hour', () => {+ // 30 minutes in milliseconds+ const start = Date.now();+ const end = start + 30 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(60);+ });++ it('should return 60 points for exactly 1 hour', () => {+ // 1 hour in milliseconds+ const start = Date.now();+ const end = start + 60 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(60);+ });++ it('should return 120 points for duration <= 3 hours', () => {+ // 2 hours in milliseconds+ const start = Date.now();+ const end = start + 2 * 60 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(120);+ });++ it('should return 120 points for exactly 3 hours', () => {+ // 3 hours in milliseconds+ const start = Date.now();+ const end = start + 3 * 60 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(120);+ });++ it('should return 180 points for duration <= 5 hours', () => {+ // 4 hours in milliseconds+ const start = Date.now();+ const end = start + 4 * 60 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(180);+ });++ it('should return 180 points for exactly 5 hours', () => {+ // 5 hours in milliseconds+ const start = Date.now();+ const end = start + 5 * 60 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(180);+ });++ it('should calculate dynamic interval for duration > 5 hours', () => {+ // 10 hours in milliseconds+ const start = Date.now();+ const end = start + 10 * 60 * 60 * 1000;++ const result = getStepIntervalPoints(start, end);++ // For 10 hours (600 minutes), interval should be ceil(600/80) = 8, rounded to 10, then * 60 = 600+ expect(result).toBe(600);+ });++ it('should handle very long durations correctly', () => {+ // 7 days in milliseconds+ const start = Date.now();+ const end = start + 7 * 24 * 60 * 60 * 1000;++ const result = getStepIntervalPoints(start, end);++ // For 7 days (10080 minutes), interval should be ceil(10080/80) = 126, rounded to 130, then * 60 = 7800+ expect(result).toBe(7800);+ });++ it('should round up to nearest multiple of 5 minutes', () => {+ // 12 hours in milliseconds+ const start = Date.now();+ const end = start + 12 * 60 * 60 * 1000;++ const result = getStepIntervalPoints(start, end);++ // For 12 hours (720 minutes), interval should be ceil(720/80) = 9, rounded to 10, then * 60 = 600+ expect(result).toBe(600);+ });++ it('should handle edge case with very small duration', () => {+ // 1 minute in milliseconds+ const start = Date.now();+ const end = start + 1 * 60 * 1000;++ expect(getStepIntervalPoints(start, end)).toBe(60);+ });++ it('should handle zero duration', () => {+ const start = Date.now();+ const end = start;++ expect(getStepIntervalPoints(start, end)).toBe(60);+ });+ });++ describe('updateStepInterval', () => {+ const mockQuery: Query = {+ queryType: EQueryType.QUERY_BUILDER,+ builder: {+ queryData: [+ {+ stepInterval: 30,+ aggregateOperator: 'avg',+ dataSource: DataSource.METRICS,+ queryName: 'A',+ aggregateAttribute: { key: 'cpu_usage', type: 'Gauge' },+ timeAggregation: 'avg',+ spaceAggregation: 'avg',+ functions: [],+ filters: { items: [], op: 'AND' },+ expression: 'A',+ disabled: false,+ having: [],+ groupBy: [],+ orderBy: [],+ limit: null,+ offset: 0,+ pageSize: 0,+ reduceTo: 'avg',+ legend: '',+ },+ ],+ queryFormulas: [],+ },+ clickhouse_sql: [],+ promql: [],+ id: 'test-query',+ };++ it('should update stepInterval based on time range', () => {+ // 2 hours duration+ const minTime = Date.now();+ const maxTime = minTime + 2 * 60 * 60 * 1000;++ const result = updateStepInterval(mockQuery, minTime, maxTime);++ expect(result.builder.queryData[0].stepInterval).toBe(120);+ });++ it('should preserve other query properties', () => {+ const minTime = Date.now();+ const maxTime = minTime + 1 * 60 * 60 * 1000;++ const result = updateStepInterval(mockQuery, minTime, maxTime);++ expect(result.builder.queryData[0].aggregateOperator).toBe('avg');+ expect(result.builder.queryData[0].queryName).toBe('A');+ expect(result.builder.queryData[0].dataSource).toBe('metrics');+ });++ it('should handle multiple queryData items', () => {+ const multiQueryMock: Query = {+ ...mockQuery,+ builder: {+ queryData: [+ ...mockQuery.builder.queryData,+ {+ ...mockQuery.builder.queryData[0],+ queryName: 'B',+ stepInterval: 45,+ },+ ],+ queryFormulas: [],+ },+ };++ const minTime = Date.now();+ const maxTime = minTime + 4 * 60 * 60 * 1000;++ const result = updateStepInterval(multiQueryMock, minTime, maxTime);++ expect(result.builder.queryData).toHaveLength(2);+ expect(result.builder.queryData[0].stepInterval).toBe(180);+ expect(result.builder.queryData[1].stepInterval).toBe(180);+ });++ it('should use calculated stepInterval when original is undefined', () => {+ const queryWithUndefinedStep: Query = {+ ...mockQuery,+ builder: {+ queryData: [+ {+ ...mockQuery.builder.queryData[0],+ stepInterval: undefined as any,+ },+ ],+ queryFormulas: [],+ },+ };++ const minTime = Date.now();+ const maxTime = minTime + 1 * 60 * 60 * 1000;++ const result = updateStepInterval(queryWithUndefinedStep, minTime, maxTime);++ expect(result.builder.queryData[0].stepInterval).toBe(60);+ });++ it('should fallback to 60 when calculated stepInterval is 0', () => {+ const minTime = Date.now();+ const maxTime = minTime; // Same time = 0 duration++ const result = updateStepInterval(mockQuery, minTime, maxTime);++ expect(result.builder.queryData[0].stepInterval).toBe(60);+ });++ it('should handle very large time ranges', () => {+ const minTime = Date.now();+ const maxTime = minTime + 30 * 24 * 60 * 60 * 1000; // 30 days++ const result = updateStepInterval(mockQuery, minTime, maxTime);++ // Should calculate appropriate interval for 30 days+ expect(result.builder.queryData[0].stepInterval).toBeGreaterThan(180);+ });+ });+});diff --git a/frontend/src/container/GridCardLayout/utils.ts b/frontend/src/container/GridCardLayout/utils.tsindex 72026a3c49..f22c9e819e 100644--- a/frontend/src/container/GridCardLayout/utils.ts+++ b/frontend/src/container/GridCardLayout/utils.ts@@ -2,6 +2,7 @@ import { FORMULA_REGEXP } from 'constants/regExp';import { isEmpty, isEqual } from 'lodash-es';import { Layout } from 'react-grid-layout';import { Dashboard, Widgets } from 'types/api/dashboard/getAll';+import { Query } from 'types/api/queryBuilder/queryBuilderData';export const removeUndefinedValuesFromLayout = (layout: Layout[]): Layout[] =>layout.map((obj) =>@@ -51,3 +52,63 @@ export const hasColumnWidthsChanged = (return !isEqual(newWidths, existingWidths);});};++/**+ * Calculates the step interval in uPlot points (1 minute = 60 points)+ * based on the time duration between two timestamps in nanoseconds.+ *+ * Conversion logic:+ * - <= 1 hr → 1 min (60 points)+ * - <= 3 hr → 2 min (120 points)+ * - <= 5 hr → 3 min (180 points)+ * - > 5 hr → max 80 bars, ceil((end-start)/80), rounded to nearest multiple of 5 min+ *+ * @param startNano - start time in nanoseconds+ * @param endNano - end time in nanoseconds+ * @returns stepInterval in uPlot points+ */+export function getStepIntervalPoints(+ startNano: number,+ endNano: number,+): number {+ const startMs = startNano;+ const endMs = endNano;+ const durationMs = endMs - startMs;+ const durationMin = durationMs / (60 * 1000); // convert to minutes++ if (durationMin <= 60) {+ return 60; // 1 min+ }+ if (durationMin <= 180) {+ return 120; // 2 min+ }+ if (durationMin <= 300) {+ return 180; // 3 min+ }++ const totalPoints = Math.ceil(durationMs / (1000 * 60)); // total minutes+ const interval = Math.ceil(totalPoints / 80); // at most 80 bars+ const roundedInterval = Math.ceil(interval / 5) * 5; // round up to nearest 5+ return roundedInterval * 60; // convert min to points+}++export function updateStepInterval(+ query: Query,+ minTime: number,+ maxTime: number,+): Query {+ const stepIntervalPoints = getStepIntervalPoints(minTime, maxTime);++ return {+ ...query,+ builder: {+ ...query.builder,+ queryData: [+ ...query.builder.queryData.map((queryData) => ({+ ...queryData,+ stepInterval: stepIntervalPoints || queryData.stepInterval || 60,+ })),+ ],+ },+ };+}diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsxindex 9c4c809971..fc337081d0 100644--- a/frontend/src/container/NewWidget/index.tsx+++ b/frontend/src/container/NewWidget/index.tsx@@ -361,6 +361,7 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {getGraphTypeForFormat(selectedGraph || selectedWidget.panelTypes) ===PANEL_TYPES.TABLE,variables: getDashboardVariables(selectedDashboard?.data.variables),+ originalGraphType: selectedGraph || selectedWidget?.panelTypes,};}diff --git a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetQueryRange.tsindex 172c5c0580..b3941bc2de 100644--- a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts+++ b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts@@ -1,9 +1,11 @@import { PANEL_TYPES } from 'constants/queryBuilder';import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';+import { updateStepInterval } from 'container/GridCardLayout/utils';import {GetMetricQueryRange,GetQueryResultsProps,} from 'lib/dashboard/getQueryResults';+import getStartEndRangeTime from 'lib/getStartEndRangeTime';import { useMemo } from 'react';import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';import { SuccessResponse } from 'types/api';@@ -75,9 +77,32 @@ export const useGetQueryRange: UseGetQueryRange = (return [REACT_QUERY_KEY.GET_QUERY_RANGE, newRequestData];}, [options?.queryKey, newRequestData]);+ const modifiedRequestData = useMemo(() => {+ const graphType = requestData.originalGraphType || requestData.graphType;+ if (graphType === PANEL_TYPES.BAR) {+ const { start, end } = getStartEndRangeTime({+ type: requestData.selectedTime,+ interval: requestData.globalSelectedInterval,+ });++ const updatedQuery = updateStepInterval(+ requestData.query,+ requestData.start ? requestData.start * 1e3 : parseInt(start, 10) * 1e3,+ requestData.end ? requestData.end * 1e3 : parseInt(end, 10) * 1e3,+ );++ return {+ ...requestData,+ query: updatedQuery,+ };+ }++ return requestData;+ }, [requestData]);+return useQuery<SuccessResponse<MetricRangePayloadProps>, Error>({queryFn: async ({ signal }) =>- GetMetricQueryRange(requestData, version, signal, headers),+ GetMetricQueryRange(modifiedRequestData, version, signal, headers),...options,queryKey,});diff --git a/frontend/src/lib/dashboard/getQueryResults.ts b/frontend/src/lib/dashboard/getQueryResults.tsindex fb0324ba57..30c6e611dc 100644--- a/frontend/src/lib/dashboard/getQueryResults.ts+++ b/frontend/src/lib/dashboard/getQueryResults.ts@@ -103,4 +103,5 @@ export interface GetQueryResultsProps {start?: number;end?: number;step?: number;+ originalGraphType?: PANEL_TYPES;}