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
chore: replace prop drilling with fetch store (#10291)
Ashwin Bhatkalf277009ff807
diff --git a/frontend/src/components/NewSelect/__test__/VariableItem.integration.test.tsx b/frontend/src/components/NewSelect/__test__/VariableItem.integration.test.tsxindex ad2a354905..e7745d4ad4 100644--- a/frontend/src/components/NewSelect/__test__/VariableItem.integration.test.tsx+++ b/frontend/src/components/NewSelect/__test__/VariableItem.integration.test.tsx@@ -78,12 +78,10 @@ function TestWrapper({ children }: { children: React.ReactNode }): JSX.Element {describe('VariableItem Integration Tests', () => {let user: ReturnType<typeof userEvent.setup>;let mockOnValueUpdate: jest.Mock;- let mockSetVariablesToGetUpdated: jest.Mock;beforeEach(() => {user = userEvent.setup();mockOnValueUpdate = jest.fn();- mockSetVariablesToGetUpdated = jest.fn();jest.clearAllMocks();});@@ -102,9 +100,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -150,9 +145,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -195,9 +187,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -247,9 +236,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -272,9 +258,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -308,9 +291,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -344,9 +324,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -369,9 +346,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -405,9 +379,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -461,9 +432,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -508,9 +476,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -548,9 +513,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);@@ -582,9 +544,6 @@ describe('VariableItem Integration Tests', () => {variableData={variable}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={null}/></TestWrapper>,);diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsxindex 5fe1868eeb..7807ad5682 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx@@ -9,11 +9,15 @@ import {import useVariablesFromUrl from 'hooks/dashboard/useVariablesFromUrl';import { useDashboard } from 'providers/Dashboard/Dashboard';import { initializeDefaultVariables } from 'providers/Dashboard/initializeDefaultVariables';+import {+ enqueueDescendantsOfVariable,+ enqueueFetchOfAllVariables,+ initializeVariableFetchStore,+} from 'providers/Dashboard/store/variableFetchStore';import { AppState } from 'store/reducers';import { IDashboardVariable } from 'types/api/dashboard/getAll';import { GlobalReducer } from 'types/reducer/globalTime';-import { onUpdateVariableNode } from './util';import VariableItem from './VariableItem';import './DashboardVariableSelection.styles.scss';@@ -22,8 +26,6 @@ function DashboardVariableSelection(): JSX.Element | null {const {setSelectedDashboard,updateLocalStorageDashboardVariables,- variablesToGetUpdated,- setVariablesToGetUpdated,} = useDashboard();const { updateUrlVariable, getUrlVariables } = useVariablesFromUrl();@@ -55,11 +57,14 @@ function DashboardVariableSelection(): JSX.Element | null {[dependencyData?.order],);- // Trigger refetch when dependency order changes or global time changes+ // Initialize fetch store then start a new fetch cycle.+ // Runs on dependency order changes, and time range changes.useEffect(() => {- if (dependencyData?.order && dependencyData.order.length > 0) {- setVariablesToGetUpdated(dependencyData?.order || []);- }+ const allVariableNames = sortedVariablesArray+ .map((v) => v.name)+ .filter((name): name is string => !!name);+ initializeVariableFetchStore(allVariableNames);+ enqueueFetchOfAllVariables();// eslint-disable-next-line react-hooks/exhaustive-deps}, [dependencyOrderKey, minTime, maxTime]);@@ -121,29 +126,14 @@ function DashboardVariableSelection(): JSX.Element | null {return prev;});- if (dependencyData) {- const updatedVariables: string[] = [];- onUpdateVariableNode(- name,- dependencyData.graph,- dependencyData.order,- (node) => updatedVariables.push(node),- );- setVariablesToGetUpdated((prev) => [- ...new Set([...prev, ...updatedVariables.filter((v) => v !== name)]),- ]);- } else {- setVariablesToGetUpdated((prev) => prev.filter((v) => v !== name));- }+ // Cascade: enqueue query-type descendants for refetching+ enqueueDescendantsOfVariable(name);},[- // This can be removeddashboardVariables,updateLocalStorageDashboardVariables,- dependencyData,updateUrlVariable,setSelectedDashboard,- setVariablesToGetUpdated,],);@@ -158,9 +148,6 @@ function DashboardVariableSelection(): JSX.Element | null {existingVariables={dashboardVariables}variableData={variable}onValueUpdate={onValueUpdate}- variablesToGetUpdated={variablesToGetUpdated}- setVariablesToGetUpdated={setVariablesToGetUpdated}- dependencyData={dependencyData}/>);})}diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsxindex 68a465a2be..4884c29220 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx@@ -2,18 +2,25 @@ import { memo, useCallback, useMemo, useState } from 'react';import { useQuery } from 'react-query';import { useSelector } from 'react-redux';import { getFieldValues } from 'api/dynamicVariables/getFieldValues';-import { SOMETHING_WENT_WRONG } from 'constants/api';import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';+import { useVariableFetchState } from 'hooks/dashboard/useVariableFetchState';import useDebounce from 'hooks/useDebounce';-import { isEmpty } from 'lodash-es';import { AppState } from 'store/reducers';+import { SuccessResponseV2 } from 'types/api';+import { FieldValueResponse } from 'types/api/dynamicVariables/getFieldValues';import { GlobalReducer } from 'types/reducer/globalTime';import { isRetryableError as checkIfRetryableError } from 'utils/errorUtils';import SelectVariableInput from './SelectVariableInput';import { useDashboardVariableSelectHelper } from './useDashboardVariableSelectHelper';-import { getOptionsForDynamicVariable } from './util';+import {+ buildExistingDynamicVariableQuery,+ extractErrorMessage,+ getOptionsForDynamicVariable,+ mergeUniqueStrings,+ settleVariableFetch,+} from './util';import { VariableItemProps } from './VariableItem';import { dynamicVariableSelectStrategy } from './variableSelectStrategy/dynamicVariableSelectStrategy';@@ -24,7 +31,6 @@ type DynamicVariableInputProps = Pick<'variableData' | 'onValueUpdate' | 'existingVariables'>;-// eslint-disable-next-line sonarjs/cognitive-complexityfunction DynamicVariableInput({variableData,onValueUpdate,@@ -55,14 +61,8 @@ function DynamicVariableInput({const debouncedApiSearchText = useDebounce(apiSearchText, DEBOUNCE_DELAY);- // Build a memoized list of all currently available option strings (normalized + related)const allAvailableOptionStrings = useMemo(- () => [- ...new Set([- ...optionsData.map((v) => v.toString()),- ...relatedValues.map((v) => v.toString()),- ]),- ],+ () => mergeUniqueStrings(optionsData, relatedValues),[optionsData, relatedValues],);@@ -104,67 +104,24 @@ function DynamicVariableInput({(state) => state.globalTime,);- // existing query is the query made from the other dynamic variables around this one with there current values- // for e.g. k8s.namespace.name IN ["zeus", "gene"] AND doc_op_type IN ["test"]- // eslint-disable-next-line sonarjs/cognitive-complexity- const existingQuery = useMemo(() => {- if (!existingVariables || !variableData.dynamicVariablesAttribute) {- return '';- }-- const queryParts: string[] = [];-- Object.entries(existingVariables).forEach(([, variable]) => {- // Skip the current variable being processed- if (variable.id === variableData.id) {- return;- }-- // Only include dynamic variables that have selected values and are not selected as ALL- if (- variable.type === 'DYNAMIC' &&- variable.dynamicVariablesAttribute &&- variable.selectedValue &&- !isEmpty(variable.selectedValue) &&- (variable.showALLOption ? !variable.allSelected : true)- ) {- const attribute = variable.dynamicVariablesAttribute;- const values = Array.isArray(variable.selectedValue)- ? variable.selectedValue- : [variable.selectedValue];-- // Filter out empty values and convert to strings- const validValues = values- .filter((val) => val !== null && val !== undefined && val !== '')- .map((val) => val.toString());-- if (validValues.length > 0) {- // Format values for query - wrap strings in quotes, keep numbers as is- const formattedValues = validValues.map((val) => {- // Check if value is a number- const numValue = Number(val);- if (!Number.isNaN(numValue) && Number.isFinite(numValue)) {- return val; // Keep as number- }- // Escape single quotes and wrap in quotes- return `'${val.replace(/'/g, "\\'")}'`;- });-- if (formattedValues.length === 1) {- queryParts.push(`${attribute} = ${formattedValues[0]}`);- } else {- queryParts.push(`${attribute} IN [${formattedValues.join(', ')}]`);- }- }- }- });-- return queryParts.join(' AND ');- }, [- existingVariables,- variableData.id,- variableData.dynamicVariablesAttribute,- ]);+ const {+ variableFetchCycleId,+ isVariableSettled,+ isVariableFetching,+ hasVariableFetchedOnce,+ isVariableWaitingForDependencies,+ variableDependencyWaitMessage,+ } = useVariableFetchState(variableData.name || '');++ const existingQuery = useMemo(+ () =>+ buildExistingDynamicVariableQuery(+ existingVariables,+ variableData.id,+ !!variableData.dynamicVariablesAttribute,+ ),+ [existingVariables, variableData.id, variableData.dynamicVariablesAttribute],+ );// Wrap the hook's onDropdownVisibleChange to also track isDropdownOpen and handle cleanupconst handleSelectDropdownVisibilityChange = useCallback(@@ -182,6 +139,73 @@ function DynamicVariableInput({[onDropdownVisibleChange, optionsData, originalRelatedValues],);+ const handleQuerySuccess = useCallback(+ (data: SuccessResponseV2<FieldValueResponse>): void => {+ const newNormalizedValues = data.data?.normalizedValues || [];+ const newRelatedValues = data.data?.relatedValues || [];++ if (!debouncedApiSearchText) {+ setOptionsData(newNormalizedValues);+ setIsComplete(data.data?.complete || false);+ }+ setFilteredOptionsData(newNormalizedValues);+ setRelatedValues(newRelatedValues);+ setOriginalRelatedValues(newRelatedValues);++ // Sync temp selection with latest API values when ALL is active and dropdown is open+ if (variableData.allSelected && isDropdownOpen) {+ const latestValues = mergeUniqueStrings(+ newNormalizedValues,+ newRelatedValues,+ );++ const currentStrings = Array.isArray(tempSelection)+ ? tempSelection.map((v) => v.toString())+ : tempSelection+ ? [tempSelection.toString()]+ : [];++ const areSame =+ currentStrings.length === latestValues.length &&+ latestValues.every((v) => currentStrings.includes(v));++ if (!areSame) {+ setTempSelection(latestValues);+ }+ }++ // Apply default if no value is selected (e.g., new variable, first load)+ if (!debouncedApiSearchText) {+ applyDefaultIfNeeded(+ mergeUniqueStrings(newNormalizedValues, newRelatedValues),+ );+ }++ settleVariableFetch(variableData.name, 'complete');+ },+ [+ debouncedApiSearchText,+ variableData.allSelected,+ variableData.name,+ isDropdownOpen,+ tempSelection,+ setTempSelection,+ applyDefaultIfNeeded,+ ],+ );++ const handleQueryError = useCallback(+ (error: { message?: string } | null): void => {+ if (error) {+ setErrorMessage(extractErrorMessage(error));+ setIsRetryableError(checkIfRetryableError(error));+ }++ settleVariableFetch(variableData.name, 'failure');+ },+ [variableData.name],+ );+const { isLoading, refetch } = useQuery([REACT_QUERY_KEY.DASHBOARD_BY_ID,@@ -192,13 +216,22 @@ function DynamicVariableInput({debouncedApiSearchText,variableData.dynamicVariablesSource,variableData.dynamicVariablesAttribute,+ variableFetchCycleId,],{+ /*+ * enabled if+ * - we have dynamic variable source and attribute defined (ALWAYS)+ * - AND+ * - we're either still fetching variable options+ * - OR+ * - if variable is in idle state and we have already fetched options for it+ **/enabled:- variableData.type === 'DYNAMIC' &&!!variableData.dynamicVariablesSource &&- !!variableData.dynamicVariablesAttribute,- queryFn: () =>+ !!variableData.dynamicVariablesAttribute &&+ (isVariableFetching || (isVariableSettled && hasVariableFetchedOnce)),+ queryFn: ({ signal }) =>getFieldValues(variableData.dynamicVariablesSource?.toLowerCase() === 'all telemetry'? undefined@@ -211,70 +244,10 @@ function DynamicVariableInput({minTime,maxTime,existingQuery,+ signal,),- onSuccess: (data) => {- const newNormalizedValues = data.data?.normalizedValues || [];- const newRelatedValues = data.data?.relatedValues || [];-- if (!debouncedApiSearchText) {- setOptionsData(newNormalizedValues);- setIsComplete(data.data?.complete || false);- }- setFilteredOptionsData(newNormalizedValues);- setRelatedValues(newRelatedValues);- setOriginalRelatedValues(newRelatedValues);-- // Only run auto-check logic when necessary to avoid performance issues- if (variableData.allSelected && isDropdownOpen) {- // Build the latest full list from API (normalized + related)- const latestValues = [- ...new Set([- ...newNormalizedValues.map((v) => v.toString()),- ...newRelatedValues.map((v) => v.toString()),- ]),- ];-- // Update temp selection to exactly reflect latest API values when ALL is active- const currentStrings = Array.isArray(tempSelection)- ? tempSelection.map((v) => v.toString())- : tempSelection- ? [tempSelection.toString()]- : [];- const areSame =- currentStrings.length === latestValues.length &&- latestValues.every((v) => currentStrings.includes(v));- if (!areSame) {- setTempSelection(latestValues);- }- }-- // Apply default if no value is selected (e.g., new variable, first load)- if (!debouncedApiSearchText) {- const allNewOptions = [- ...new Set([- ...newNormalizedValues.map((v) => v.toString()),- ...newRelatedValues.map((v) => v.toString()),- ]),- ];- applyDefaultIfNeeded(allNewOptions);- }- },- onError: (error: any) => {- if (error) {- let message = SOMETHING_WENT_WRONG;- if (error?.message) {- message = error?.message;- } else {- message =- 'Please make sure configuration is valid and you have required setup and permissions';- }- setErrorMessage(message);-- // Check if error is retryable (5xx) or not (4xx)- const isRetryable = checkIfRetryableError(error);- setIsRetryableError(isRetryable);- }- },+ onSuccess: handleQuerySuccess,+ onError: handleQueryError,},);@@ -336,6 +309,8 @@ function DynamicVariableInput({showRetryButton={isRetryableError}showIncompleteDataMessage={!isComplete && filteredOptionsData.length > 0}onSearch={handleSearch}+ waiting={isVariableWaitingForDependencies}+ waitingMessage={variableDependencyWaitMessage}/>);}diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsxindex 82943e529f..c2e896d424 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx@@ -3,8 +3,9 @@ import { useQuery } from 'react-query';import { useSelector } from 'react-redux';import dashboardVariablesQuery from 'api/dashboard/variables/dashboardVariablesQuery';import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';+import { useVariableFetchState } from 'hooks/dashboard/useVariableFetchState';import sortValues from 'lib/dashboardVariables/sortVariableValues';-import { isArray, isString } from 'lodash-es';+import { isArray, isEmpty, isString } from 'lodash-es';import { AppState } from 'store/reducers';import { VariableResponseProps } from 'types/api/dashboard/variables/query';import { GlobalReducer } from 'types/reducer/globalTime';@@ -12,26 +13,18 @@ import { GlobalReducer } from 'types/reducer/globalTime';import { variablePropsToPayloadVariables } from '../utils';import SelectVariableInput from './SelectVariableInput';import { useDashboardVariableSelectHelper } from './useDashboardVariableSelectHelper';-import { areArraysEqual, checkAPIInvocation } from './util';+import { areArraysEqual, settleVariableFetch } from './util';import { VariableItemProps } from './VariableItem';import { queryVariableSelectStrategy } from './variableSelectStrategy/queryVariableSelectStrategy';type QueryVariableInputProps = Pick<VariableItemProps,- | 'variableData'- | 'existingVariables'- | 'onValueUpdate'- | 'variablesToGetUpdated'- | 'setVariablesToGetUpdated'- | 'dependencyData'+ 'variableData' | 'existingVariables' | 'onValueUpdate'>;function QueryVariableInput({variableData,existingVariables,- variablesToGetUpdated,- setVariablesToGetUpdated,- dependencyData,onValueUpdate,}: QueryVariableInputProps): JSX.Element {const [optionsData, setOptionsData] = useState<(string | number | boolean)[]>(@@ -43,6 +36,15 @@ function QueryVariableInput({(state) => state.globalTime,);+ const {+ variableFetchCycleId,+ isVariableSettled,+ isVariableFetching,+ hasVariableFetchedOnce,+ isVariableWaitingForDependencies,+ variableDependencyWaitMessage,+ } = useVariableFetchState(variableData.name || '');+const {tempSelection,setTempSelection,@@ -60,16 +62,6 @@ function QueryVariableInput({strategy: queryVariableSelectStrategy,});- const validVariableUpdate = useCallback((): boolean => {- if (!variableData.name) {- return false;- }- return Boolean(- variablesToGetUpdated.length &&- variablesToGetUpdated[0] === variableData.name,- );- }, [variableData.name, variablesToGetUpdated]);-const getOptions = useCallback(// eslint-disable-next-line sonarjs/cognitive-complexity(variablesRes: VariableResponseProps | null): void => {@@ -103,18 +95,24 @@ function QueryVariableInput({valueNotInList = true;}- // variablesData.allSelected is added for the case where on change of options we need to update the- // local storage- if (- variableData.name &&- (validVariableUpdate() || valueNotInList || variableData.allSelected)- ) {+ if (variableData.name && (valueNotInList || variableData.allSelected)) {if (variableData.allSelected &&variableData.multiSelect &&variableData.showALLOption) {- onValueUpdate(variableData.name, variableData.id, newOptionsData, true);+ if (+ variableData.name &&+ variableData.id &&+ !isEmpty(variableData.selectedValue)+ ) {+ onValueUpdate(+ variableData.name,+ variableData.id,+ newOptionsData,+ true,+ );+ }// Update tempSelection to maintain ALL state when dropdown is openif (tempSelection !== undefined) {@@ -132,7 +130,11 @@ function QueryVariableInput({newOptionsData.every((option) => selectedValue.includes(option));}- if (variableData.name && variableData.id) {+ if (+ variableData.name &&+ variableData.id &&+ !isEmpty(variableData.selectedValue)+ ) {onValueUpdate(variableData.name, variableData.id, value, allSelected);}}@@ -141,10 +143,6 @@ function QueryVariableInput({setOptionsData(newOptionsData);// Apply default if no value is selected (e.g., new variable, first load)applyDefaultIfNeeded(newOptionsData);- } else {- setVariablesToGetUpdated((prev) =>- prev.filter((name) => name !== variableData.name),- );}}} catch (e) {@@ -157,8 +155,6 @@ function QueryVariableInput({onValueUpdate,tempSelection,setTempSelection,- validVariableUpdate,- setVariablesToGetUpdated,applyDefaultIfNeeded,],);@@ -169,27 +165,28 @@ function QueryVariableInput({variableData.name || '',`${minTime}`,`${maxTime}`,- JSON.stringify(dependencyData?.order),+ variableFetchCycleId,],{- enabled:- variableData &&- checkAPIInvocation(- variablesToGetUpdated,- variableData,- dependencyData?.parentDependencyGraph,+ /*+ * enabled if+ * - we're either still fetching variable options+ * - OR+ * - if variable is in idle state and we have already fetched options for it+ **/+ enabled: isVariableFetching || (isVariableSettled && hasVariableFetchedOnce),+ queryFn: ({ signal }) =>+ dashboardVariablesQuery(+ {+ query: variableData.queryValue || '',+ variables: variablePropsToPayloadVariables(existingVariables),+ },+ signal,),- queryFn: () =>- dashboardVariablesQuery({- query: variableData.queryValue || '',- variables: variablePropsToPayloadVariables(existingVariables),- }),refetchOnWindowFocus: false,onSuccess: (response) => {getOptions(response.payload);- setVariablesToGetUpdated((prev) =>- prev.filter((v) => v !== variableData.name),- );+ settleVariableFetch(variableData.name, 'complete');},onError: (error: {details: {@@ -206,9 +203,7 @@ function QueryVariableInput({}setErrorMessage(message);}- setVariablesToGetUpdated((prev) =>- prev.filter((v) => v !== variableData.name),- );+ settleVariableFetch(variableData.name, 'failure');},},);@@ -242,6 +237,8 @@ function QueryVariableInput({loading={isLoading}errorMessage={errorMessage}onRetry={handleRetry}+ waiting={isVariableWaitingForDependencies}+ waitingMessage={variableDependencyWaitMessage}/>);}diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsxindex 3d6249e96c..5c46419782 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx@@ -28,6 +28,8 @@ interface SelectVariableInputProps {showRetryButton?: boolean;showIncompleteDataMessage?: boolean;onSearch?: (searchTerm: string) => void;+ waiting?: boolean;+ waitingMessage?: string;}const MAX_TAG_DISPLAY_VALUES = 10;@@ -65,6 +67,7 @@ function SelectVariableInput({showRetryButton,showIncompleteDataMessage,onSearch,+ waitingMessage,}: SelectVariableInputProps): JSX.Element {const commonProps = useMemo(() => ({@@ -78,7 +81,6 @@ function SelectVariableInput({className: 'variable-select',popupClassName: 'dropdown-styles',getPopupContainer: popupContainer,- style: SelectItemStyle,showSearch: true,bordered: false,@@ -86,6 +88,8 @@ function SelectVariableInput({'data-testid': 'variable-select',onChange,loading,+ waitingMessage,+ style: SelectItemStyle,options,errorMessage,onRetry,@@ -101,6 +105,7 @@ function SelectVariableInput({defaultValue,onChange,loading,+ waitingMessage,options,value,errorMessage,diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.test.tsxindex 00df106aed..3d6ac415df 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.test.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.test.tsx@@ -47,15 +47,6 @@ describe('VariableItem', () => {variableData={mockVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);@@ -70,15 +61,6 @@ describe('VariableItem', () => {variableData={mockVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);@@ -94,15 +76,6 @@ describe('VariableItem', () => {variableData={mockVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);@@ -136,15 +109,6 @@ describe('VariableItem', () => {variableData={mockCustomVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);@@ -167,15 +131,6 @@ describe('VariableItem', () => {variableData={customVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);@@ -190,15 +145,6 @@ describe('VariableItem', () => {variableData={mockCustomVariableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={(): void => {}}- dependencyData={{- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,- }}/></MockQueryClientProvider>,);diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsxindex 50f535cddf..6f516361cf 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx@@ -1,7 +1,6 @@import { memo } from 'react';import { InfoCircleOutlined } from '@ant-design/icons';import { Tooltip, Typography } from 'antd';-import { IDependencyData } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';import { IDashboardVariable } from 'types/api/dashboard/getAll';import CustomVariableInput from './CustomVariableInput';@@ -21,18 +20,12 @@ export interface VariableItemProps {allSelected: boolean,haveCustomValuesSelected?: boolean,) => void;- variablesToGetUpdated: string[];- setVariablesToGetUpdated: React.Dispatch<React.SetStateAction<string[]>>;- dependencyData: IDependencyData | null;}function VariableItem({variableData,onValueUpdate,existingVariables,- variablesToGetUpdated,- setVariablesToGetUpdated,- dependencyData,}: VariableItemProps): JSX.Element {const { name, description, type: variableType } = variableData;@@ -65,9 +58,6 @@ function VariableItem({variableData={variableData}onValueUpdate={onValueUpdate}existingVariables={existingVariables}- variablesToGetUpdated={variablesToGetUpdated}- setVariablesToGetUpdated={setVariablesToGetUpdated}- dependencyData={dependencyData}/>)}{variableType === 'DYNAMIC' && (diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsxindex a56ec0381c..b4a6d72576 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx@@ -7,6 +7,19 @@ import { IDashboardVariable } from 'types/api/dashboard/getAll';import DynamicVariableInput from '../DynamicVariableInput';+// Mock useVariableFetchState to return "fetching" state so useQuery is enabled+jest.mock('hooks/dashboard/useVariableFetchState', () => ({+ useVariableFetchState: (): Record<string, unknown> => ({+ variableFetchCycleId: 0,+ variableFetchState: 'loading',+ isVariableSettled: false,+ isVariableFetching: true,+ hasVariableFetchedOnce: false,+ isVariableWaitingForDependencies: false,+ variableDependencyWaitMessage: '',+ }),+}));+// Don't mock the components - use real ones// Mock for useQuery@@ -217,9 +230,10 @@ describe('DynamicVariableInput Component', () => {'','Traces','service.name',+ 0, // variableFetchCycleId],expect.objectContaining({- enabled: true, // Type is 'DYNAMIC'+ enabled: true, // isVariableFetching is true from mockqueryFn: expect.any(Function),onSuccess: expect.any(Function),onError: expect.any(Function),diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsxindex b51db05cb6..8c32873dc3 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx@@ -8,15 +8,6 @@ import '@testing-library/jest-dom/extend-expect';import VariableItem from '../VariableItem';const mockOnValueUpdate = jest.fn();-const mockSetVariablesToGetUpdated = jest.fn();--const baseDependencyData = {- order: [],- graph: {},- parentDependencyGraph: {},- transitiveDescendants: {},- hasCycle: false,-};const TEST_VARIABLE_ID = 'test_variable';const VARIABLE_SELECT_TESTID = 'variable-select';@@ -32,9 +23,6 @@ const renderVariableItem = (variableData={variableData}existingVariables={{}}onValueUpdate={mockOnValueUpdate}- variablesToGetUpdated={[]}- setVariablesToGetUpdated={mockSetVariablesToGetUpdated}- dependencyData={baseDependencyData}/></MockQueryClientProvider>,);diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/dashboardVariables.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/dashboardVariables.test.tsxindex 9a1a3c4ded..06837c5560 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/dashboardVariables.test.tsx+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/dashboardVariables.test.tsx@@ -2,14 +2,12 @@ import {buildDependencies,buildDependencyGraph,buildParentDependencyGraph,- checkAPIInvocation,onUpdateVariableNode,VariableGraph,} from '../util';import {buildDependenciesMock,buildGraphMock,- checkAPIInvocationMock,onUpdateVariableNodeMock,} from './mock';@@ -72,97 +70,6 @@ describe('dashboardVariables - utilities and processors', () => {});});- describe('checkAPIInvocation', () => {- const {- variablesToGetUpdated,- variableData,- parentDependencyGraph,- } = checkAPIInvocationMock;-- const mockRootElement = {- name: 'deployment_environment',- key: '036a47cd-9ffc-47de-9f27-0329198964a8',- id: '036a47cd-9ffc-47de-9f27-0329198964a8',- modificationUUID: '5f71b591-f583-497c-839d-6a1590c3f60f',- selectedValue: 'production',- type: 'QUERY',- // ... other properties omitted for brevity- } as any;-- describe('edge cases', () => {- it('should return false when variableData is empty', () => {- expect(- checkAPIInvocation(- variablesToGetUpdated,- variableData,- parentDependencyGraph,- ),- ).toBeFalsy();- });-- it('should return true when parentDependencyGraph is empty', () => {- expect(- checkAPIInvocation(variablesToGetUpdated, variableData, {}),- ).toBeFalsy();- });- });-- describe('variable sequences', () => {- it('should return true for valid sequence', () => {- expect(- checkAPIInvocation(- ['k8s_node_name', 'k8s_namespace_name'],- variableData,- parentDependencyGraph,- ),- ).toBeTruthy();- });-- it('should return false for invalid sequence', () => {- expect(- checkAPIInvocation(- ['k8s_cluster_name', 'k8s_node_name', 'k8s_namespace_name'],- variableData,- parentDependencyGraph,- ),- ).toBeFalsy();- });-- it('should return false when variableData is not in sequence', () => {- expect(- checkAPIInvocation(- ['deployment_environment', 'service_name', 'endpoint'],- variableData,- parentDependencyGraph,- ),- ).toBeFalsy();- });- });-- describe('root element behavior', () => {- it('should return true for valid root element sequence', () => {- expect(- checkAPIInvocation(- [- 'deployment_environment',- 'service_name',- 'endpoint',- 'http_status_code',- ],- mockRootElement,- parentDependencyGraph,- ),- ).toBeTruthy();- });-- it('should return true for empty variablesToGetUpdated array', () => {- expect(- checkAPIInvocation([], mockRootElement, parentDependencyGraph),- ).toBeTruthy();- });- });- });-describe('Graph Building Utilities', () => {const { graph } = buildGraphMock;const { variables } = buildDependenciesMock;diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/mock.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/mock.tsindex c39841fcf4..3ba37f7b8c 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/mock.ts+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/mock.ts@@ -1,36 +1,3 @@-/* eslint-disable sonarjs/no-duplicate-string */-export const checkAPIInvocationMock = {- variablesToGetUpdated: [],- variableData: {- name: 'k8s_node_name',- key: '4d71d385-beaf-4434-8dbf-c62be68049fc',- allSelected: false,- customValue: '',- description: '',- id: '4d71d385-beaf-4434-8dbf-c62be68049fc',- modificationUUID: '77233d3c-96d7-4ccb-aa9d-11b04d563068',- multiSelect: false,- order: 6,- queryValue:- "SELECT JSONExtractString(labels, 'k8s_node_name') AS k8s_node_name\nFROM signoz_metrics.distributed_time_series_v4_1day\nWHERE metric_name = 'k8s_node_cpu_time' AND JSONExtractString(labels, 'k8s_cluster_name') = {{.k8s_cluster_name}}\nGROUP BY k8s_node_name",- selectedValue: 'gke-signoz-saas-si-consumer-bsc-e2sd4-a6d430fa-gvm2',- showALLOption: false,- sort: 'DISABLED',- textboxValue: '',- type: 'QUERY',- },- parentDependencyGraph: {- deployment_environment: [],- service_name: ['deployment_environment'],- endpoint: ['deployment_environment', 'service_name'],- http_status_code: ['endpoint'],- k8s_cluster_name: [],- environment: [],- k8s_node_name: ['k8s_cluster_name'],- k8s_namespace_name: ['k8s_cluster_name', 'k8s_node_name'],- },-} as any;-export const onUpdateVariableNodeMock = {nodeToUpdate: 'deployment_environment',graph: {diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.tsindex c1fc3f307f..2ea9e32f48 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts@@ -1,9 +1,16 @@import { OptionData } from 'components/NewSelect/types';-import { isEmpty, isNull } from 'lodash-es';+import { SOMETHING_WENT_WRONG } from 'constants/api';+import { textContainsVariableReference } from 'lib/dashboardVariables/variableReference';+import { isEmpty } from 'lodash-es';import {IDashboardVariables,IDependencyData,} from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';+import {+ onVariableFetchComplete,+ onVariableFetchFailure,+ variableFetchStore,+} from 'providers/Dashboard/store/variableFetchStore';import { IDashboardVariable } from 'types/api/dashboard/getAll';export function areArraysEqual(@@ -45,30 +52,16 @@ const getDependentVariablesBasedOnVariableName = (}return variables- ?.map((variable: any) => {+ .map((variable) => {if (variable.type === 'QUERY') {- // Combined pattern for all formats- // {{.variable_name}} - original format- // $variable_name - dollar prefix format- // [[variable_name]] - square bracket format- // {{variable_name}} - without dot format- const patterns = [- `\\{\\{\\s*?\\.${variableName}\\s*?\\}\\}`, // {{.var}}- `\\{\\{\\s*${variableName}\\s*\\}\\}`, // {{var}}- `\\$${variableName}\\b`, // $var- `\\[\\[\\s*${variableName}\\s*\\]\\]`, // [[var]]- ];- const combinedRegex = new RegExp(patterns.join('|'));-const queryValue = variable.queryValue || '';- const dependVarReMatch = queryValue.match(combinedRegex);- if (dependVarReMatch !== null && dependVarReMatch.length > 0) {+ if (textContainsVariableReference(queryValue, variableName)) {return variable.name;}}return null;})- .filter((val: string | null) => !isNull(val));+ .filter((val): val is string => val !== null);};export type VariableGraph = Record<string, string[]>;@@ -300,33 +293,6 @@ export const onUpdateVariableNode = (});};-export const checkAPIInvocation = (- variablesToGetUpdated: string[],- variableData: IDashboardVariable,- parentDependencyGraph?: VariableGraph,-): boolean => {- if (isEmpty(variableData.name)) {- return false;- }-- if (isEmpty(parentDependencyGraph)) {- return false;- }-- // if no dependency then true- const haveDependency =- parentDependencyGraph?.[variableData.name || '']?.length > 0;- if (!haveDependency) {- return true;- }-- // if variable is in the list and has dependency then check if its the top element in the queue then true else false- return (- variablesToGetUpdated.length > 0 &&- variablesToGetUpdated[0] === variableData.name- );-};-export const getOptionsForDynamicVariable = (normalizedValues: (string | number | boolean)[],relatedValues: string[],@@ -391,3 +357,130 @@ export const getSelectValue = (}return selectedValue?.toString();};++/**+ * Merges multiple arrays of values into a single deduplicated string array.+ */+export function mergeUniqueStrings(+ ...arrays: (string | number | boolean)[][]+): string[] {+ return [...new Set(arrays.flatMap((arr) => arr.map((v) => v.toString())))];+}++function isEligibleFilterVariable(+ variable: IDashboardVariable,+ currentVariableId: string,+): boolean {+ if (variable.id === currentVariableId) {+ return false;+ }+ if (variable.type !== 'DYNAMIC') {+ return false;+ }+ if (!variable.dynamicVariablesAttribute) {+ return false;+ }+ if (!variable.selectedValue || isEmpty(variable.selectedValue)) {+ return false;+ }+ return !(variable.showALLOption && variable.allSelected);+}++function formatQueryValue(val: string): string {+ const numValue = Number(val);+ if (!Number.isNaN(numValue) && Number.isFinite(numValue)) {+ return val;+ }+ return `'${val.replace(/'/g, "\\'")}'`;+}++function buildQueryPart(attribute: string, values: string[]): string {+ const formatted = values.map(formatQueryValue);+ if (formatted.length === 1) {+ return `${attribute} = ${formatted[0]}`;+ }+ return `${attribute} IN [${formatted.join(', ')}]`;+}++/**+ * Builds a filter query string from sibling dynamic variables' selected values.+ * e.g. `k8s.namespace.name IN ['zeus', 'gene'] AND doc_op_type = 'test'`+ */+export function buildExistingDynamicVariableQuery(+ existingVariables: IDashboardVariables | null,+ currentVariableId: string,+ hasDynamicAttribute: boolean,+): string {+ if (!existingVariables || !hasDynamicAttribute) {+ return '';+ }++ const queryParts: string[] = [];++ for (const variable of Object.values(existingVariables)) {+ // Skip the current variable being processed+ if (!isEligibleFilterVariable(variable, currentVariableId)) {+ continue;+ }++ const rawValues = Array.isArray(variable.selectedValue)+ ? variable.selectedValue+ : [variable.selectedValue];++ // Filter out empty values and convert to strings+ const validValues = rawValues+ .filter(+ (val): val is string | number | boolean =>+ val !== null && val !== undefined && val !== '',+ )+ .map((val) => val.toString());++ if (validValues.length > 0 && variable.dynamicVariablesAttribute) {+ queryParts.push(+ buildQueryPart(variable.dynamicVariablesAttribute, validValues),+ );+ }+ }++ return queryParts.join(' AND ');+}++function isVariableInActiveFetchState(state: string | undefined): boolean {+ return state === 'loading' || state === 'revalidating';+}++/**+ * Completes or fails a variable's fetch state machine transition.+ * No-ops if the variable is not currently in an active fetch state.+ */+export function settleVariableFetch(+ name: string | undefined,+ outcome: 'complete' | 'failure',+): void {+ if (!name) {+ return;+ }++ const currentState = variableFetchStore.getSnapshot().states[name];+ if (!isVariableInActiveFetchState(currentState)) {+ return;+ }++ if (outcome === 'complete') {+ onVariableFetchComplete(name);+ } else {+ onVariableFetchFailure(name);+ }+}++export function extractErrorMessage(+ error: { message?: string } | null,+): string {+ if (!error) {+ return SOMETHING_WENT_WRONG;+ }+ return (+ error.message ||+ 'Please make sure configuration is valid and you have required setup and permissions'+ );+}diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/utils.test.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/utils.test.tsindex c5b8721c19..9b82d3e23a 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/utils.test.ts+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/utils.test.ts@@ -1,4 +1,31 @@-import { areArraysEqual, onUpdateVariableNode, VariableGraph } from './util';+jest.mock('providers/Dashboard/store/variableFetchStore', () => ({+ variableFetchStore: {+ getSnapshot: jest.fn(),+ },+ onVariableFetchComplete: jest.fn(),+ onVariableFetchFailure: jest.fn(),+}));++import {+ onVariableFetchComplete,+ onVariableFetchFailure,+ variableFetchStore,+} from 'providers/Dashboard/store/variableFetchStore';+import { IDashboardVariable } from 'types/api/dashboard/getAll';++import {+ areArraysEqual,+ buildExistingDynamicVariableQuery,+ extractErrorMessage,+ mergeUniqueStrings,+ onUpdateVariableNode,+ settleVariableFetch,+ VariableGraph,+} from './util';++// ────────────────────────────────────────────────────────────────+// Existing tests+// ────────────────────────────────────────────────────────────────describe('areArraysEqual', () => {it('should return true for equal arrays with same order', () => {@@ -149,3 +176,348 @@ describe('onUpdateVariableNode', () => {expect(visited).toEqual(['namespace', 'service', 'pod']);});});++// ────────────────────────────────────────────────────────────────+// New tests for functions added in recent commits+// ────────────────────────────────────────────────────────────────++function makeDynamicVar(+ overrides: Partial<IDashboardVariable> & { id: string },+): IDashboardVariable {+ return {+ name: overrides.id,+ description: '',+ type: 'DYNAMIC',+ sort: 'DISABLED',+ multiSelect: false,+ showALLOption: false,+ allSelected: false,+ dynamicVariablesAttribute: 'attr',+ selectedValue: 'some-value',+ ...overrides,+ } as IDashboardVariable;+}++describe('mergeUniqueStrings', () => {+ it('should merge two arrays and deduplicate', () => {+ expect(mergeUniqueStrings(['a', 'b'], ['b', 'c'])).toEqual(['a', 'b', 'c']);+ });++ it('should convert numbers and booleans to strings', () => {+ expect(mergeUniqueStrings([1, true, 'hello'], [2, false])).toEqual([+ '1',+ 'true',+ 'hello',+ '2',+ 'false',+ ]);+ });++ it('should deduplicate when number and its string form both appear', () => {+ expect(mergeUniqueStrings([42], ['42'])).toEqual(['42']);+ });++ it('should handle a single array', () => {+ expect(mergeUniqueStrings(['x', 'y', 'x'])).toEqual(['x', 'y']);+ });++ it('should handle three or more arrays', () => {+ expect(mergeUniqueStrings(['a'], ['b'], ['c'], ['a', 'c'])).toEqual([+ 'a',+ 'b',+ 'c',+ ]);+ });++ it('should return empty array when no arrays are provided', () => {+ expect(mergeUniqueStrings()).toEqual([]);+ });++ it('should return empty array when all input arrays are empty', () => {+ expect(mergeUniqueStrings([], [], [])).toEqual([]);+ });++ it('should preserve order of first occurrence', () => {+ expect(mergeUniqueStrings(['c', 'a'], ['b', 'a'])).toEqual(['c', 'a', 'b']);+ });+});++describe('buildExistingDynamicVariableQuery', () => {+ // --- Guard clauses ---+ it('should return empty string when existingVariables is null', () => {+ expect(buildExistingDynamicVariableQuery(null, 'v1', true)).toBe('');+ });++ it('should return empty string when hasDynamicAttribute is false', () => {+ const variables = { v2: makeDynamicVar({ id: 'v2' }) };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', false)).toBe('');+ });++ // --- Eligibility filtering ---+ it('should skip the current variable (same id)', () => {+ const variables = {+ v1: makeDynamicVar({+ id: 'v1',+ dynamicVariablesAttribute: 'ns',+ selectedValue: 'prod',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip non-DYNAMIC variables', () => {+ const variables = {+ v2: makeDynamicVar({ id: 'v2', type: 'QUERY' as any }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip variables without dynamicVariablesAttribute', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: undefined,+ selectedValue: 'val',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip variables with null selectedValue', () => {+ const variables = {+ v2: makeDynamicVar({ id: 'v2', selectedValue: null }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip variables with empty string selectedValue', () => {+ const variables = {+ v2: makeDynamicVar({ id: 'v2', selectedValue: '' }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip variables with empty array selectedValue', () => {+ const variables = {+ v2: makeDynamicVar({ id: 'v2', selectedValue: [] }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should skip variables where showALLOption and allSelected are both true', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ showALLOption: true,+ allSelected: true,+ dynamicVariablesAttribute: 'ns',+ selectedValue: 'prod',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });++ it('should include variable with showALLOption true but allSelected false', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ showALLOption: true,+ allSelected: false,+ dynamicVariablesAttribute: 'ns',+ selectedValue: 'prod',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "ns = 'prod'",+ );+ });++ // --- Value formatting ---+ it('should quote string values in the query', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'k8s.namespace.name',+ selectedValue: 'zeus',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "k8s.namespace.name = 'zeus'",+ );+ });++ it('should leave numeric values unquoted', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'http.status_code',+ selectedValue: '200',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ 'http.status_code = 200',+ );+ });++ it('should escape single quotes in string values', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'user.name',+ selectedValue: "O'Brien",+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "user.name = 'O\\'Brien'",+ );+ });++ it('should build an IN clause for array selectedValue with multiple items', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'k8s.namespace.name',+ selectedValue: ['zeus', 'gene'],+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "k8s.namespace.name IN ['zeus', 'gene']",+ );+ });++ it('should handle mix of numeric and string values in IN clause', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'http.status_code',+ selectedValue: ['200', 'unknown'],+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "http.status_code IN [200, 'unknown']",+ );+ });++ it('should filter out empty string values from array', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'region',+ selectedValue: ['us-east', '', 'eu-west'],+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "region IN ['us-east', 'eu-west']",+ );+ });++ // --- Multiple siblings ---+ it('should join multiple sibling variables with AND', () => {+ const variables = {+ v2: makeDynamicVar({+ id: 'v2',+ dynamicVariablesAttribute: 'k8s.namespace.name',+ selectedValue: ['zeus', 'gene'],+ }),+ v3: makeDynamicVar({+ id: 'v3',+ dynamicVariablesAttribute: 'doc_op_type',+ selectedValue: 'test',+ }),+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe(+ "k8s.namespace.name IN ['zeus', 'gene'] AND doc_op_type = 'test'",+ );+ });++ it('should return empty string when no variables are eligible', () => {+ const variables = {+ v1: makeDynamicVar({ id: 'v1' }), // same as current — skipped+ v2: makeDynamicVar({ id: 'v2', type: 'QUERY' as any }), // not DYNAMIC+ v3: makeDynamicVar({ id: 'v3', selectedValue: null }), // no value+ };+ expect(buildExistingDynamicVariableQuery(variables, 'v1', true)).toBe('');+ });+});++describe('settleVariableFetch', () => {+ const mockGetSnapshot = variableFetchStore.getSnapshot as jest.Mock;+ const mockComplete = onVariableFetchComplete as jest.Mock;+ const mockFailure = onVariableFetchFailure as jest.Mock;++ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('should no-op when name is undefined', () => {+ settleVariableFetch(undefined, 'complete');+ expect(mockGetSnapshot).not.toHaveBeenCalled();+ expect(mockComplete).not.toHaveBeenCalled();+ expect(mockFailure).not.toHaveBeenCalled();+ });++ it.each(['idle', 'waiting', 'error', undefined] as const)(+ 'should no-op when variable state is %s',+ (state) => {+ mockGetSnapshot.mockReturnValue({ states: { myVar: state } });+ settleVariableFetch('myVar', 'complete');+ expect(mockComplete).not.toHaveBeenCalled();+ expect(mockFailure).not.toHaveBeenCalled();+ },+ );++ it('should call onVariableFetchComplete when state is loading and outcome is complete', () => {+ mockGetSnapshot.mockReturnValue({ states: { myVar: 'loading' } });+ settleVariableFetch('myVar', 'complete');+ expect(mockComplete).toHaveBeenCalledWith('myVar');+ expect(mockFailure).not.toHaveBeenCalled();+ });++ it('should call onVariableFetchComplete when state is revalidating and outcome is complete', () => {+ mockGetSnapshot.mockReturnValue({ states: { myVar: 'revalidating' } });+ settleVariableFetch('myVar', 'complete');+ expect(mockComplete).toHaveBeenCalledWith('myVar');+ expect(mockFailure).not.toHaveBeenCalled();+ });++ it('should call onVariableFetchFailure when state is loading and outcome is failure', () => {+ mockGetSnapshot.mockReturnValue({ states: { myVar: 'loading' } });+ settleVariableFetch('myVar', 'failure');+ expect(mockFailure).toHaveBeenCalledWith('myVar');+ expect(mockComplete).not.toHaveBeenCalled();+ });++ it('should call onVariableFetchFailure when state is revalidating and outcome is failure', () => {+ mockGetSnapshot.mockReturnValue({ states: { myVar: 'revalidating' } });+ settleVariableFetch('myVar', 'failure');+ expect(mockFailure).toHaveBeenCalledWith('myVar');+ expect(mockComplete).not.toHaveBeenCalled();+ });+});++describe('extractErrorMessage', () => {+ const FALLBACK_MESSAGE =+ 'Please make sure configuration is valid and you have required setup and permissions';++ it('should return SOMETHING_WENT_WRONG when error is null', () => {+ expect(extractErrorMessage(null)).toBe('Something went wrong');+ });++ it('should return the error message when it exists', () => {+ expect(extractErrorMessage({ message: 'Query timeout' })).toBe(+ 'Query timeout',+ );+ });++ it('should return fallback when error object has no message property', () => {+ expect(extractErrorMessage({})).toBe(FALLBACK_MESSAGE);+ });++ it('should return fallback when error.message is empty string', () => {+ expect(extractErrorMessage({ message: '' })).toBe(FALLBACK_MESSAGE);+ });++ it('should return fallback when error.message is undefined', () => {+ expect(extractErrorMessage({ message: undefined })).toBe(FALLBACK_MESSAGE);+ });+});diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.tsindex 30fc50bd70..f14917bbe2 100644--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts@@ -1,17 +1,11 @@-import { IDashboardVariable } from 'types/api/dashboard/getAll';+import { VariableItemProps } from '../VariableItem';export interface VariableSelectStrategy {handleChange(params: {value: string | string[];- variableData: IDashboardVariable;+ variableData: VariableItemProps['variableData'];+ onValueUpdate: VariableItemProps['onValueUpdate'];optionsData: (string | number | boolean)[];allAvailableOptionStrings: string[];- onValueUpdate: (- name: string,- id: string,- value: IDashboardVariable['selectedValue'],- allSelected: boolean,- haveCustomValuesSelected?: boolean,- ) => void;}): void;}diff --git a/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx b/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsxindex 3576c0f32a..098eba9aa2 100644--- a/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx+++ b/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx@@ -17,6 +17,19 @@ import { IDashboardVariable } from 'types/api/dashboard/getAll';import DynamicVariableInput from '../DashboardVariablesSelection/DynamicVariableInput';+// Mock useVariableFetchState to return "fetching" state so useQuery is enabled+jest.mock('hooks/dashboard/useVariableFetchState', () => ({+ useVariableFetchState: (): Record<string, unknown> => ({+ variableFetchCycleId: 0,+ variableFetchState: 'loading',+ isVariableSettled: false,+ isVariableFetching: true,+ hasVariableFetchedOnce: false,+ isVariableWaitingForDependencies: false,+ variableDependencyWaitMessage: '',+ }),+}));+// Mock the getFieldValues APIjest.mock('api/dynamicVariables/getFieldValues', () => ({getFieldValues: jest.fn(),@@ -95,7 +108,7 @@ describe('Dynamic Variable Default Behavior', () => {}}if (queryFn) {- queryFn();+ queryFn({ signal: undefined });}}}, [enabled, variableName, dynamicVarsKey]); // Only depend on enabled/keys@@ -234,6 +247,7 @@ describe('Dynamic Variable Default Behavior', () => {'2023-01-01T00:00:00Z','2023-01-02T00:00:00Z','',+ undefined, // signal);});@@ -487,6 +501,7 @@ describe('Dynamic Variable Default Behavior', () => {'2023-01-01T00:00:00Z','2023-01-02T00:00:00Z','',+ undefined, // signal);});diff --git a/frontend/src/container/DashboardContainer/__test__/IntegrationTests.test.tsx b/frontend/src/container/DashboardContainer/__test__/IntegrationTests.test.tsxindex 45326986b6..5d8b2132e7 100644--- a/frontend/src/container/DashboardContainer/__test__/IntegrationTests.test.tsx+++ b/frontend/src/container/DashboardContainer/__test__/IntegrationTests.test.tsx@@ -49,15 +49,11 @@ const mockDashboard = {// Mock the dashboard provider with stable functions to prevent infinite loopsconst mockSetSelectedDashboard = jest.fn();const mockUpdateLocalStorageDashboardVariables = jest.fn();-const mockSetVariablesToGetUpdated = jest.fn();-jest.mock('providers/Dashboard/Dashboard', () => ({useDashboard: (): any => ({selectedDashboard: mockDashboard,setSelectedDashboard: mockSetSelectedDashboard,updateLocalStorageDashboardVariables: mockUpdateLocalStorageDashboardVariables,- variablesToGetUpdated: ['env'], // Stable initial value- setVariablesToGetUpdated: mockSetVariablesToGetUpdated,}),}));diff --git a/frontend/src/container/GridCardLayout/GridCard/index.tsx b/frontend/src/container/GridCardLayout/GridCard/index.tsxindex 0c9c79a87f..8329055896 100644--- a/frontend/src/container/GridCardLayout/GridCard/index.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/index.tsx@@ -318,9 +318,7 @@ function GridCardGraph({version={version}threshold={threshold}headerMenuList={menuList}- isFetchingResponse={- queryResponse.isFetching || variablesToGetUpdated.length > 0- }+ isFetchingResponse={queryResponse.isFetching}setRequestData={setRequestData}onClickHandler={onClickHandler}onDragSelect={onDragSelect}diff --git a/frontend/src/providers/Dashboard/Dashboard.tsx b/frontend/src/providers/Dashboard/Dashboard.tsxindex e8a941c48b..3dab519e54 100644--- a/frontend/src/providers/Dashboard/Dashboard.tsx+++ b/frontend/src/providers/Dashboard/Dashboard.tsx@@ -84,8 +84,6 @@ const DashboardContext = createContext<IDashboardContext>({toScrollWidgetId: '',setToScrollWidgetId: () => {},updateLocalStorageDashboardVariables: () => {},- variablesToGetUpdated: [],- setVariablesToGetUpdated: () => {},dashboardQueryRangeCalled: false,setDashboardQueryRangeCalled: () => {},selectedRowWidgetId: '',@@ -183,10 +181,6 @@ export function DashboardProvider({exact: true,});- const [variablesToGetUpdated, setVariablesToGetUpdated] = useState<string[]>(- [],- );-const [layouts, setLayouts] = useState<Layout[]>([]);const [panelMap, setPanelMap] = useState<@@ -517,8 +511,6 @@ export function DashboardProvider({updatedTimeRef,setToScrollWidgetId,updateLocalStorageDashboardVariables,- variablesToGetUpdated,- setVariablesToGetUpdated,dashboardQueryRangeCalled,setDashboardQueryRangeCalled,selectedRowWidgetId,@@ -541,8 +533,6 @@ export function DashboardProvider({toScrollWidgetId,updateLocalStorageDashboardVariables,currentDashboard,- variablesToGetUpdated,- setVariablesToGetUpdated,dashboardQueryRangeCalled,setDashboardQueryRangeCalled,selectedRowWidgetId,diff --git a/frontend/src/providers/Dashboard/types.ts b/frontend/src/providers/Dashboard/types.tsindex 8d047da0ab..91393ca7c3 100644--- a/frontend/src/providers/Dashboard/types.ts+++ b/frontend/src/providers/Dashboard/types.ts@@ -47,8 +47,7 @@ export interface IDashboardContext {allSelected: boolean,isDynamic?: boolean,) => void;- variablesToGetUpdated: string[];- setVariablesToGetUpdated: React.Dispatch<React.SetStateAction<string[]>>;+ variablesToGetUpdated?: string[];dashboardQueryRangeCalled: boolean;setDashboardQueryRangeCalled: (value: boolean) => void;selectedRowWidgetId: string | null;