From 465bf4cd8ad09748d2701ed6e9994076d63d6282 Mon Sep 17 00:00:00 2001 From: Raj Gahoi Date: Mon, 9 Nov 2026 09:39:08 +0530 Subject: [PATCH 1/3] fix(dashboard): prevent time range race condition on CPU and memory metrics charts (#590) Assign a unique requestId to each cpuUsageRequested and memoryUsageRequested action, echo it back from the server in fulfilled and error responses, and ignore stale responses whose requestId does not match the latest request in the slice. Signed-off-by: Raj Gahoi --- apps/frontend/src/state/epics/valkeyEpics.ts | 8 +-- .../src/state/valkey-features/cpu/cpuSlice.ts | 62 +++++++++++++++---- .../valkey-features/memory/memorySlice.ts | 62 +++++++++++++++---- apps/server/src/actions/cpuUsage.ts | 17 +++-- apps/server/src/actions/memoryUsage.ts | 17 +++-- 5 files changed, 124 insertions(+), 42 deletions(-) diff --git a/apps/frontend/src/state/epics/valkeyEpics.ts b/apps/frontend/src/state/epics/valkeyEpics.ts index eaccd167..504224da 100644 --- a/apps/frontend/src/state/epics/valkeyEpics.ts +++ b/apps/frontend/src/state/epics/valkeyEpics.ts @@ -609,12 +609,12 @@ export const getCpuUsageEpic = () => select(cpuUsageRequested), tap((action) => { try { - const { timeRange, connectionId, clusterId } = action.payload + const { timeRange, connectionId, clusterId, requestId } = action.payload const socket = getSocket() socket.next({ type: action.type, - payload: { connectionId, clusterId, timeRange }, + payload: { connectionId, clusterId, timeRange, requestId }, }) } catch (error) { console.error("[getCpuUsageEpic] Error sending action:", error) @@ -628,12 +628,12 @@ export const getMemoryUsageEpic = () => select(memoryUsageRequested), tap((action) => { try { - const { timeRange, connectionId, clusterId } = action.payload + const { timeRange, connectionId, clusterId, requestId } = action.payload const socket = getSocket() socket.next({ type: action.type, - payload: { connectionId, timeRange, clusterId }, + payload: { connectionId, timeRange, clusterId, requestId }, }) } catch (error) { console.error("[getMemoryUsageEpic] Error sending action:", error) diff --git a/apps/frontend/src/state/valkey-features/cpu/cpuSlice.ts b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.ts index f1ca345f..72cb8130 100644 --- a/apps/frontend/src/state/valkey-features/cpu/cpuSlice.ts +++ b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.ts @@ -1,4 +1,4 @@ -import { createSlice } from "@reduxjs/toolkit" +import { createSlice, type PayloadAction, nanoid } from "@reduxjs/toolkit" import { type JSONObject } from "@common/src/json-utils" import { VALKEY } from "@common/src/constants.ts" import * as R from "ramda" @@ -24,33 +24,66 @@ interface CpuState { data: CpuDataPoint[] error?: JSONObject | null loading?: boolean + lastRequestId?: string } } const initialCpuState: CpuState = {} +interface CpuUsageRequestedPayload { + connectionId: string + clusterId?: string + timeRange?: number + requestId: string +} + +interface CpuUsageFulfilledPayload { + connectionId: string + parsedResponse: unknown + requestId?: string +} + +interface CpuUsageErrorPayload { + connectionId: string + error: JSONObject + requestId?: string +} + const cpuSlice = createSlice({ name: "cpu", initialState: initialCpuState, reducers: { - cpuUsageRequested: (state, action) => { - const { connectionId } = action.payload - if (!state[connectionId]) { - state[connectionId] = { - data: [], - loading: false, + cpuUsageRequested: { + reducer: (state, action: PayloadAction) => { + const { connectionId, requestId } = action.payload + if (!state[connectionId]) { + state[connectionId] = { + data: [], + loading: false, + } } - } - state[connectionId].loading = true + state[connectionId].loading = true + state[connectionId].lastRequestId = requestId + }, + prepare: (payload: { connectionId: string; clusterId?: string; timeRange?: number; requestId?: string }) => ({ + payload: { + ...payload, + requestId: payload.requestId ?? nanoid(), + }, + }), }, - cpuUsageFulfilled: (state, action) => { - const { connectionId, parsedResponse } = action.payload + cpuUsageFulfilled: (state, action: PayloadAction) => { + const { connectionId, parsedResponse, requestId } = action.payload if (!state[connectionId]) { state[connectionId] = { data: [], loading: false, } } + // If a requestId is provided and does not match the latest request, ignore it to prevent race conditions (#590) + if (requestId && state[connectionId].lastRequestId && requestId !== state[connectionId].lastRequestId) { + return + } // Validate that parsedResponse is an array if (Array.isArray(parsedResponse)) { state[connectionId].data = parsedResponse @@ -61,9 +94,12 @@ const cpuSlice = createSlice({ } state[connectionId].loading = false }, - cpuUsageError: (state, action) => { - const { connectionId, error } = action.payload + cpuUsageError: (state, action: PayloadAction) => { + const { connectionId, error, requestId } = action.payload if (state[connectionId]) { + if (requestId && state[connectionId].lastRequestId && requestId !== state[connectionId].lastRequestId) { + return + } state[connectionId].error = error state[connectionId].loading = false } diff --git a/apps/frontend/src/state/valkey-features/memory/memorySlice.ts b/apps/frontend/src/state/valkey-features/memory/memorySlice.ts index 46b3dbea..4031ac0e 100644 --- a/apps/frontend/src/state/valkey-features/memory/memorySlice.ts +++ b/apps/frontend/src/state/valkey-features/memory/memorySlice.ts @@ -1,4 +1,4 @@ -import { createSlice } from "@reduxjs/toolkit" +import { createSlice, type PayloadAction, nanoid } from "@reduxjs/toolkit" import { type JSONObject } from "@common/src/json-utils" import { VALKEY } from "@common/src/constants.ts" import * as R from "ramda" @@ -31,33 +31,66 @@ interface MemoryState { data: MemoryData | null error?: JSONObject | null loading?: boolean + lastRequestId?: string } } const initialMemoryState: MemoryState = {} +interface MemoryUsageRequestedPayload { + connectionId: string + clusterId?: string + timeRange?: number + requestId: string +} + +interface MemoryUsageFulfilledPayload { + connectionId: string + parsedResponse: unknown + requestId?: string +} + +interface MemoryUsageErrorPayload { + connectionId: string + error: JSONObject + requestId?: string +} + const memorySlice = createSlice({ name: "memory", initialState: initialMemoryState, reducers: { - memoryUsageRequested: (state, action) => { - const { connectionId } = action.payload - if (!state[connectionId]) { - state[connectionId] = { - data: null, - loading: false, + memoryUsageRequested: { + reducer: (state, action: PayloadAction) => { + const { connectionId, requestId } = action.payload + if (!state[connectionId]) { + state[connectionId] = { + data: null, + loading: false, + } } - } - state[connectionId].loading = true + state[connectionId].loading = true + state[connectionId].lastRequestId = requestId + }, + prepare: (payload: { connectionId: string; clusterId?: string; timeRange?: number; requestId?: string }) => ({ + payload: { + ...payload, + requestId: payload.requestId ?? nanoid(), + }, + }), }, - memoryUsageFulfilled: (state, action) => { - const { connectionId, parsedResponse } = action.payload + memoryUsageFulfilled: (state, action: PayloadAction) => { + const { connectionId, parsedResponse, requestId } = action.payload if (!state[connectionId]) { state[connectionId] = { data: null, loading: false, } } + // If a requestId is provided and does not match the latest request, ignore it to prevent race conditions (#590) + if (requestId && state[connectionId].lastRequestId && requestId !== state[connectionId].lastRequestId) { + return + } // validating that parsedResponse is an object (not an array, not null) if (parsedResponse && typeof parsedResponse === "object" && !Array.isArray(parsedResponse)) { state[connectionId].data = parsedResponse @@ -68,9 +101,12 @@ const memorySlice = createSlice({ } state[connectionId].loading = false }, - memoryUsageError: (state, action) => { - const { connectionId, error } = action.payload + memoryUsageError: (state, action: PayloadAction) => { + const { connectionId, error, requestId } = action.payload if (state[connectionId]) { + if (requestId && state[connectionId].lastRequestId && requestId !== state[connectionId].lastRequestId) { + return + } state[connectionId].error = error state[connectionId].loading = false } diff --git a/apps/server/src/actions/cpuUsage.ts b/apps/server/src/actions/cpuUsage.ts index 931dbea7..47d5fa2b 100644 --- a/apps/server/src/actions/cpuUsage.ts +++ b/apps/server/src/actions/cpuUsage.ts @@ -11,6 +11,7 @@ const sendCpuUsageFulfilled = ( ws: WebSocket, connectionId: string, parsedResponse: CpuUsageResponse, + requestId?: string, ) => { ws.send( JSON.stringify({ @@ -18,6 +19,7 @@ const sendCpuUsageFulfilled = ( payload: { connectionId, parsedResponse, + requestId, }, }), ) @@ -27,6 +29,7 @@ const sendCpuUsageError = ( ws: WebSocket, connectionId: string, error: unknown, + requestId?: string, ) => { console.error(error) ws.send( @@ -35,6 +38,7 @@ const sendCpuUsageError = ( payload: { connectionId, error: error instanceof Error ? error.message : String(error), + requestId, }, }), ) @@ -43,14 +47,15 @@ const sendCpuUsageError = ( type RequestPayload = { connectionId: string, clusterId: string, - timeRange?: number + timeRange?: number, + requestId?: string, } export const cpuUsageRequested = withDeps( async ({ ws, metricsServerMap, action, connectedNodesByCluster }) => { - const { connectionId, clusterId, timeRange = 12 * MILLISECONDS_IN_AN_HOUR } = action.payload as unknown as RequestPayload + const { connectionId, clusterId, timeRange = 12 * MILLISECONDS_IN_AN_HOUR, requestId } = action.payload as unknown as RequestPayload if (collectorFeaturesDisabled()) { - sendCpuUsageError(ws, connectionId, new Error(KUBERNETES_METRICS_UNAVAILABLE)) + sendCpuUsageError(ws, connectionId, new Error(KUBERNETES_METRICS_UNAVAILABLE), requestId) return } const connectionIds = clusterId ? connectedNodesByCluster.get(clusterId as string) ?? [] : [connectionId] @@ -61,7 +66,7 @@ export const cpuUsageRequested = withDeps( const metricsServerURI = metricsServerMap.get(toNodeId(connectionId))?.metricsURI if (!metricsServerURI) { - sendCpuUsageError(ws, connectionId, new Error("Metrics server URI not found")) + sendCpuUsageError(ws, connectionId, new Error("Metrics server URI not found"), requestId) return } @@ -73,9 +78,9 @@ export const cpuUsageRequested = withDeps( const response = await fetchWithTimeout(url) const parsedResponse: CpuUsageResponse = await response.json() as CpuUsageResponse - sendCpuUsageFulfilled(ws, connectionId, parsedResponse) + sendCpuUsageFulfilled(ws, connectionId, parsedResponse, requestId) } catch (error) { - sendCpuUsageError(ws, connectionId, error) + sendCpuUsageError(ws, connectionId, error, requestId) } }) await Promise.all(promises) diff --git a/apps/server/src/actions/memoryUsage.ts b/apps/server/src/actions/memoryUsage.ts index 7870248d..e48f071b 100644 --- a/apps/server/src/actions/memoryUsage.ts +++ b/apps/server/src/actions/memoryUsage.ts @@ -18,6 +18,7 @@ const sendMemoryUsageFulfilled = ( ws: WebSocket, connectionId: string, parsedResponse: MemoryUsageResponse, + requestId?: string, ) => { ws.send( JSON.stringify({ @@ -25,6 +26,7 @@ const sendMemoryUsageFulfilled = ( payload: { connectionId, parsedResponse, + requestId, }, }), ) @@ -34,6 +36,7 @@ const sendMemoryUsageError = ( ws: WebSocket, connectionId: string, error: unknown, + requestId?: string, ) => { console.error(error) ws.send( @@ -42,6 +45,7 @@ const sendMemoryUsageError = ( payload: { connectionId, error: error instanceof Error ? error.message : String(error), + requestId, }, }), ) @@ -50,14 +54,15 @@ const sendMemoryUsageError = ( type RequestPayload = { connectionId: string, clusterId: string, - timeRange?: number + timeRange?: number, + requestId?: string, } export const memoryUsageRequested = withDeps( async ({ ws, metricsServerMap, action, connectedNodesByCluster }) => { - const { connectionId, clusterId, timeRange = 12 * MILLISECONDS_IN_AN_HOUR } = action.payload as unknown as RequestPayload + const { connectionId, clusterId, timeRange = 12 * MILLISECONDS_IN_AN_HOUR, requestId } = action.payload as unknown as RequestPayload if (collectorFeaturesDisabled()) { - sendMemoryUsageError(ws, connectionId, new Error(KUBERNETES_METRICS_UNAVAILABLE)) + sendMemoryUsageError(ws, connectionId, new Error(KUBERNETES_METRICS_UNAVAILABLE), requestId) return } const connectionIds = clusterId ? connectedNodesByCluster.get(clusterId as string) ?? [] : [connectionId] @@ -67,7 +72,7 @@ export const memoryUsageRequested = withDeps( const metricsServerURI = metricsServerMap.get(toNodeId(connectionId))?.metricsURI if (!metricsServerURI) { - sendMemoryUsageError(ws, connectionId, new Error("Metrics server URI not found")) + sendMemoryUsageError(ws, connectionId, new Error("Metrics server URI not found"), requestId) return } @@ -79,9 +84,9 @@ export const memoryUsageRequested = withDeps( const response = await fetchWithTimeout(url) const parsedResponse: MemoryUsageResponse = await response.json() as MemoryUsageResponse - sendMemoryUsageFulfilled(ws, connectionId, parsedResponse) + sendMemoryUsageFulfilled(ws, connectionId, parsedResponse, requestId) } catch (error) { - sendMemoryUsageError(ws, connectionId, error) + sendMemoryUsageError(ws, connectionId, error, requestId) } }) await Promise.all(promises) From f378a96f4a61fc4c21a1a513ea4db485a8fe1a45 Mon Sep 17 00:00:00 2001 From: Raj Gahoi Date: Thu, 26 Nov 2026 15:19:36 +0530 Subject: [PATCH 2/3] test(frontend): add regression tests for cpu and memory slice requestId correlation Signed-off-by: Raj Gahoi --- .../valkey-features/cpu/cpuSlice.test.ts | 81 ++++++++++++++++ .../memory/memorySlice.test.ts | 96 +++++++++++++++++++ 2 files changed, 177 insertions(+) create mode 100644 apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts create mode 100644 apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts diff --git a/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts new file mode 100644 index 00000000..d699bf8d --- /dev/null +++ b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect } from "vitest" +import cpuReducer, { + cpuUsageRequested, + cpuUsageFulfilled, + cpuUsageError, +} from "./cpuSlice" + +describe("cpuSlice", () => { + const connectionId = "conn-1" + + it("adds a generated requestId via prepare callback when caller does not provide one", () => { + const action = cpuUsageRequested({ connectionId }) + expect(action.payload.requestId).toBeDefined() + expect(typeof action.payload.requestId).toBe("string") + expect(action.payload.requestId.length).toBeGreaterThan(0) + }) + + it("preserves an explicitly provided requestId via prepare callback", () => { + const explicitId = "custom-req-id-123" + const action = cpuUsageRequested({ connectionId, requestId: explicitId }) + expect(action.payload.requestId).toBe(explicitId) + }) + + it("updates state with latest requestId when fulfilled", () => { + const reqAction = cpuUsageRequested({ connectionId, requestId: "req-latest" }) + let state = cpuReducer(undefined, reqAction) + expect(state[connectionId].loading).toBe(true) + expect(state[connectionId].lastRequestId).toBe("req-latest") + + const mockData = [{ timestamp: 1000, value: 42.5 }] + const fulfilledAction = cpuUsageFulfilled({ + connectionId, + parsedResponse: mockData, + requestId: "req-latest", + }) + state = cpuReducer(state, fulfilledAction) + expect(state[connectionId].data).toEqual(mockData) + expect(state[connectionId].loading).toBe(false) + }) + + it("ignores fulfilled response with an old requestId, leaving data unchanged and loading true", () => { + // Initial request 1 + let state = cpuReducer(undefined, cpuUsageRequested({ connectionId, requestId: "req-1" })) + // Initial fulfillment for request 1 + const initialData = [{ timestamp: 1000, value: 20 }] + state = cpuReducer(state, cpuUsageFulfilled({ connectionId, parsedResponse: initialData, requestId: "req-1" })) + expect(state[connectionId].data).toEqual(initialData) + + // Second request 2 sets loading to true + state = cpuReducer(state, cpuUsageRequested({ connectionId, requestId: "req-2" })) + expect(state[connectionId].loading).toBe(true) + expect(state[connectionId].lastRequestId).toBe("req-2") + + // Late arriving fulfillment for request 1 should be ignored + const staleData = [{ timestamp: 2000, value: 99 }] + state = cpuReducer(state, cpuUsageFulfilled({ connectionId, parsedResponse: staleData, requestId: "req-1" })) + expect(state[connectionId].data).toEqual(initialData) + expect(state[connectionId].loading).toBe(true) + }) + + it("ignores error response with an old requestId, leaving error unset and loading true", () => { + // Request 1 then Request 2 + let state = cpuReducer(undefined, cpuUsageRequested({ connectionId, requestId: "req-1" })) + state = cpuReducer(state, cpuUsageRequested({ connectionId, requestId: "req-2" })) + expect(state[connectionId].loading).toBe(true) + + // Stale error for request 1 + const staleError = { message: "stale network error" } + state = cpuReducer(state, cpuUsageError({ connectionId, error: staleError, requestId: "req-1" })) + expect(state[connectionId].error).toBeUndefined() + expect(state[connectionId].loading).toBe(true) + }) + + it("applies error response when requestId matches latest", () => { + let state = cpuReducer(undefined, cpuUsageRequested({ connectionId, requestId: "req-latest" })) + const validError = { message: "valid connection error" } + state = cpuReducer(state, cpuUsageError({ connectionId, error: validError, requestId: "req-latest" })) + expect(state[connectionId].error).toEqual(validError) + expect(state[connectionId].loading).toBe(false) + }) +}) diff --git a/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts b/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts new file mode 100644 index 00000000..c35f04f8 --- /dev/null +++ b/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts @@ -0,0 +1,96 @@ +import { describe, it, expect } from "vitest" +import memoryReducer, { + memoryUsageRequested, + memoryUsageFulfilled, + memoryUsageError, +} from "./memorySlice" + +describe("memorySlice", () => { + const connectionId = "conn-1" + + it("adds a generated requestId via prepare callback when caller does not provide one", () => { + const action = memoryUsageRequested({ connectionId }) + expect(action.payload.requestId).toBeDefined() + expect(typeof action.payload.requestId).toBe("string") + expect(action.payload.requestId.length).toBeGreaterThan(0) + }) + + it("preserves an explicitly provided requestId via prepare callback", () => { + const explicitId = "custom-mem-id-456" + const action = memoryUsageRequested({ connectionId, requestId: explicitId }) + expect(action.payload.requestId).toBe(explicitId) + }) + + it("updates state with latest requestId when fulfilled", () => { + const reqAction = memoryUsageRequested({ connectionId, requestId: "req-latest" }) + let state = memoryReducer(undefined, reqAction) + expect(state[connectionId].loading).toBe(true) + expect(state[connectionId].lastRequestId).toBe("req-latest") + + const mockData = { + used_memory: { + description: "Used memory in bytes", + series: [{ timestamp: 1000, value: 1024000 }], + }, + } + const fulfilledAction = memoryUsageFulfilled({ + connectionId, + parsedResponse: mockData, + requestId: "req-latest", + }) + state = memoryReducer(state, fulfilledAction) + expect(state[connectionId].data).toEqual(mockData) + expect(state[connectionId].loading).toBe(false) + }) + + it("ignores fulfilled response with an old requestId, leaving data unchanged and loading true", () => { + // Initial request 1 + let state = memoryReducer(undefined, memoryUsageRequested({ connectionId, requestId: "req-1" })) + // Initial fulfillment for request 1 + const initialData = { + used_memory: { + description: "Initial memory", + series: [{ timestamp: 1000, value: 500000 }], + }, + } + state = memoryReducer(state, memoryUsageFulfilled({ connectionId, parsedResponse: initialData, requestId: "req-1" })) + expect(state[connectionId].data).toEqual(initialData) + + // Second request 2 sets loading to true + state = memoryReducer(state, memoryUsageRequested({ connectionId, requestId: "req-2" })) + expect(state[connectionId].loading).toBe(true) + expect(state[connectionId].lastRequestId).toBe("req-2") + + // Late arriving fulfillment for request 1 should be ignored + const staleData = { + used_memory: { + description: "Stale memory", + series: [{ timestamp: 2000, value: 9999999 }], + }, + } + state = memoryReducer(state, memoryUsageFulfilled({ connectionId, parsedResponse: staleData, requestId: "req-1" })) + expect(state[connectionId].data).toEqual(initialData) + expect(state[connectionId].loading).toBe(true) + }) + + it("ignores error response with an old requestId, leaving error unset and loading true", () => { + // Request 1 then Request 2 + let state = memoryReducer(undefined, memoryUsageRequested({ connectionId, requestId: "req-1" })) + state = memoryReducer(state, memoryUsageRequested({ connectionId, requestId: "req-2" })) + expect(state[connectionId].loading).toBe(true) + + // Stale error for request 1 + const staleError = { message: "stale memory network error" } + state = memoryReducer(state, memoryUsageError({ connectionId, error: staleError, requestId: "req-1" })) + expect(state[connectionId].error).toBeUndefined() + expect(state[connectionId].loading).toBe(true) + }) + + it("applies error response when requestId matches latest", () => { + let state = memoryReducer(undefined, memoryUsageRequested({ connectionId, requestId: "req-latest" })) + const validError = { message: "valid memory fetch error" } + state = memoryReducer(state, memoryUsageError({ connectionId, error: validError, requestId: "req-latest" })) + expect(state[connectionId].error).toEqual(validError) + expect(state[connectionId].loading).toBe(false) + }) +}) From 482b83216db0cfccb27703e784abfa3b9f97efd5 Mon Sep 17 00:00:00 2001 From: Raj Gahoi Date: Thu, 26 Nov 2026 15:38:32 +0530 Subject: [PATCH 3/3] style(frontend): format regression tests with eslint Signed-off-by: Raj Gahoi --- apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts | 2 +- .../src/state/valkey-features/memory/memorySlice.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts index d699bf8d..47e7ac0b 100644 --- a/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts +++ b/apps/frontend/src/state/valkey-features/cpu/cpuSlice.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest" import cpuReducer, { cpuUsageRequested, cpuUsageFulfilled, - cpuUsageError, + cpuUsageError } from "./cpuSlice" describe("cpuSlice", () => { diff --git a/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts b/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts index c35f04f8..d9ba506b 100644 --- a/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts +++ b/apps/frontend/src/state/valkey-features/memory/memorySlice.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest" import memoryReducer, { memoryUsageRequested, memoryUsageFulfilled, - memoryUsageError, + memoryUsageError } from "./memorySlice" describe("memorySlice", () => {