Skip to content

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.

fix(query-builder): legacy having casing and non-positive limits (#13315)

Abhi kumarcd1068e1c392
diff --git a/frontend/src/components/InputWithLabel/InputWithLabel.tsx b/frontend/src/components/InputWithLabel/InputWithLabel.tsx
index eab8ece340..48d7f066fc 100644
--- a/frontend/src/components/InputWithLabel/InputWithLabel.tsx
+++ b/frontend/src/components/InputWithLabel/InputWithLabel.tsx
@@ -18,6 +18,7 @@ function InputWithLabel({
className,
closeIcon,
disabled,
+ sanitize,
}: {
label: string;
initialValue?: string | number | null;
@@ -29,14 +30,17 @@ function InputWithLabel({
className?: string;
closeIcon?: React.ReactNode;
disabled?: boolean;
+ /** Rewrites the typed value before it is shown and reported. */
+ sanitize?: (value: string) => string;
}): JSX.Element {
const [inputValue, setInputValue] = useState<string>(
initialValue ? initialValue.toString() : '',
);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
- setInputValue(e.target.value);
- onChange?.(e.target.value);
+ const value = sanitize ? sanitize(e.target.value) : e.target.value;
+ setInputValue(value);
+ onChange?.(value);
};
return (
@@ -78,6 +82,7 @@ InputWithLabel.defaultProps = {
initialValue: undefined,
className: undefined,
closeIcon: undefined,
+ sanitize: undefined,
};
export default InputWithLabel;
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QueryAddOns/QueryAddOns.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QueryAddOns/QueryAddOns.tsx
index a2427453d2..e4384a116e 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QueryAddOns/QueryAddOns.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QueryAddOns/QueryAddOns.tsx
@@ -26,6 +26,7 @@ import {
RAW_QUERY_FIELDS,
resolveQueryBuilderFields,
} from '../../queryBuilderFields.utils';
+import { parseLimit, sanitizeLimit } from '../../utils';
import BucketOptions from './BucketOptions/BucketOptions';
import HavingFilter from './HavingFilter/HavingFilter';
@@ -278,7 +279,7 @@ function QueryAddOns({
const handleChangeLimit = useCallback(
(value: string) => {
- handleChangeQueryData('limit', Number(value) || null);
+ handleChangeQueryData('limit', parseLimit(value));
},
[handleChangeQueryData],
);
@@ -374,6 +375,7 @@ function QueryAddOns({
label="Limit"
type="number"
onChange={handleChangeLimit}
+ sanitize={sanitizeLimit}
initialValue={query?.limit ?? undefined}
placeholder={placeholderOf(QueryBuilderField.Limit)}
onClose={(): void => handleRemoveView(QueryBuilderField.Limit)}
diff --git a/frontend/src/components/QueryBuilderV2/__tests__/QueryAddOns.test.tsx b/frontend/src/components/QueryBuilderV2/__tests__/QueryAddOns.test.tsx
index d0ed433223..c137a61414 100644
--- a/frontend/src/components/QueryBuilderV2/__tests__/QueryAddOns.test.tsx
+++ b/frontend/src/components/QueryBuilderV2/__tests__/QueryAddOns.test.tsx
@@ -169,8 +169,15 @@ describe('QueryAddOns', () => {
expect(screen.getByTestId('limit-content')).toBeInTheDocument();
expect(input.value).toBe('5');
- fireEvent.change(input, { target: { value: '10' } });
- expect(mockHandleChangeQueryData).toHaveBeenCalledWith('limit', 10);
+ const user = userEvent.setup();
+ await user.clear(input);
+ await user.type(input, '10');
+ expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 10);
+
+ await user.clear(input);
+ await user.type(input, '-5');
+ expect(input.value).toBe('5');
+ expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 5);
});
it.each([
diff --git a/frontend/src/components/QueryBuilderV2/__tests__/utils.test.ts b/frontend/src/components/QueryBuilderV2/__tests__/utils.test.ts
index 517e418f04..8c999e708e 100644
--- a/frontend/src/components/QueryBuilderV2/__tests__/utils.test.ts
+++ b/frontend/src/components/QueryBuilderV2/__tests__/utils.test.ts
@@ -12,10 +12,62 @@ import {
convertExpressionToFilters,
convertFiltersToExpression,
convertFiltersToExpressionWithExistingQuery,
+ convertHavingToExpression,
formatValueForExpression,
+ parseLimit,
removeKeysFromExpression,
+ sanitizeLimit,
} from '../utils';
+describe('convertHavingToExpression', () => {
+ it.each([
+ ['COUNT()', 'count() > 5'],
+ ['COUNT_DISTINCT(service.name)', 'count_distinct(service.name) > 5'],
+ ['P99(duration_nano)', 'p99(duration_nano) > 5'],
+ ['SUM(http.Request.Size)', 'sum(http.Request.Size) > 5'],
+ ['count()', 'count() > 5'],
+ ])('references %s by its lower-case function', (columnName, expected) => {
+ expect(
+ convertHavingToExpression([{ columnName, op: '>', value: 5 }]),
+ ).toStrictEqual({ expression: expected });
+ });
+
+ it('joins several conditions and formats list values', () => {
+ expect(
+ convertHavingToExpression([
+ { columnName: 'COUNT()', op: '>', value: 5 },
+ { columnName: 'COUNT()', op: 'NOT IN', value: [1, 2] },
+ ]),
+ ).toStrictEqual({ expression: 'count() > 5 AND count() NOT IN [1, 2]' });
+ });
+});
+
+describe('sanitizeLimit', () => {
+ it.each([
+ ['10', '10'],
+ ['-10', '10'],
+ ['2.5', '25'],
+ ['1e3', '13'],
+ ['', ''],
+ ])('sanitizes %j to %j', (value, expected) => {
+ expect(sanitizeLimit(value)).toBe(expected);
+ });
+});
+
+describe('parseLimit', () => {
+ it.each([
+ ['10', 10],
+ ['1', 1],
+ ['', null],
+ ['0', null],
+ ['-5', null],
+ ['2.5', null],
+ ['abc', null],
+ ])('parses %j as %j', (value, expected) => {
+ expect(parseLimit(value)).toBe(expected);
+ });
+});
+
describe('convertFiltersToExpression', () => {
beforeEach(() => {
jest.clearAllMocks();
diff --git a/frontend/src/components/QueryBuilderV2/utils.ts b/frontend/src/components/QueryBuilderV2/utils.ts
index 73d66dfd24..2eff73e751 100644
--- a/frontend/src/components/QueryBuilderV2/utils.ts
+++ b/frontend/src/components/QueryBuilderV2/utils.ts
@@ -840,6 +840,16 @@ export const appendAndClause = (
return hasTopLevelOr ? `(${base}) AND ${clause}` : `${base} AND ${clause}`;
};
+/** Strips everything but digits, so a limit input can't hold a sign or decimal. */
+export const sanitizeLimit = (value: string): string =>
+ value.replace(/\D/g, '');
+
+/** A query or formula limit: a positive integer, otherwise none. */
+export const parseLimit = (value: string): number | null => {
+ const limit = Number(value);
+ return Number.isInteger(limit) && limit > 0 ? limit : null;
+};
+
/**
* Convert old having format to new having format
* @param having - Array of old having objects with columnName, op, and value
@@ -871,7 +881,14 @@ export const convertHavingToExpression = (
formattedValue = String(value);
}
- return `${columnName} ${op} ${formattedValue}`;
+ // The old having filter upper-cased the function (`COUNT()`); v5 only
+ // resolves the aggregation's own lower-case expression.
+ const reference = columnName.replace(
+ /^\s*([A-Za-z_]\w*)\(/,
+ (_, fn: string) => `${fn.toLowerCase()}(`,
+ );
+
+ return `${reference} ${op} ${formattedValue}`;
})
.filter((expression) => expression !== ''); // Remove empty expressions
diff --git a/frontend/src/container/QueryBuilder/components/Formula/Formula.tsx b/frontend/src/container/QueryBuilder/components/Formula/Formula.tsx
index 4d59364148..669aac4cb9 100644
--- a/frontend/src/container/QueryBuilder/components/Formula/Formula.tsx
+++ b/frontend/src/container/QueryBuilder/components/Formula/Formula.tsx
@@ -2,6 +2,7 @@ import { ChangeEvent, useCallback, useMemo, useState } from 'react';
import { Col, Input, Row, Select } from 'antd';
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';
// ** Hooks
@@ -171,7 +172,8 @@ export function Formula({
<InputWithLabel
label="Limit"
type="number"
- onChange={(value): void => handleChangeLimit(Number(value))}
+ onChange={(value): void => handleChangeLimit(parseLimit(value))}
+ sanitize={sanitizeLimit}
initialValue={formula?.limit ?? undefined}
placeholder="Enter limit"
/>