Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix(infrastructure-monitoring): page reset on switch category & page outside total (#12453)

Vinicius Lourenço5b94d79e4614
diff --git a/frontend/src/components/TanStackTableView/__tests__/useRecoverFromEmptyPage.test.ts b/frontend/src/components/TanStackTableView/__tests__/useRecoverFromEmptyPage.test.ts
new file mode 100644
index 0000000000..9ecd4a8973
--- /dev/null
+++ b/frontend/src/components/TanStackTableView/__tests__/useRecoverFromEmptyPage.test.ts
@@ -0,0 +1,280 @@
+import { renderHook } from '@testing-library/react';
+
+import {
+ useRecoverFromEmptyPage,
+ UseRecoverFromEmptyPageParams,
+} from '../useRecoverFromEmptyPage';
+
+const REPLACE = { history: 'replace' };
+
+function renderRecovery(
+ overrides: Partial<UseRecoverFromEmptyPageParams> = {},
+): { setPage: jest.Mock; rerender: (next?: unknown) => void } {
+ const setPage = jest.fn();
+ const props: UseRecoverFromEmptyPageParams = {
+ page: 1,
+ pageSize: 10,
+ rowCount: 10,
+ total: 100,
+ isFetching: false,
+ setPage,
+ ...overrides,
+ };
+
+ const { rerender } = renderHook(
+ (next: UseRecoverFromEmptyPageParams) => useRecoverFromEmptyPage(next),
+ { initialProps: props },
+ );
+
+ return {
+ setPage,
+ rerender: (next?: unknown): void =>
+ rerender({ ...props, ...(next as Partial<UseRecoverFromEmptyPageParams>) }),
+ };
+}
+
+describe('useRecoverFromEmptyPage', () => {
+ it('leaves the page alone while it still holds rows', () => {
+ const { setPage } = renderRecovery({ page: 3, rowCount: 10 });
+
+ expect(setPage).not.toHaveBeenCalled();
+ });
+
+ it('leaves the page alone on page 1 with no rows at all', () => {
+ const { setPage } = renderRecovery({ page: 1, rowCount: 0, total: 0 });
+
+ expect(setPage).not.toHaveBeenCalled();
+ });
+
+ it('jumps to the last page that holds data when the page is out of range', () => {
+ const { setPage } = renderRecovery({
+ page: 7,
+ pageSize: 10,
+ rowCount: 0,
+ total: 25,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(3, REPLACE);
+ });
+
+ it('replaces the history entry so the back button does not return to the empty page', () => {
+ const { setPage } = renderRecovery({ page: 4, rowCount: 0, total: 10 });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('falls back to page 1 when the total is unknown', () => {
+ const { setPage } = renderRecovery({ page: 5, rowCount: 0, total: 0 });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('steps back one page when the total claims the page should have data', () => {
+ // total says 100 rows exist, yet page 5 came back empty — step back rather
+ // than stall on a page the query cannot actually serve.
+ const { setPage } = renderRecovery({
+ page: 5,
+ pageSize: 10,
+ rowCount: 0,
+ total: 100,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(4, REPLACE);
+ });
+
+ it('clamps a page below the first one', () => {
+ const { setPage } = renderRecovery({ page: 0, rowCount: 10 });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('falls back to page 1 when pageSize is zero', () => {
+ const { setPage } = renderRecovery({
+ page: 5,
+ pageSize: 0,
+ rowCount: 0,
+ total: 100,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('waits for the request to settle before moving the user', () => {
+ const { setPage, rerender } = renderRecovery({
+ page: 3,
+ rowCount: 0,
+ total: 10,
+ isFetching: true,
+ });
+
+ expect(setPage).not.toHaveBeenCalled();
+
+ rerender({ page: 3, rowCount: 0, total: 10, isFetching: false });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('clamps a page below the first one even when the query failed', () => {
+ // A negative offset is what made the request fail (400 "offset cannot be
+ // negative"), so retrying the same page loops forever — clamp regardless.
+ const { setPage } = renderRecovery({
+ page: 0,
+ rowCount: 0,
+ total: 0,
+ isDisabled: true,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('clamps a page below the first one while the query is still in flight', () => {
+ const { setPage } = renderRecovery({
+ page: -2,
+ rowCount: 0,
+ isFetching: true,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(1, REPLACE);
+ });
+
+ it('keeps the page when the query failed so a retry lands where the user was', () => {
+ const { setPage } = renderRecovery({
+ page: 3,
+ rowCount: 0,
+ total: 0,
+ isDisabled: true,
+ });
+
+ expect(setPage).not.toHaveBeenCalled();
+ });
+
+ it('clamps a page below the first one exactly once while the request settles', () => {
+ // The clamp runs ahead of both gates, so a request settling underneath an
+ // uncorrected page must not re-issue the same history rewrite.
+ const { setPage, rerender } = renderRecovery({
+ page: 0,
+ rowCount: 0,
+ total: 0,
+ isFetching: true,
+ });
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+
+ rerender({ page: 0, rowCount: 0, total: 0, isFetching: false });
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops correcting once the corrected page comes back with rows', () => {
+ const { setPage, rerender } = renderRecovery({
+ page: 7,
+ pageSize: 10,
+ rowCount: 0,
+ total: 25,
+ });
+
+ expect(setPage).toHaveBeenCalledWith(3, REPLACE);
+
+ // The correction lands: the query refetches, then resolves with the rows page 3 holds.
+ rerender({ page: 3, pageSize: 10, rowCount: 0, total: 25, isFetching: true });
+ rerender({
+ page: 3,
+ pageSize: 10,
+ rowCount: 5,
+ total: 25,
+ isFetching: false,
+ });
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not correct again while the same page is still being observed', () => {
+ const { setPage, rerender } = renderRecovery({
+ page: 5,
+ pageSize: 10,
+ rowCount: 0,
+ total: 100,
+ });
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+
+ // A refetch cycle that leaves the page untouched — the correction is already in flight.
+ rerender({
+ page: 5,
+ pageSize: 10,
+ rowCount: 0,
+ total: 100,
+ isFetching: true,
+ });
+ rerender({
+ page: 5,
+ pageSize: 10,
+ rowCount: 0,
+ total: 100,
+ isFetching: false,
+ });
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives up on step-backs and jumps to page 1 when the total keeps lying', () => {
+ // `total` claims 400 rows exist, but every page comes back empty. Walking back one
+ // page at a time would cost a request per hop, so bail out to page 1 instead.
+ const { setPage, rerender } = renderRecovery({
+ page: 40,
+ pageSize: 10,
+ rowCount: 0,
+ total: 400,
+ });
+
+ expect(setPage).toHaveBeenNthCalledWith(1, 39, REPLACE);
+
+ rerender({ page: 39, pageSize: 10, rowCount: 0, total: 400 });
+
+ expect(setPage).toHaveBeenNthCalledWith(2, 38, REPLACE);
+
+ rerender({ page: 38, pageSize: 10, rowCount: 0, total: 400 });
+
+ expect(setPage).toHaveBeenNthCalledWith(3, 1, REPLACE);
+ expect(setPage).toHaveBeenCalledTimes(3);
+ });
+
+ it('corrects again when the user returns to a page that is still empty', () => {
+ const { setPage, rerender } = renderRecovery({
+ page: 3,
+ pageSize: 10,
+ rowCount: 0,
+ total: 10,
+ });
+
+ expect(setPage).toHaveBeenNthCalledWith(1, 1, REPLACE);
+
+ rerender({ page: 1, pageSize: 10, rowCount: 10, total: 10 });
+ rerender({ page: 3, pageSize: 10, rowCount: 0, total: 10 });
+
+ expect(setPage).toHaveBeenNthCalledWith(2, 1, REPLACE);
+ });
+
+ it('does not re-run the correction when setPage is a fresh function each render', () => {
+ // The hook reads setPage through a ref, so an inline arrow must not turn the
+ // ungated `page < 1` clamp into a per-render history rewrite.
+ const setPage = jest.fn();
+ const { rerender } = renderHook(
+ () =>
+ useRecoverFromEmptyPage({
+ page: 0,
+ pageSize: 10,
+ rowCount: 0,
+ total: 0,
+ isFetching: false,
+ setPage: (nextPage, options): void => setPage(nextPage, options),
+ }),
+ { initialProps: undefined },
+ );
+
+ rerender(undefined);
+ rerender(undefined);
+
+ expect(setPage).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/components/TanStackTableView/index.tsx b/frontend/src/components/TanStackTableView/index.tsx
index 2f69ef2be8..995f77a6ad 100644
--- a/frontend/src/components/TanStackTableView/index.tsx
+++ b/frontend/src/components/TanStackTableView/index.tsx
@@ -9,6 +9,7 @@ export * from './useCalculatedPageSize';
export * from './useColumnState';
export * from './useColumnStore';
export * from './usePreferredPageSize.store';
+export * from './useRecoverFromEmptyPage';
export * from './useTableParams';
/**
@@ -285,6 +286,51 @@ export * from './useTableParams';
*
* **Pagination shows "Auto" option** when `calculatedPageSize` is passed, allowing users
* to reset to auto-calculated size.
+ *
+ * **`setPage` accepts history options**: `setPage(page, { history: 'replace' })` rewrites the
+ * current history entry instead of pushing a new one. Use `replace` for corrections the user
+ * did not ask for — otherwise the back button walks straight back into the state that was just
+ * corrected. Only applies when the page is synced to the URL; local (non-URL) pages ignore it.
+ *
+ * @example useRecoverFromEmptyPage — send the user back to a page that has data
+ *
+ * When rows disappear underneath the current page (filters narrowed, time range moved, items
+ * deleted), the user is stranded on an empty page they cannot leave by scrolling. This hook
+ * watches the fetched result and corrects the page with `history: 'replace'`, so the back
+ * button does not return to the empty page.
+ *
+ * Correction rules:
+ * - `page < 1` → jump to page 1, even while fetching or disabled. Such a page usually maps to a
+ * negative offset the API rejects (400 `offset cannot be negative`), so the response can never
+ * confirm the page is empty — deferring to it would strand the user on a permanent error.
+ * - Page is empty and not page 1 → go to `min(ceil(total / pageSize), page - 1)`. When `total`
+ * is trustworthy that lands on the last page holding data; when `total` is unknown or zero it
+ * lands on page 1; and when `total` claims this page should have had rows it steps back a
+ * single page. Repeated step-backs give up and jump to page 1 after the second one, so a
+ * badly inflated `total` cannot walk the user down one request at a time.
+ * - Page has rows, or the user is already on page 1 → do nothing (an empty page 1 means there
+ * is genuinely nothing to show).
+ *
+ * Pass `isFetching` so the hook waits for the request to settle, and `isDisabled` so a failed
+ * request is not mistaken for an empty page. Neither gate suppresses the `page < 1` clamp.
+ *
+ * ```tsx
+ * import { useRecoverFromEmptyPage, useTableParams } from 'components/TanStackTableView';
+ *
+ * const { page, limit, setPage } = useTableParams(QUERY_PARAMS, { page: 1, limit: 20 });
+ * const { data, isLoading, isFetching, isError } = useListQuery({ page, limit });
+ *
+ * useRecoverFromEmptyPage({
+ * page,
+ * pageSize: limit,
+ * rowCount: data?.rows.length ?? 0,
+ * total: data?.total ?? 0,
+ * isFetching: isLoading || isFetching,
+ * // Skip correction on errors — no rows there means "request failed", not "page is empty".
+ * isDisabled: isError,
+ * setPage,
+ * });
+ * ```
*/
const TanStackTable = Object.assign(TanStackTableBase, {
Text: TanStackTableText,
diff --git a/frontend/src/components/TanStackTableView/useRecoverFromEmptyPage.ts b/frontend/src/components/TanStackTableView/useRecoverFromEmptyPage.ts
new file mode 100644
index 0000000000..78d0c7db8b
--- /dev/null
+++ b/frontend/src/components/TanStackTableView/useRecoverFromEmptyPage.ts
@@ -0,0 +1,107 @@
+import { useEffect, useRef } from 'react';
+
+import { SetPageOptions } from './useTableParams';
+
+const FIRST_PAGE = 1;
+const REPLACE_HISTORY: SetPageOptions = { history: 'replace' };
+
+/**
+ * How many single-page step-backs to attempt before giving up and going to page 1.
+ *
+ * A step-back only happens when `total` claims the current page should hold data but the
+ * response came back empty. Each hop costs a request, so an inflated `total` on a high page
+ * number would otherwise walk the user down one page at a time behind a spinner.
+ */
+const MAX_STEP_BACKS = 2;
+
+type Correction = {
+ from: number;
+ to: number;
+};
+
+export type UseRecoverFromEmptyPageParams = {
+ page: number;
+ pageSize: number;
+ rowCount: number;
+ total: number;
+ isFetching: boolean;
+ isDisabled?: boolean;
+ setPage: (page: number, options?: SetPageOptions) => void;
+};
+
+export function useRecoverFromEmptyPage({
+ page,
+ pageSize,
+ rowCount,
+ total,
+ isFetching,
+ isDisabled = false,
+ setPage,
+}: UseRecoverFromEmptyPageParams): void {
+ const setPageRef = useRef(setPage);
+ const lastCorrectionRef = useRef<Correction | null>(null);
+ const stepBacksRef = useRef(0);
+
+ useEffect(() => {
+ setPageRef.current = setPage;
+ });
+
+ useEffect(() => {
+ if (lastCorrectionRef.current && lastCorrectionRef.current.from !== page) {
+ lastCorrectionRef.current = null;
+ }
+
+ const correctTo = (nextPage: number): boolean => {
+ if (lastCorrectionRef.current?.to === nextPage) {
+ return false;
+ }
+
+ lastCorrectionRef.current = { from: page, to: nextPage };
+ setPageRef.current(nextPage, REPLACE_HISTORY);
+ return true;
+ };
+
+ // A page below the first one is invalid on its own terms — it usually maps to a
+ // negative offset the API rejects outright, so waiting for a response that will
+ // never arrive (or trusting a failed one) would strand the user for good.
+ if (page < FIRST_PAGE) {
+ stepBacksRef.current = 0;
+ void correctTo(FIRST_PAGE);
+ return;
+ }
+
+ if (isFetching || isDisabled) {
+ return;
+ }
+
+ // The page has data, or there is genuinely nothing to show anywhere.
+ if (rowCount > 0 || page === FIRST_PAGE) {
+ stepBacksRef.current = 0;
+ return;
+ }
+
+ const currentPage = Math.floor(page);
+ const lastPageWithData =
+ pageSize > 0 && total > 0 ? Math.ceil(total / pageSize) : FIRST_PAGE;
+ const nextPage = Math.max(
+ FIRST_PAGE,
+ Math.min(lastPageWithData, currentPage - 1),
+ );
+
+ // `total` disagrees with the response: it says this page should have rows, so the
+ // only safe move is one page back. Cap how often that repeats — every hop is a
+ // request, and a badly inflated `total` would otherwise crawl down from page 40.
+ const isStepBack = nextPage === currentPage - 1;
+
+ if (isStepBack && stepBacksRef.current >= MAX_STEP_BACKS) {
+ if (correctTo(FIRST_PAGE)) {
+ stepBacksRef.current = 0;
+ }
+ return;
+ }
+
+ if (correctTo(nextPage) && isStepBack) {
+ stepBacksRef.current += 1;
+ }
+ }, [isFetching, isDisabled, page, pageSize, rowCount, total]);
+}
diff --git a/frontend/src/components/TanStackTableView/useTableParams.ts b/frontend/src/components/TanStackTableView/useTableParams.ts
index 9b93e74b7c..b3fe4223f7 100644
--- a/frontend/src/components/TanStackTableView/useTableParams.ts
+++ b/frontend/src/components/TanStackTableView/useTableParams.ts
@@ -29,12 +29,16 @@ type Defaults = {
cleanupOnUnmount?: boolean;
};
+export type SetPageOptions = {
+ history?: 'push' | 'replace';
+};
+
export type TableParamsResult = {
page: number;
limit: number;
orderBy: SortState | null;
expanded: ExpandedState;
- setPage: (p: number) => void;
+ setPage: (p: number, options?: SetPageOptions) => void;
setLimit: (l: number) => void;
setOrderBy: (s: SortState | null) => void;
setExpanded: (updaterOrValue: Updater<ExpandedState>) => void;
@@ -249,6 +253,17 @@ export function useTableParams(
[],
);
+ const setUrlPageWithOptions = useCallback(
+ (page: number, options?: SetPageOptions): void => {
+ void setUrlPage(page, options);
+ },
+ [setUrlPage],
+ );
+
+ const setLocalPageValue = useCallback((page: number): void => {
+ setLocalPage(page);
+ }, []);
+
const orderByUrlMemoKey = `${urlOrderBy?.columnName}${urlOrderBy?.order}`;
const prevOrderByRef = useRef<string | null>(null);
@@ -303,7 +318,7 @@ export function useTableParams(
limit: useUrlForLimit ? urlLimit : localLimit,
orderBy: (useUrlForOrderBy ? urlOrderBy : localOrderBy) as SortState | null,
expanded: useUrlForExpanded ? urlExpanded : localExpanded,
- setPage: useUrlForPage ? setUrlPage : setLocalPage,
+ setPage: useUrlForPage ? setUrlPageWithOptions : setLocalPageValue,
setLimit: useUrlForLimit ? setUrlLimit : setLocalLimitWithPersist,
setOrderBy: useUrlForOrderBy ? setUrlOrderBy : setLocalOrderBy,
setExpanded: useUrlForExpanded ? setUrlExpanded : handleSetLocalExpanded,
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
index 0d58ed5c36..82e65cdc19 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
@@ -7,6 +7,7 @@ import TanStackTable, {
TableColumnDef,
useCalculatedPageSize,
useHiddenColumnIds,
+ useRecoverFromEmptyPage,
useTableParams,
} from 'components/TanStackTableView';
import { InfraMonitoringEvents } from 'constants/events';
@@ -136,6 +137,7 @@ export function K8sBaseList<
page: currentPage,
limit: currentPageSize,
setLimit,
+ setPage,
} = useTableParams(
{
page: INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE,
@@ -243,6 +245,16 @@ export function K8sBaseList<
const totalCount = data?.total || 0;
const hasFilters = !!expression?.trim();
+ useRecoverFromEmptyPage({
+ page: currentPage,
+ pageSize: currentPageSize,
+ rowCount: pageData.length,
+ total: totalCount,
+ isFetching: isLoading || isFetching,
+ isDisabled: isError || Boolean(data?.error),
+ setPage,
+ });
+
const getGroupKeyFn = useCallback(
(item: T) => getGroupedByMeta(item, groupBy),
[groupBy],
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
index c7314ec03e..fa91a2bf2f 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
@@ -591,12 +591,14 @@ describe('K8sBaseList', () => {
});
describe('with empty data', () => {
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
const fetchListDataMock = jest.fn<
ReturnType<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>,
Parameters<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>
>();
beforeEach(() => {
+ onUrlUpdateMock.mockClear();
fetchListDataMock.mockClear();
fetchListDataMock.mockResolvedValue({
data: [],
@@ -605,6 +607,7 @@ describe('K8sBaseList', () => {
});
renderComponent<TestItem>({
+ onUrlUpdate: onUrlUpdateMock,
entity: InfraMonitoringEntity.PODS,
eventCategory: InfraMonitoringEvents.Pod,
fetchListData: fetchListDataMock,
@@ -625,6 +628,177 @@ describe('K8sBaseList', () => {
expect(fetchListDataMock).toHaveBeenCalled();
});
});
+
+ it('should not rewrite the page when already on the first page', async () => {
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalled();
+ });
+
+ const pageUpdates = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('page'))
+ .filter(Boolean);
+
+ expect(pageUpdates).toHaveLength(0);
+ });
+ });
+
+ describe('with a page beyond the end of the list', () => {
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
+ const fetchListDataMock = jest.fn<
+ ReturnType<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>,
+ Parameters<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>
+ >();
+
+ // 25 rows exist, so pages 1-3 serve data and page 7 of 10 comes back empty.
+ const rows: TestItem[] = Array.from({ length: 25 }, (_, index) => ({
+ id: `pod-${index + 1}`,
+ }));
+
+ beforeEach(() => {
+ onUrlUpdateMock.mockClear();
+ fetchListDataMock.mockClear();
+ // Offset-aware on purpose: a mock that answers empty for every offset would let
+ // the assertions pass against a page the recovery has already moved on from.
+ fetchListDataMock.mockImplementation(async ({ offset = 0, limit = 10 }) => ({
+ data: rows.slice(offset, offset + limit),
+ total: rows.length,
+ error: null,
+ }));
+
+ renderComponent<TestItem>({
+ onUrlUpdate: onUrlUpdateMock,
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: { page: '7', pageSize: '10' },
+ tableColumns: createTestColumns(),
+ getRowKey: (row): string => row.id,
+ getItemKey: (row): string => row.id,
+ });
+ });
+
+ it('should send the user back to the last page holding data', async () => {
+ // The rows of page 3 on screen are what proves the recovery settled there,
+ // rather than passing through on its way somewhere else.
+ await expect(screen.findByText('pod-21')).resolves.toBeInTheDocument();
+
+ const pageUpdates = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('page'))
+ .filter(Boolean);
+
+ expect(pageUpdates).toStrictEqual(['3']);
+ });
+
+ it('should correct the page in a single hop', async () => {
+ await expect(screen.findByText('pod-21')).resolves.toBeInTheDocument();
+
+ // Only the original out-of-range page and the corrected one are requested.
+ expect(
+ fetchListDataMock.mock.calls.map((call) => call[0].offset),
+ ).toStrictEqual([60, 20]);
+ });
+
+ it('should replace the history entry instead of pushing the correction', async () => {
+ await expect(screen.findByText('pod-21')).resolves.toBeInTheDocument();
+
+ const pageCorrection = onUrlUpdateMock.mock.calls.find(
+ (call) => call[0].searchParams.get('page') === '3',
+ );
+
+ expect(pageCorrection?.[0].options.history).toBe('replace');
+ });
+ });
+
+ describe('with a page below the first one', () => {
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
+ const fetchListDataMock = jest.fn<
+ ReturnType<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>,
+ Parameters<NonNullable<K8sBaseListProps<TestItem>['fetchListData']>>
+ >();
+
+ beforeEach(() => {
+ onUrlUpdateMock.mockClear();
+ fetchListDataMock.mockClear();
+ // page=0 turns into offset=-10, which the API rejects outright — the list
+ // can only recover by clamping the page, never by reading the response.
+ fetchListDataMock.mockImplementation(async ({ offset = 0 }) => {
+ if (offset < 0) {
+ throw new APIError({
+ httpStatusCode: 400,
+ error: {
+ code: 'invalid_input',
+ message: 'offset cannot be negative',
+ url: '',
+ errors: [],
+ },
+ });
+ }
+
+ return { data: [{ id: 'pod-1' }], total: 1, error: null };
+ });
+
+ renderComponent<TestItem>({
+ onUrlUpdate: onUrlUpdateMock,
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: { page: '0', pageSize: '10' },
+ tableColumns: createTestColumns(),
+ getRowKey: (row): string => row.id,
+ getItemKey: (row): string => row.id,
+ });
+ });
+
+ it('should reject the request that carried the negative offset', async () => {
+ await waitFor(() => {
+ expect(
+ fetchListDataMock.mock.calls.some((call) => call[0].offset === -10),
+ ).toBe(true);
+ });
+
+ await expect(
+ fetchListDataMock.mock.results[0].value as Promise<unknown>,
+ ).rejects.toThrow('offset cannot be negative');
+ });
+
+ it('should clamp the page to the first one even though the request failed', async () => {
+ await waitFor(() => {
+ expect(onUrlUpdateMock).toHaveBeenCalled();
+ });
+
+ // Page 1 is the default, so the correction drops the param rather than
+ // writing `page=1`.
+ const pageCorrection = onUrlUpdateMock.mock.calls.find(
+ (call) => call[0].searchParams.get('page') === null,
+ );
+
+ expect(pageCorrection).toBeDefined();
+ expect(pageCorrection?.[0].queryString).toBe('?pageSize=10');
+ });
+
+ it('should replace the history entry instead of pushing the correction', async () => {
+ await waitFor(() => {
+ expect(onUrlUpdateMock).toHaveBeenCalled();
+ });
+
+ const pageCorrection = onUrlUpdateMock.mock.calls.find(
+ (call) => call[0].searchParams.get('page') === null,
+ );
+
+ expect(pageCorrection?.[0].options.history).toBe('replace');
+ });
+
+ it('should refetch with a non-negative offset after clamping', async () => {
+ await waitFor(() => {
+ expect(
+ fetchListDataMock.mock.calls.some((call) => call[0].offset === 0),
+ ).toBe(true);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('pod-1')).toBeInTheDocument();
+ });
+ });
});
describe('with error response', () => {
diff --git a/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx b/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
index 53353ce583..94e3b9fada 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
@@ -47,6 +47,7 @@ import {
useInfraMonitoringCategory,
useInfraMonitoringGroupBy,
useInfraMonitoringOrderBy,
+ useInfraMonitoringPageListing,
useInfraMonitoringSelectedItemParams,
} from './hooks';
@@ -67,6 +68,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
const [, setGroupBy] = useInfraMonitoringGroupBy();
const [, setOrderBy] = useInfraMonitoringOrderBy();
const [, setSelectedItemParams] = useInfraMonitoringSelectedItemParams();
+ const [, setCurrentPage] = useInfraMonitoringPageListing();
const compositeQuery = useGetCompositeQueryParam();
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
@@ -218,6 +220,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
void setSelectedCategory(key as string);
void setOrderBy(null);
void setGroupBy(null);
+ void setCurrentPage(null);
setSelectedItemParams(null);
redirectWithQueryBuilderData({
...currentQuery,
diff --git a/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx
new file mode 100644
index 0000000000..55d183768b
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx
@@ -0,0 +1,128 @@
+import React from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+// eslint-disable-next-line no-restricted-imports
+import { Provider } from 'react-redux';
+import { MemoryRouter } from 'react-router-dom';
+import { MemoryRouter as MemoryRouterV5 } from 'react-router-dom-v5-compat';
+import { TooltipProvider } from '@signozhq/ui/tooltip';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { NuqsTestingAdapter, UrlUpdateEvent } from 'nuqs/adapters/testing';
+import { AppProvider } from 'providers/App/App';
+import { QueryBuilderProvider } from 'providers/QueryBuilder';
+import TimezoneProvider from 'providers/Timezone';
+import store from 'store';
+
+import { K8sCategories } from '../constants';
+import InfraMonitoringK8s from '../InfraMonitoringK8s';
+
+// Quick filters fire their own field APIs and are irrelevant to pagination.
+jest.mock('components/QuickFilters/QuickFilters', () => ({
+ __esModule: true,
+ default: (): JSX.Element => <div data-testid="quick-filters" />,
+}));
+
+// The list owns its own page recovery; stubbing it keeps the page param under the
+// sole control of the category handler being tested here.
+jest.mock('../Base/K8sDynamicList', () => ({
+ __esModule: true,
+ K8sDynamicList: (): JSX.Element => <div data-testid="k8s-dynamic-list" />,
+ default: (): JSX.Element => <div data-testid="k8s-dynamic-list" />,
+}));
+
+// Analytics only; jsdom lacks the Performance navigation entries it reads.
+jest.mock('lib/navigation', () => ({
+ getNavigationReferrer: (): string => 'direct',
+}));
+
+function renderPage(
+ queryParams: Record<string, string>,
+ onUrlUpdate: jest.Mock<void, [UrlUpdateEvent]>,
+): void {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ render(
+ <MemoryRouter>
+ <MemoryRouterV5>
+ <TimezoneProvider>
+ <QueryClientProvider client={queryClient}>
+ <AppProvider>
+ <Provider store={store}>
+ <NuqsTestingAdapter
+ searchParams={queryParams}
+ onUrlUpdate={onUrlUpdate}
+ >
+ <TooltipProvider>
+ <QueryBuilderProvider>
+ <InfraMonitoringK8s />
+ </QueryBuilderProvider>
+ </TooltipProvider>
+ </NuqsTestingAdapter>
+ </Provider>
+ </AppProvider>
+ </QueryClientProvider>
+ </TimezoneProvider>
+ </MemoryRouterV5>
+ </MemoryRouter>,
+ );
+}
+
+describe('InfraMonitoringK8s', () => {
+ describe('when the category changes from a page other than the first', () => {
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
+
+ beforeEach(async () => {
+ onUrlUpdateMock.mockClear();
+
+ renderPage(
+ { category: K8sCategories.PODS, page: '3', pageSize: '10' },
+ onUrlUpdateMock,
+ );
+
+ await screen.findByTestId(`category-${K8sCategories.NODES}`);
+ });
+
+ it('should drop the page so the new category starts at the first one', async () => {
+ fireEvent.click(screen.getByTestId(`category-${K8sCategories.NODES}`));
+
+ // Page 3 of pods says nothing about nodes — keeping it asks the new entity
+ // for an offset it may not have. The param is cleared rather than set to 1,
+ // since an absent page already means the first one.
+ await waitFor(() => {
+ const categorySwitch = onUrlUpdateMock.mock.calls.find(
+ (call) => call[0].searchParams.get('category') === K8sCategories.NODES,
+ );
+
+ expect(categorySwitch).toBeDefined();
+ expect(categorySwitch?.[0].searchParams.get('page')).toBeNull();
+ });
+ });
+
+ it('should keep the page size, which is not category specific', async () => {
+ fireEvent.click(screen.getByTestId(`category-${K8sCategories.NODES}`));
+
+ await waitFor(() => {
+ const categorySwitch = onUrlUpdateMock.mock.calls.find(
+ (call) => call[0].searchParams.get('category') === K8sCategories.NODES,
+ );
+
+ expect(categorySwitch?.[0].searchParams.get('pageSize')).toBe('10');
+ });
+ });
+
+ it('should leave the page alone when the same category is clicked again', async () => {
+ fireEvent.click(screen.getByTestId(`category-${K8sCategories.PODS}`));
+
+ await waitFor(() => {
+ expect(screen.getByTestId('k8s-dynamic-list')).toBeInTheDocument();
+ });
+
+ const droppedPage = onUrlUpdateMock.mock.calls.some(
+ (call) => !call[0].searchParams.has('page'),
+ );
+
+ expect(droppedPage).toBe(false);
+ });
+ });
+});
diff --git a/frontend/src/container/InfraMonitoringK8sV2/hooks.ts b/frontend/src/container/InfraMonitoringK8sV2/hooks.ts
index d4e0804137..33e4bbd0ba 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/hooks.ts
+++ b/frontend/src/container/InfraMonitoringK8sV2/hooks.ts
@@ -34,6 +34,9 @@ export const useInfraMonitoringPageListing = (): UseQueryStateReturn<
> =>
useQueryState(
INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE,
+ // do not use .withDefault here, this can cause bugs when
+ // two hooks of nuqs define default twice, this is also
+ // defined at useTableParams
parseAsInteger.withOptions(defaultNuqsOptions),
);