Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix race in `initializeQB` (#74202)

Romeo Van Snickc84ebe190480
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index 2426a2a70d7..9fbc3410946 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -262,13 +262,24 @@ export async function updateTemplateTagNames(
return query;
}
+// Tracks the most recent initializeQB invocation so that stale, in-flight
+// calls (whose location has been superseded by a newer navigation before they
+// finished awaiting metadata) don't overwrite the QB state with results
+// belonging to the previous URL.
+let latestInitializeQBVersion = 0;
+
async function handleQBInit(
dispatch: Dispatch,
getState: GetState,
{
location,
params,
- }: { location: LocationDescriptorObject; params: QueryParams },
+ isStale,
+ }: {
+ location: LocationDescriptorObject;
+ params: QueryParams;
+ isStale: () => boolean;
+ },
) {
dispatch(resetQB());
dispatch(cancelQuery());
@@ -299,6 +310,10 @@ async function handleQBInit(
getState,
});
+ if (isStale()) {
+ return;
+ }
+
if (isSavedCard(card) && card.archived && !currentUser) {
dispatch(setErrorPage(ARCHIVED_ERROR));
return;
@@ -331,8 +346,16 @@ async function handleQBInit(
});
}
+ if (isStale()) {
+ return;
+ }
+
await dispatch(loadMetadataForCard(card));
+ if (isStale()) {
+ return;
+ }
+
// Populate the metadata store with param_fields from the card response.
// This ensures field filter widgets have has_field_values even when the user
// lacks create-queries permission on the underlying table (GHY-1605).
@@ -380,6 +403,10 @@ async function handleQBInit(
question = question.setLegacyQuery(newQuery);
}
+ if (isStale()) {
+ return;
+ }
+
const finalCard = question.card();
const parameterValues = getParameterValuesForQuestion({
@@ -427,9 +454,14 @@ async function handleQBInit(
export const initializeQB =
(location: LocationDescriptorObject, params: QueryParams) =>
async (dispatch: Dispatch, getState: GetState) => {
+ const version = ++latestInitializeQBVersion;
+ const isStale = () => version !== latestInitializeQBVersion;
try {
- await handleQBInit(dispatch, getState, { location, params });
+ await handleQBInit(dispatch, getState, { location, params, isStale });
} catch (error) {
+ if (isStale()) {
+ return;
+ }
console.warn("initializeQB failed because of an error:", error);
dispatch(setErrorPage(error));
}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
index 80347dbb23e..e737ac0918d 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
@@ -668,6 +668,119 @@ describe("QB Actions > initializeQB", () => {
});
});
+ describe("staleness / overlapping initializeQB calls", () => {
+ function startInit(
+ card: Card,
+ dispatch: jest.Mock,
+ getState: () => ReturnType<typeof createMockState>,
+ ) {
+ return initializeQB(
+ getLocationForCard(card),
+ getQueryParamsForCard(card),
+ )(dispatch, getState);
+ }
+
+ function makeState() {
+ const state = createMockState({
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ }),
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({ can_create_queries: true }),
+ }),
+ });
+ return { state, getState: () => state };
+ }
+
+ it("aborts a stale initializeQB once a newer one is in flight", async () => {
+ const firstCard = createSavedStructuredCard({ id: 1, name: "first" });
+ const secondCard = createSavedStructuredCard({ id: 2, name: "second" });
+
+ const { getState } = makeState();
+ const dispatch = jest.fn((action) => action);
+
+ let resolveFirstLoad!: (card: Card) => void;
+ const firstLoadPromise = new Promise<Card>((resolve) => {
+ resolveFirstLoad = resolve;
+ });
+
+ jest
+ .spyOn(cardActions, "loadCard")
+ .mockReturnValueOnce(firstLoadPromise)
+ .mockReturnValueOnce(Promise.resolve(secondCard as Card));
+
+ fetchMock.get(`path:/api/card/${firstCard.id}`, firstCard);
+ fetchMock.get(`path:/api/card/${secondCard.id}`, secondCard);
+
+ // First init: hangs on loadCard
+ const firstInit = startInit(firstCard as Card, dispatch, getState);
+ await Promise.resolve();
+
+ // Second init runs to completion, superseding the first
+ await startInit(secondCard as Card, dispatch, getState);
+ jest.runAllTimers();
+
+ // Unblock the first init; it should bail out once it sees the version
+ // has been superseded.
+ resolveFirstLoad(firstCard as Card);
+ await firstInit;
+ jest.runAllTimers();
+
+ const initActions = dispatch.mock.calls.filter(
+ (call) => call[0]?.type === "metabase/qb/INITIALIZE_QB",
+ );
+ expect(initActions).toHaveLength(1);
+ expect(initActions[0][0].payload.card.id).toBe(secondCard.id);
+ });
+
+ it("does not dispatch setErrorPage from a stale init even when its card would have errored", async () => {
+ const firstCard = createSavedStructuredCard({
+ id: 1,
+ name: "archived first",
+ archived: true,
+ });
+ const secondCard = createSavedStructuredCard({ id: 2, name: "second" });
+
+ // user=null + archived first card → archived setErrorPage on the stale path
+ const state = createMockState({
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ }),
+ currentUser: null,
+ });
+ const getState = () => state;
+ const dispatch = jest.fn((action) => action);
+
+ let resolveFirstLoad!: (card: Card) => void;
+ const firstLoadPromise = new Promise<Card>((resolve) => {
+ resolveFirstLoad = resolve;
+ });
+
+ jest
+ .spyOn(cardActions, "loadCard")
+ .mockReturnValueOnce(firstLoadPromise)
+ .mockReturnValueOnce(Promise.resolve(secondCard as Card));
+
+ fetchMock.get(`path:/api/card/${firstCard.id}`, firstCard);
+ fetchMock.get(`path:/api/card/${secondCard.id}`, secondCard);
+
+ const firstInit = startInit(firstCard as Card, dispatch, getState);
+ await Promise.resolve();
+
+ await startInit(secondCard as Card, dispatch, getState);
+ jest.runAllTimers();
+
+ resolveFirstLoad(firstCard as Card);
+ await firstInit;
+ jest.runAllTimers();
+
+ const archiveError = setErrorPage(
+ expect.objectContaining({ data: { error_code: "archived" } }),
+ );
+ expect(dispatch).not.toHaveBeenCalledWith(archiveError);
+ });
+ });
+
describe("blank question", () => {
type BlankSetupOpts = Omit<BaseSetupOpts, "location" | "params"> & {
db?: DatabaseId;
diff --git a/frontend/src/metabase/query_builder/actions/navigation.ts b/frontend/src/metabase/query_builder/actions/navigation.ts
index 5cdbcf453f2..9bc76494197 100644
--- a/frontend/src/metabase/query_builder/actions/navigation.ts
+++ b/frontend/src/metabase/query_builder/actions/navigation.ts
@@ -83,7 +83,7 @@ export const popState = createThunkAction(
);
}
- if (location.state.objectId) {
+ if (location.state?.objectId) {
await dispatch(zoomInRow({ objectId: location.state.objectId }));
}
},
@@ -102,19 +102,30 @@ export const locationChanged =
(location: Location, nextLocation: Location, nextParams: QueryParams) =>
(dispatch: Dispatch) => {
if (location !== nextLocation) {
+ // Treat both undefined and null as "no state" — the browser leaves
+ // `history.state` as null for navigations the app didn't initiate (typed
+ // URLs, browser hash changes, cy.visit), while `updateUrl` always sets a
+ // `state.card` object.
+ const isExternalUrlChange = nextLocation.state == null;
+ const urlChanged =
+ getURL(nextLocation, { includeMode: true }) !==
+ getURL(location, { includeMode: true });
if (nextLocation.action === "POP") {
- if (
- getURL(nextLocation, { includeMode: true }) !==
- getURL(location, { includeMode: true })
- ) {
+ if (urlChanged) {
// the browser forward/back button was pressed
-
dispatch(popState(nextLocation));
+ // POP without state means navigation to an externally-set URL (eg.
+ // typing into the address bar, or a hash-only navigation that the
+ // browser handled without a full page reload). Re-run init so the
+ // QB picks up the new query.
+ if (isExternalUrlChange) {
+ dispatch(initializeQB(nextLocation, nextParams));
+ }
}
} else if (
(nextLocation.action === "PUSH" || nextLocation.action === "REPLACE") &&
// ignore PUSH/REPLACE with `state` because they were initiated by the `updateUrl` action
- nextLocation.state === undefined
+ isExternalUrlChange
) {
// a link to a different qb url was clicked
dispatch(initializeQB(nextLocation, nextParams));