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
fix: thresholds working correctly with number panel (#10394)
Abhi kumarf9868e22210c
diff --git a/frontend/src/components/ValueGraph/index.tsx b/frontend/src/components/ValueGraph/index.tsxindex 5c31cfb3f9..5570b7a328 100644--- a/frontend/src/components/ValueGraph/index.tsx+++ b/frontend/src/components/ValueGraph/index.tsx@@ -40,6 +40,7 @@ function ValueGraph({value,rawValue,thresholds,+ yAxisUnit,}: ValueGraphProps): JSX.Element {const { t } = useTranslation(['valueGraph']);const containerRef = useRef<HTMLDivElement>(null);@@ -87,7 +88,7 @@ function ValueGraph({const {threshold,isConflictingThresholds,- } = getBackgroundColorAndThresholdCheck(thresholds, rawValue);+ } = getBackgroundColorAndThresholdCheck(thresholds, rawValue, yAxisUnit);return (<div@@ -155,6 +156,7 @@ interface ValueGraphProps {value: string;rawValue: number;thresholds: ThresholdProps[];+ yAxisUnit?: string;}export default ValueGraph;diff --git a/frontend/src/components/ValueGraph/utils.ts b/frontend/src/components/ValueGraph/utils.tsindex 189d22518d..ca7087dd07 100644--- a/frontend/src/components/ValueGraph/utils.ts+++ b/frontend/src/components/ValueGraph/utils.ts@@ -1,9 +1,10 @@-import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';+import { evaluateThresholdWithConvertedValue } from 'container/GridTableComponent/utils';import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';-function compareThreshold(+function doesValueSatisfyThreshold(rawValue: number,threshold: ThresholdProps,+ yAxisUnit?: string,): boolean {if (threshold.thresholdOperator === undefined ||@@ -11,31 +12,14 @@ function compareThreshold() {return false;}- switch (threshold.thresholdOperator) {- case '>':- return rawValue > threshold.thresholdValue;- case '>=':- return rawValue >= threshold.thresholdValue;- case '<':- return rawValue < threshold.thresholdValue;- case '<=':- return rawValue <= threshold.thresholdValue;- case '=':- return rawValue === threshold.thresholdValue;- default:- return false;- }-}--function extractNumbersFromString(inputString: string): number[] {- const regex = /[+-]?\d+(\.\d+)?/g;- const matches = inputString.match(regex);- if (matches) {- return matches.map(Number);- }-- return [];+ return evaluateThresholdWithConvertedValue(+ rawValue,+ threshold.thresholdValue,+ threshold.thresholdOperator,+ threshold.thresholdUnit,+ yAxisUnit,+ );}function getHighestPrecedenceThreshold(@@ -60,21 +44,32 @@ function getHighestPrecedenceThreshold(return highestPrecedenceThreshold;}+function extractNumbersFromString(inputString: string): number[] {+ const regex = /[+-]?\d+(\.\d+)?/g;+ const matches = inputString.match(regex);++ if (matches) {+ return matches.map(Number);+ }++ return [];+}+export function getBackgroundColorAndThresholdCheck(thresholds: ThresholdProps[],rawValue: number,+ yAxisUnit?: string,): {threshold: ThresholdProps;isConflictingThresholds: boolean;} {- const matchingThresholds = thresholds.filter((threshold) =>- compareThreshold(- extractNumbersFromString(- getYAxisFormattedValue(rawValue.toString(), threshold.thresholdUnit || ''),- )[0],- threshold,- ),- );+ const matchingThresholds = thresholds.filter((threshold) => {+ const numbers = extractNumbersFromString(rawValue.toString());+ if (numbers.length === 0) {+ return false;+ }+ return doesValueSatisfyThreshold(numbers[0], threshold, yAxisUnit);+ });if (matchingThresholds.length === 0) {return {diff --git a/frontend/src/components/YAxisUnitSelector/YAxisUnitSelector.tsx b/frontend/src/components/YAxisUnitSelector/YAxisUnitSelector.tsxindex 4857b98867..25ebb34ef8 100644--- a/frontend/src/components/YAxisUnitSelector/YAxisUnitSelector.tsx+++ b/frontend/src/components/YAxisUnitSelector/YAxisUnitSelector.tsx@@ -22,6 +22,8 @@ function YAxisUnitSelector({'data-testid': dataTestId,source,initialValue,+ categoriesOverride,+ containerClassName,}: YAxisUnitSelectorProps): JSX.Element {const universalUnit = mapMetricUnitToUniversalUnit(value);@@ -66,10 +68,14 @@ function YAxisUnitSelector({return aliases.some((alias) => alias.toLowerCase().includes(search));};- const categories = getYAxisCategories(source);+ const categoriesToRender = useMemo(() => {+ return categoriesOverride || getYAxisCategories(source);+ }, [categoriesOverride, source]);return (- <div className="y-axis-unit-selector-component">+ <div+ className={classNames('y-axis-unit-selector-component', containerClassName)}+ ><SelectshowSearchvalue={universalUnit}@@ -90,7 +96,7 @@ function YAxisUnitSelector({data-testid={dataTestId}allowClear>- {categories.map((category) => (+ {categoriesToRender.map((category) => (<Select.OptGroup key={category.name} label={category.name}>{category.units.map((unit) => (<Select.Option key={unit.id} value={unit.id}>diff --git a/frontend/src/components/YAxisUnitSelector/__tests__/YAxisUnitSelector.test.tsx b/frontend/src/components/YAxisUnitSelector/__tests__/YAxisUnitSelector.test.tsxindex 4ac1c615b4..09af319af6 100644--- a/frontend/src/components/YAxisUnitSelector/__tests__/YAxisUnitSelector.test.tsx+++ b/frontend/src/components/YAxisUnitSelector/__tests__/YAxisUnitSelector.test.tsx@@ -1,6 +1,7 @@import { fireEvent, render, screen } from '@testing-library/react';-import { YAxisSource } from '../types';+import { YAxisCategoryNames } from '../constants';+import { UniversalYAxisUnit, YAxisSource } from '../types';import YAxisUnitSelector from '../YAxisUnitSelector';describe('YAxisUnitSelector', () => {@@ -123,4 +124,34 @@ describe('YAxisUnitSelector', () => {const warningIcon = screen.queryByLabelText('warning');expect(warningIcon).not.toBeInTheDocument();});++ it('uses categories override to render custom units', () => {+ const customCategories = [+ {+ name: YAxisCategoryNames.Data,+ units: [+ {+ id: UniversalYAxisUnit.BYTES,+ name: 'Custom Bytes (B)',+ },+ ],+ },+ ];++ render(+ <YAxisUnitSelector+ value=""+ onChange={mockOnChange}+ source={YAxisSource.ALERTS}+ categoriesOverride={customCategories}+ />,+ );++ const select = screen.getByRole('combobox');++ fireEvent.mouseDown(select);++ expect(screen.getByText('Custom Bytes (B)')).toBeInTheDocument();+ expect(screen.queryByText('Bytes (B)')).not.toBeInTheDocument();+ });});diff --git a/frontend/src/components/YAxisUnitSelector/types.ts b/frontend/src/components/YAxisUnitSelector/types.tsindex 94c5397c4c..54085bf798 100644--- a/frontend/src/components/YAxisUnitSelector/types.ts+++ b/frontend/src/components/YAxisUnitSelector/types.ts@@ -9,6 +9,8 @@ export interface YAxisUnitSelectorProps {'data-testid'?: string;source: YAxisSource;initialValue?: string;+ categoriesOverride?: YAxisCategory[];+ containerClassName?: string;}export enum UniversalYAxisUnit {diff --git a/frontend/src/container/GridTableComponent/utils.ts b/frontend/src/container/GridTableComponent/utils.tsindex 97a907bc04..4ebed34e1f 100644--- a/frontend/src/container/GridTableComponent/utils.ts+++ b/frontend/src/container/GridTableComponent/utils.ts@@ -49,7 +49,7 @@ function evaluateCondition(* @param columnUnit - The current unit of the value.* @returns A boolean indicating whether the value meets the threshold condition.*/-function evaluateThresholdWithConvertedValue(+export function evaluateThresholdWithConvertedValue(value: number,thresholdValue: number,thresholdOperator?: string,diff --git a/frontend/src/container/GridValueComponent/index.tsx b/frontend/src/container/GridValueComponent/index.tsxindex 64683d0dc8..f4819cc610 100644--- a/frontend/src/container/GridValueComponent/index.tsx+++ b/frontend/src/container/GridValueComponent/index.tsx@@ -99,6 +99,7 @@ function GridValueComponent({<ValueGraphthresholds={thresholds || []}rawValue={value}+ yAxisUnit={yAxisUnit}value={yAxisUnit? getYAxisFormattedValue(diff --git a/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.styles.scss b/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.styles.scssindex 15b3d05f4e..00c4cb115f 100644--- a/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.styles.scss+++ b/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.styles.scss@@ -169,6 +169,10 @@font-weight: 400;line-height: 16px; /* 133.333% */+ .ant-select {+ width: 100%;+ }+.ant-select-selector {border: none;height: unset;diff --git a/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.tsx b/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.tsxindex 0ff8273058..068838f5c8 100644--- a/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.tsx+++ b/frontend/src/container/NewWidget/RightContainer/Threshold/Threshold.tsx@@ -2,6 +2,9 @@import { useMemo, useRef, useState } from 'react';import { useDrag, useDrop, XYCoord } from 'react-dnd';import { Button, Input, InputNumber, Select, Space, Typography } from 'antd';+import YAxisUnitSelector from 'components/YAxisUnitSelector';+import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';+import { YAxisSource } from 'components/YAxisUnitSelector/types';import { PANEL_TYPES } from 'constants/queryBuilder';import { unitOptions } from 'container/NewWidget/utils';import { useIsDarkMode } from 'hooks/useDarkMode';@@ -204,6 +207,18 @@ function Threshold({return unit !== 'none' && convertUnit(value, unit, toUnitId) === null;}, [selectedGraph, yAxisUnit, tableSelectedOption, columnUnits, unit, value]);+ const unitSelectCategories = useMemo(() => {+ return unitOptions(+ selectedGraph === PANEL_TYPES.TABLE+ ? getColumnUnit(tableSelectedOption, columnUnits || {}) || ''+ : yAxisUnit || '',+ );+ }, [selectedGraph, yAxisUnit, tableSelectedOption, columnUnits]);++ const unitLabel = useMemo(() => {+ return Y_AXIS_UNIT_NAMES[unit as keyof typeof Y_AXIS_UNIT_NAMES];+ }, [unit]);+return (<divref={allowDragAndDrop ? ref : null}@@ -313,19 +328,17 @@ function Threshold({<ShowCaseValue value={value} className="unit-input" />)}{isEditMode ? (- <Select- defaultValue={unit}- options={unitOptions(- selectedGraph === PANEL_TYPES.TABLE- ? getColumnUnit(tableSelectedOption, columnUnits || {}) || ''- : yAxisUnit || '',- )}+ <YAxisUnitSelector+ value={unit}onChange={handleUnitChange}- showSearch- className="unit-selection"+ placeholder="Select unit"+ source={YAxisSource.DASHBOARDS}+ initialValue={unit}+ categoriesOverride={unitSelectCategories}+ containerClassName="unit-selection"/>) : (- <ShowCaseValue value={unit} className="unit-selection-prev" />+ <ShowCaseValue value={unitLabel} className="unit-selection-prev" />)}</div><div className="thresholds-color-selector">@@ -356,7 +369,10 @@ function Threshold({)}</div>{isInvalidUnitComparison && (- <Typography.Text className="invalid-unit">+ <Typography.Text+ className="invalid-unit"+ data-testid="invalid-unit-comparison"+ >Threshold unit ({unit}) is not valid in comparison with the{' '}{selectedGraph === PANEL_TYPES.TABLE ? 'column' : 'y-axis'} unit ({selectedGraph === PANEL_TYPES.TABLEdiff --git a/frontend/src/container/NewWidget/RightContainer/Threshold/__tests__/Threshold.test.tsx b/frontend/src/container/NewWidget/RightContainer/Threshold/__tests__/Threshold.test.tsxindex 0b79669250..65d9bb5e02 100644--- a/frontend/src/container/NewWidget/RightContainer/Threshold/__tests__/Threshold.test.tsx+++ b/frontend/src/container/NewWidget/RightContainer/Threshold/__tests__/Threshold.test.tsx@@ -1,6 +1,8 @@/* eslint-disable react/jsx-props-no-spreading */import { DndProvider } from 'react-dnd';import { HTML5Backend } from 'react-dnd-html5-backend';+import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';+import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';import { PANEL_TYPES } from 'constants/queryBuilder';import { render, screen } from 'tests/test-utils';@@ -14,12 +16,26 @@ jest.mock('lib/query/createTableColumnsFromQuery', () => ({),}));-// Mock the unitOptions function+// Mock the unitOptions function to return YAxisCategory-shaped datajest.mock('container/NewWidget/utils', () => ({unitOptions: jest.fn(() => [- { value: 'none', label: 'None' },- { value: '%', label: 'Percent (0 - 100)' },- { value: 'ms', label: 'Milliseconds (ms)' },+ {+ name: 'Mock Category',+ units: [+ {+ id: UniversalYAxisUnit.NONE,+ name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.NONE],+ },+ {+ id: UniversalYAxisUnit.PERCENT,+ name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.PERCENT],+ },+ {+ id: UniversalYAxisUnit.MILLISECONDS,+ name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MILLISECONDS],+ },+ ],+ },]),}));@@ -28,7 +44,7 @@ const defaultProps = {keyIndex: 0,thresholdOperator: '>' as const,thresholdValue: 50,- thresholdUnit: 'none',+ thresholdUnit: UniversalYAxisUnit.NONE,thresholdColor: 'Red',thresholdFormat: 'Text' as const,isEditEnabled: true,@@ -38,8 +54,11 @@ const defaultProps = {{ value: 'memory_usage', label: 'Memory Usage' },],thresholdTableOptions: 'cpu_usage',- columnUnits: { cpu_usage: 'percent', memory_usage: 'bytes' },- yAxisUnit: '%',+ columnUnits: {+ cpu_usage: UniversalYAxisUnit.PERCENT,+ memory_usage: UniversalYAxisUnit.BYTES,+ },+ yAxisUnit: UniversalYAxisUnit.PERCENT,moveThreshold: jest.fn(),};@@ -68,28 +87,27 @@ describe('Threshold Component Unit Validation', () => {it('should show validation error when threshold unit is not "none" and units are incompatible', () => {// Act - Render component with incompatible units (ms vs percent)renderThreshold({- thresholdUnit: 'ms',+ thresholdUnit: UniversalYAxisUnit.MILLISECONDS,thresholdValue: 50,});+ const errorMessage = screen.getByTestId('invalid-unit-comparison');// Assert - Validation error should be displayed- expect(- screen.getByText(- /Threshold unit \(ms\) is not valid in comparison with the column unit \(percent\)/i,- ),- ).toBeInTheDocument();+ expect(errorMessage.textContent).toBe(+ `Threshold unit (${UniversalYAxisUnit.MILLISECONDS}) is not valid in comparison with the column unit (${UniversalYAxisUnit.PERCENT})`,+ );});it('should not show validation error when threshold unit matches column unit', () => {// Act - Render component with matching unitsrenderThreshold({- thresholdUnit: 'percent',+ thresholdUnit: UniversalYAxisUnit.PERCENT,thresholdValue: 50,});// Assert - No validation error should be displayedexpect(- screen.queryByText(/Threshold unit.*is not valid in comparison/i),+ screen.queryByTestId('invalid-unit-comparison'),).not.toBeInTheDocument();});@@ -97,17 +115,16 @@ describe('Threshold Component Unit Validation', () => {// Act - Render component for time series with incompatible unitsrenderThreshold({selectedGraph: PANEL_TYPES.TIME_SERIES,- thresholdUnit: 'ms',+ thresholdUnit: UniversalYAxisUnit.MILLISECONDS,thresholdValue: 100,- yAxisUnit: 'percent',+ yAxisUnit: UniversalYAxisUnit.PERCENT,});+ const errorMessage = screen.getByTestId('invalid-unit-comparison');// Assert - Validation error should be displayed- expect(- screen.getByText(- /Threshold unit \(ms\) is not valid in comparison with the y-axis unit \(percent\)/i,- ),- ).toBeInTheDocument();+ expect(errorMessage.textContent).toBe(+ `Threshold unit (${UniversalYAxisUnit.MILLISECONDS}) is not valid in comparison with the y-axis unit (${UniversalYAxisUnit.PERCENT})`,+ );});it('should not show validation error for time series graph when threshold unit is "none"', () => {@@ -116,43 +133,39 @@ describe('Threshold Component Unit Validation', () => {selectedGraph: PANEL_TYPES.TIME_SERIES,thresholdUnit: 'none',thresholdValue: 100,- yAxisUnit: 'percent',+ yAxisUnit: UniversalYAxisUnit.PERCENT,});-- // Assert - No validation error should be displayedexpect(- screen.queryByText(/Threshold unit.*is not valid in comparison/i),+ screen.queryByTestId('invalid-unit-comparison'),).not.toBeInTheDocument();});it('should not show validation error when threshold unit is compatible with column unit', () => {// Act - Render component with compatible units (both in same category - Time)renderThreshold({- thresholdUnit: 's',+ thresholdUnit: UniversalYAxisUnit.SECONDS,thresholdValue: 100,- columnUnits: { cpu_usage: 'ms' },+ columnUnits: { cpu_usage: UniversalYAxisUnit.MILLISECONDS },thresholdTableOptions: 'cpu_usage',});-// Assert - No validation error should be displayedexpect(- screen.queryByText(/Threshold unit.*is not valid in comparison/i),+ screen.queryByTestId('invalid-unit-comparison'),).not.toBeInTheDocument();});it('should show validation error when threshold unit is in different category than column unit', () => {// Act - Render component with units from different categoriesrenderThreshold({- thresholdUnit: 'bytes',+ thresholdUnit: UniversalYAxisUnit.BYTES,thresholdValue: 100,- yAxisUnit: 'percent',+ yAxisUnit: UniversalYAxisUnit.PERCENT,});+ const errorMessage = screen.getByTestId('invalid-unit-comparison');// Assert - Validation error should be displayed- expect(- screen.getByText(- /Threshold unit \(bytes\) is not valid in comparison with the column unit \(percent\)/i,- ),- ).toBeInTheDocument();+ expect(errorMessage.textContent).toBe(+ `Threshold unit (${UniversalYAxisUnit.BYTES}) is not valid in comparison with the column unit (${UniversalYAxisUnit.PERCENT})`,+ );});});diff --git a/frontend/src/container/NewWidget/utils.ts b/frontend/src/container/NewWidget/utils.tsindex c38cd31e0e..4f64b24311 100644--- a/frontend/src/container/NewWidget/utils.ts+++ b/frontend/src/container/NewWidget/utils.ts@@ -1,9 +1,12 @@import { Layout } from 'react-grid-layout';-import { DefaultOptionType } from 'antd/es/select';import { omitIdFromQuery } from 'components/ExplorerCard/utils';import { PrecisionOptionsEnum } from 'components/Graph/types';import { YAxisCategoryNames } from 'components/YAxisUnitSelector/constants';-import { YAxisSource } from 'components/YAxisUnitSelector/types';+import {+ UniversalYAxisUnit,+ YAxisCategory,+ YAxisSource,+} from 'components/YAxisUnitSelector/types';import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';import {initialQueryBuilderFormValuesMap,@@ -606,7 +609,7 @@ export const PANEL_TYPE_TO_QUERY_TYPES: Record<PANEL_TYPES, EQueryType[]> = {*/export const getCategorySelectOptionByName = (name?: YAxisCategoryNames,-): DefaultOptionType[] => {+): { name: string; id: UniversalYAxisUnit }[] => {const categories = getYAxisCategories(YAxisSource.DASHBOARDS);if (!categories.length) {return [];@@ -615,8 +618,8 @@ export const getCategorySelectOptionByName = (categories.find((category) => category.name === name)?.units.map((unit) => ({- label: unit.name,- value: unit.id,+ name: unit.name,+ id: unit.id,})) || []);};@@ -628,19 +631,19 @@ export const getCategorySelectOptionByName = (* select options. If a valid category is found, it filters the supported categories* to return only the options for the matched category.*/-export const unitOptions = (columnUnit: string): DefaultOptionType[] => {+export const unitOptions = (columnUnit: string): YAxisCategory[] => {const category = getCategoryName(columnUnit);if (isEmpty(category)) {return categoryToSupport.map((category) => ({- label: category,- options: getCategorySelectOptionByName(category),+ name: category,+ units: getCategorySelectOptionByName(category),}));}return categoryToSupport.filter((supportedCategory) => supportedCategory === category).map((filteredCategory) => ({- label: filteredCategory,- options: getCategorySelectOptionByName(filteredCategory),+ name: filteredCategory,+ units: getCategorySelectOptionByName(filteredCategory),}));};