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: fixed series visiblity logic, not relying on index now (#10318)
Abhi kumar2d2d0c3d9f19
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/types.ts b/frontend/src/container/DashboardContainer/visualization/panels/types.tsindex 0261db6be3..e081c72035 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/types.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/types.ts@@ -14,11 +14,6 @@ export interface GraphVisibilityState {dataIndex: SeriesVisibilityItem[];}-export interface SeriesVisibilityState {- labels: string[];- visibility: boolean[];-}-/*** Context in which a panel is rendered. Used to vary behavior (e.g. persistence,* interactions) per context.diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/legendVisibilityUtils.test.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/legendVisibilityUtils.test.tsindex fd57fa8581..2af056126a 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/legendVisibilityUtils.test.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/legendVisibilityUtils.test.ts@@ -62,10 +62,10 @@ describe('legendVisibilityUtils', () => {const result = getStoredSeriesVisibility('widget-1');expect(result).not.toBeNull();- expect(result).toEqual({- labels: ['CPU', 'Memory'],- visibility: [true, false],- });+ expect(result).toEqual([+ { label: 'CPU', show: true },+ { label: 'Memory', show: false },+ ]);});it('returns visibility by index including duplicate labels', () => {@@ -85,10 +85,11 @@ describe('legendVisibilityUtils', () => {const result = getStoredSeriesVisibility('widget-1');expect(result).not.toBeNull();- expect(result).toEqual({- labels: ['CPU', 'CPU', 'Memory'],- visibility: [true, false, false],- });+ expect(result).toEqual([+ { label: 'CPU', show: true },+ { label: 'CPU', show: false },+ { label: 'Memory', show: false },+ ]);});it('returns null on malformed JSON in localStorage', () => {@@ -127,10 +128,10 @@ describe('legendVisibilityUtils', () => {const stored = getStoredSeriesVisibility('widget-1');expect(stored).not.toBeNull();- expect(stored).toEqual({- labels: ['CPU', 'Memory'],- visibility: [true, false],- });+ expect(stored).toEqual([+ { label: 'CPU', show: true },+ { label: 'Memory', show: false },+ ]);});it('adds a new widget entry when other widgets already exist', () => {@@ -149,7 +150,7 @@ describe('legendVisibilityUtils', () => {const stored = getStoredSeriesVisibility('widget-new');expect(stored).not.toBeNull();- expect(stored).toEqual({ labels: ['CPU'], visibility: [false] });+ expect(stored).toEqual([{ label: 'CPU', show: false }]);});it('updates existing widget visibility when entry already exists', () => {@@ -175,10 +176,10 @@ describe('legendVisibilityUtils', () => {const stored = getStoredSeriesVisibility('widget-1');expect(stored).not.toBeNull();- expect(stored).toEqual({- labels: ['CPU', 'Memory'],- visibility: [false, true],- });+ expect(stored).toEqual([+ { label: 'CPU', show: false },+ { label: 'Memory', show: true },+ ]);});it('silently handles malformed existing JSON without throwing', () => {@@ -201,10 +202,10 @@ describe('legendVisibilityUtils', () => {const stored = getStoredSeriesVisibility('widget-1');expect(stored).not.toBeNull();- expect(stored).toEqual({- labels: ['x-axis', 'CPU'],- visibility: [true, false],- });+ expect(stored).toEqual([+ { label: 'x-axis', show: true },+ { label: 'CPU', show: false },+ ]);const expected = [{name: 'widget-1',@@ -231,14 +232,12 @@ describe('legendVisibilityUtils', () => {{ label: 'B', show: true },]);- expect(getStoredSeriesVisibility('widget-a')).toEqual({- labels: ['A'],- visibility: [true],- });- expect(getStoredSeriesVisibility('widget-b')).toEqual({- labels: ['B'],- visibility: [true],- });+ expect(getStoredSeriesVisibility('widget-a')).toEqual([+ { label: 'A', show: true },+ ]);+ expect(getStoredSeriesVisibility('widget-b')).toEqual([+ { label: 'B', show: true },+ ]);});it('calls setItem with storage key and stringified visibility states', () => {diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils.tsindex 49f4ca8ece..ccd2c5ee7a 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils.ts@@ -1,10 +1,6 @@import { LOCALSTORAGE } from 'constants/localStorage';-import {- GraphVisibilityState,- SeriesVisibilityItem,- SeriesVisibilityState,-} from '../types';+import { GraphVisibilityState, SeriesVisibilityItem } from '../types';/*** Retrieves the stored series visibility for a specific widget from localStorage by index.@@ -14,7 +10,7 @@ import {*/export function getStoredSeriesVisibility(widgetId: string,-): SeriesVisibilityState | null {+): SeriesVisibilityItem[] | null {try {const storedData = localStorage.getItem(LOCALSTORAGE.GRAPH_VISIBILITY_STATES);@@ -29,10 +25,7 @@ export function getStoredSeriesVisibility(return null;}- return {- labels: widgetState.dataIndex.map((item) => item.label),- visibility: widgetState.dataIndex.map((item) => item.show),- };+ return widgetState.dataIndex;} catch (error) {if (error instanceof SyntaxError) {// If the stored data is malformed, remove itdiff --git a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.tsindex a8fd24da70..786dfe10d2 100644--- a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts+++ b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts@@ -1,4 +1,4 @@-import { SeriesVisibilityState } from 'container/DashboardContainer/visualization/panels/types';+import { SeriesVisibilityItem } from 'container/DashboardContainer/visualization/panels/types';import { getStoredSeriesVisibility } from 'container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils';import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';import { thresholdsDrawHook } from 'lib/uPlotV2/hooks/useThresholdsDrawHook';@@ -238,7 +238,7 @@ export class UPlotConfigBuilder extends ConfigBuilder</*** Returns stored series visibility by index from localStorage when preferences source is LOCAL_STORAGE, otherwise null.*/- private getStoredVisibility(): SeriesVisibilityState | null {+ private getStoredVisibility(): SeriesVisibilityItem[] | null {if (this.widgetId &&this.selectionPreferencesSource === SelectionPreferencesSource.LOCAL_STORAGE@@ -249,25 +249,109 @@ export class UPlotConfigBuilder extends ConfigBuilder<}/**- * Get legend items with visibility state restored from localStorage if available+ * Derive visibility resolution state from stored preferences and current series:+ * - visibleStoredLabels: labels that should always be visible+ * - hiddenStoredLabels: labels that should always be hidden+ * - hasActivePreference: whether a "mix" preference applies to new labels*/- getLegendItems(): Record<number, LegendItem> {+ // eslint-disable-next-line sonarjs/cognitive-complexity+ private getVisibilityResolutionState(): {+ visibleStoredLabels: Set<string>;+ hiddenStoredLabels: Set<string>;+ hasActivePreference: boolean;+ } {const seriesVisibilityState = this.getStoredVisibility();- const isAnySeriesHidden = !!seriesVisibilityState?.visibility?.some(- (show) => !show,+ if (!seriesVisibilityState || seriesVisibilityState.length === 0) {+ return {+ visibleStoredLabels: new Set<string>(),+ hiddenStoredLabels: new Set<string>(),+ hasActivePreference: false,+ };+ }++ // Single pass over stored items to derive:+ // - visibleStoredLabels: any label that is ever stored as visible+ // - hiddenStoredLabels: labels that are only ever stored as hidden+ // - hasMixPreference: there is at least one visible and one hidden entry+ const visibleStoredLabels = new Set<string>();+ const hiddenStoredLabels = new Set<string>();+ let hasAnyVisible = false;+ let hasAnyHidden = false;++ for (const { label, show } of seriesVisibilityState) {+ if (show) {+ hasAnyVisible = true;+ visibleStoredLabels.add(label);+ // If a label is ever visible, it should not be treated as "only hidden"+ if (hiddenStoredLabels.has(label)) {+ hiddenStoredLabels.delete(label);+ }+ } else {+ hasAnyHidden = true;+ // Only track as hidden if we have not already seen it as visible+ if (!visibleStoredLabels.has(label)) {+ hiddenStoredLabels.add(label);+ }+ }+ }++ const hasMixPreference = hasAnyVisible && hasAnyHidden;++ // Current series labels in this chart.+ const currentSeriesLabels = this.series.map(+ (s: UPlotSeriesBuilder) => s.getConfig().label ?? '',);+ // Check if any stored "visible" label exists in the current series list.+ const hasVisibleIntersection =+ visibleStoredLabels.size > 0 &&+ currentSeriesLabels.some((label) => visibleStoredLabels.has(label));++ // Active preference only when there is a mix AND at least one visible+ // stored label is present in the current series list.+ const hasActivePreference = hasMixPreference && hasVisibleIntersection;++ // We apply stored visibility in two cases:+ // - There is an active preference (mix + intersection), OR+ // - There is no mix (all true or all false) – preserve legacy behavior.+ const shouldApplyStoredVisibility = !hasMixPreference || hasActivePreference;++ if (!shouldApplyStoredVisibility) {+ return {+ visibleStoredLabels: new Set<string>(),+ hiddenStoredLabels: new Set<string>(),+ hasActivePreference,+ };+ }++ return {+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,+ };+ }++ /**+ * Get legend items with visibility state restored from localStorage if available+ */+ getLegendItems(): Record<number, LegendItem> {+ const {+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,+ } = this.getVisibilityResolutionState();+return this.series.reduce((acc, s: UPlotSeriesBuilder, index: number) => {const seriesConfig = s.getConfig();const label = seriesConfig.label ?? '';// +1 because uPlot series 0 is x-axis/time; data series are at 1, 2, ... (also matches stored visibility[0]=time, visibility[1]=first data, ...)const seriesIndex = index + 1;const show = resolveSeriesVisibility({- seriesIndex,seriesShow: seriesConfig.show,seriesLabel: label,- seriesVisibilityState,- isAnySeriesHidden,+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,});acc[seriesIndex] = {@@ -296,22 +380,23 @@ export class UPlotConfigBuilder extends ConfigBuilder<...DEFAULT_PLOT_CONFIG,};- const seriesVisibilityState = this.getStoredVisibility();- const isAnySeriesHidden = !!seriesVisibilityState?.visibility?.some(- (show) => !show,- );+ const {+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,+ } = this.getVisibilityResolutionState();config.series = [{ value: (): string => '' }, // Base series for timestamp- ...this.series.map((s, index) => {+ ...this.series.map((s) => {const series = s.getConfig();// Stored visibility[0] is x-axis/time; data series start at visibility[1]const visible = resolveSeriesVisibility({- seriesIndex: index + 1,seriesShow: series.show,seriesLabel: series.label ?? '',- seriesVisibilityState,- isAnySeriesHidden,+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,});return {...series,diff --git a/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts b/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.tsindex 248c3831fe..593a1bf139 100644--- a/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts+++ b/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts@@ -186,11 +186,10 @@ describe('UPlotConfigBuilder', () => {});it('restores visibility state from localStorage when selectionPreferencesSource is LOCAL_STORAGE', () => {- // Index 0 = x-axis/time; indices 1,2 = data series (Requests, Errors). resolveSeriesVisibility matches by seriesIndex + seriesLabel.- getStoredSeriesVisibilityMock.getStoredSeriesVisibility.mockReturnValue({- labels: ['x-axis', 'Requests', 'Errors'],- visibility: [true, true, false],- });+ getStoredSeriesVisibilityMock.getStoredSeriesVisibility.mockReturnValue([+ { label: 'Requests', show: true },+ { label: 'Errors', show: false },+ ]);const builder = new UPlotConfigBuilder({widgetId: 'widget-1',@@ -202,7 +201,7 @@ describe('UPlotConfigBuilder', () => {const legendItems = builder.getLegendItems();- // When any series is hidden, legend visibility is driven by the stored map+ // When any series is hidden, visibility is driven by stored label-based preferencesexpect(legendItems[1].show).toBe(true);expect(legendItems[2].show).toBe(false);@@ -213,6 +212,109 @@ describe('UPlotConfigBuilder', () => {expect(secondSeries?.show).toBe(false);});+ it('hides new series by default when there is a mixed preference and a visible label matches current series', () => {+ getStoredSeriesVisibilityMock.getStoredSeriesVisibility.mockReturnValue([+ { label: 'Requests', show: true },+ { label: 'Errors', show: false },+ ]);++ const builder = new UPlotConfigBuilder({+ widgetId: 'widget-1',+ selectionPreferencesSource: SelectionPreferencesSource.LOCAL_STORAGE,+ });++ builder.addSeries(createSeriesProps({ label: 'Requests' }));+ builder.addSeries(createSeriesProps({ label: 'Errors' }));+ builder.addSeries(createSeriesProps({ label: 'Latency' }));++ const legendItems = builder.getLegendItems();++ // Stored labels: Requests (visible), Errors (hidden).+ // New label "Latency" should be hidden because there is a mixed preference+ // and "Requests" (a visible stored label) is present in the current series.+ expect(legendItems[1].label).toBe('Requests');+ expect(legendItems[1].show).toBe(true);+ expect(legendItems[2].label).toBe('Errors');+ expect(legendItems[2].show).toBe(false);+ expect(legendItems[3].label).toBe('Latency');+ expect(legendItems[3].show).toBe(false);++ const config = builder.getConfig();+ const [, firstSeries, secondSeries, thirdSeries] = config.series ?? [];++ expect(firstSeries?.label).toBe('Requests');+ expect(firstSeries?.show).toBe(true);+ expect(secondSeries?.label).toBe('Errors');+ expect(secondSeries?.show).toBe(false);+ expect(thirdSeries?.label).toBe('Latency');+ expect(thirdSeries?.show).toBe(false);+ });++ it('shows all series when there is a mixed preference but no visible stored labels match current series', () => {+ getStoredSeriesVisibilityMock.getStoredSeriesVisibility.mockReturnValue([+ { label: 'StoredVisible', show: true },+ { label: 'StoredHidden', show: false },+ ]);++ const builder = new UPlotConfigBuilder({+ widgetId: 'widget-1',+ selectionPreferencesSource: SelectionPreferencesSource.LOCAL_STORAGE,+ });++ // None of these labels intersect with the stored visible label "StoredVisible"+ builder.addSeries(createSeriesProps({ label: 'CPU' }));+ builder.addSeries(createSeriesProps({ label: 'Memory' }));++ const legendItems = builder.getLegendItems();++ // Mixed preference exists in storage, but since no visible labels intersect+ // with current series, stored preferences are ignored and all are visible.+ expect(legendItems[1].label).toBe('CPU');+ expect(legendItems[1].show).toBe(true);+ expect(legendItems[2].label).toBe('Memory');+ expect(legendItems[2].show).toBe(true);++ const config = builder.getConfig();+ const [, firstSeries, secondSeries] = config.series ?? [];++ expect(firstSeries?.label).toBe('CPU');+ expect(firstSeries?.show).toBe(true);+ expect(secondSeries?.label).toBe('Memory');+ expect(secondSeries?.show).toBe(true);+ });++ it('treats duplicate labels as visible when any stored entry for that label is visible', () => {+ getStoredSeriesVisibilityMock.getStoredSeriesVisibility.mockReturnValue([+ { label: 'CPU', show: true },+ { label: 'CPU', show: false },+ ]);++ const builder = new UPlotConfigBuilder({+ widgetId: 'widget-dup',+ selectionPreferencesSource: SelectionPreferencesSource.LOCAL_STORAGE,+ });++ // Two series with the same label; both should be visible because at least+ // one stored entry for "CPU" is visible.+ builder.addSeries(createSeriesProps({ label: 'CPU' }));+ builder.addSeries(createSeriesProps({ label: 'CPU' }));++ const legendItems = builder.getLegendItems();++ expect(legendItems[1].label).toBe('CPU');+ expect(legendItems[1].show).toBe(true);+ expect(legendItems[2].label).toBe('CPU');+ expect(legendItems[2].show).toBe(true);++ const config = builder.getConfig();+ const [, firstSeries, secondSeries] = config.series ?? [];++ expect(firstSeries?.label).toBe('CPU');+ expect(firstSeries?.show).toBe(true);+ expect(secondSeries?.label).toBe('CPU');+ expect(secondSeries?.show).toBe(true);+ });+it('does not attempt to read stored visibility when using in-memory preferences', () => {const builder = new UPlotConfigBuilder({widgetId: 'widget-1',diff --git a/frontend/src/lib/uPlotV2/utils/seriesVisibility.ts b/frontend/src/lib/uPlotV2/utils/seriesVisibility.tsindex f00f9f8e5b..8474153c13 100644--- a/frontend/src/lib/uPlotV2/utils/seriesVisibility.ts+++ b/frontend/src/lib/uPlotV2/utils/seriesVisibility.ts@@ -1,25 +1,44 @@-import { SeriesVisibilityState } from 'container/DashboardContainer/visualization/panels/types';-+/**+ * Resolve the visibility of a single series based on:+ * - Stored per-series visibility (when applicable)+ * - Whether there is an "active preference" (mix of visible/hidden that matches current series)+ * - The series' own default show flag+ */export function resolveSeriesVisibility({- seriesIndex,seriesShow,seriesLabel,- seriesVisibilityState,- isAnySeriesHidden,+ visibleStoredLabels,+ hiddenStoredLabels,+ hasActivePreference,}: {- seriesIndex: number;seriesShow: boolean | undefined | null;seriesLabel: string;- seriesVisibilityState: SeriesVisibilityState | null;- isAnySeriesHidden: boolean;+ visibleStoredLabels: Set<string> | null;+ hiddenStoredLabels: Set<string> | null;+ hasActivePreference: boolean;}): boolean {- if (- isAnySeriesHidden &&- seriesVisibilityState?.visibility &&- seriesVisibilityState.labels.length > seriesIndex &&- seriesVisibilityState.labels[seriesIndex] === seriesLabel- ) {- return seriesVisibilityState.visibility[seriesIndex] ?? false;+ const isStoredVisible = !!visibleStoredLabels?.has(seriesLabel);+ const isStoredHidden = !!hiddenStoredLabels?.has(seriesLabel);++ // If the label is explicitly stored as visible, always show it.+ if (isStoredVisible) {+ return true;+ }++ // If the label is explicitly stored as hidden (and never stored as visible),+ // always hide it.+ if (isStoredHidden) {+ return false;}++ // "Active preference" means:+ // - There is a mix of visible/hidden in storage, AND+ // - At least one stored *visible* label exists in the current series list.+ // For such a preference, any new/unknown series should be hidden by default.+ if (hasActivePreference) {+ return false;+ }++ // Otherwise fall back to the series' own config or show by default.return seriesShow ?? true;}