The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix timeline events intermittently not rendered (#75566)
Nemanja Glumacb79f6cdd507d
diff --git a/e2e/test/scenarios/organization/timelines-question.cy.spec.js b/e2e/test/scenarios/organization/timelines-question.cy.spec.jsindex 15008de9044..1acc91c0240 100644--- a/e2e/test/scenarios/organization/timelines-question.cy.spec.js+++ b/e2e/test/scenarios/organization/timelines-question.cy.spec.js@@ -272,11 +272,20 @@ describe("scenarios > organization > timelines > question", () => {events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],});+ cy.intercept("GET", "/api/timeline?include=events").as("getTimelines");++ // Aggregate by month so the result is a deterministic ~48-row series that+ // spans the full ORDERS date range. A raw `SELECT TOTAL, CREATED_AT FROM+ // ORDERS` is truncated to the first 2000 (unordered) rows, so the chart's+ // x-domain was non-deterministic and often fell short of the event date+ // (2027-10-20); the event then landed outside the domain, was filtered out+ // of the visible timeline events, and the star marker never rendered.H.visitQuestionAdhoc({dataset_query: {type: "native",native: {- query: "SELECT TOTAL, CREATED_AT FROM ORDERS",+ query:+ "SELECT DATE_TRUNC('month', CREATED_AT) AS CREATED_AT, COUNT(*) AS TOTAL FROM ORDERS GROUP BY DATE_TRUNC('month', CREATED_AT) ORDER BY 1",},database: SAMPLE_DB_ID,},@@ -289,6 +298,8 @@ describe("scenarios > organization > timelines > question", () => {// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usagecy.findByText("Visualization").should("be.visible");+ cy.wait("@getTimelines");+H.echartsIcon("star").should("be.visible");});diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsxnew file mode 100644index 00000000000..00e007082e5--- /dev/null+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx@@ -0,0 +1,71 @@+import { screen, waitFor } from "__support__/ui";+import registerVisualizations from "metabase/visualizations/register";+import {+ createMockTimeline,+ createMockTimelineEvent,+} from "metabase-types/api/mocks";++import { getFetchedTimelines, getVisibleTimelineEventIds } from "../selectors";++import { TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD, setup } from "./test-utils";++registerVisualizations();++const EVENT_ID = 99;++const CARD = TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD;++const TIMELINE = createMockTimeline({+ id: 1,+ // Match the question's collection so showTimelinesForCollection selects it.+ collection_id: CARD.collection_id,+ events: [+ createMockTimelineEvent({+ id: EVENT_ID,+ name: "RC1",+ timestamp: "2025-06-01T00:00:00Z",+ }),+ ],+});++describe("QueryBuilder > timeline events (GHY-3839)", () => {+ it("shows timeline events when the timelines request resolves after the question loads", async () => {+ // Delay /api/timeline so it resolves *after* the question and bookmarks have+ // loaded — i.e. after the effect that calls showTimelinesForCollection has+ // already run once without them. This reproduces the load-order race: if the+ // effect doesn't re-run when the timelines arrive, the event is never added+ // to the visible set and no marker ever renders on the chart.+ const { store } = await setup({+ card: CARD,+ timelines: [TIMELINE],+ timelinesDelay: 200,+ });++ // Guard the race conditions: the timelines must not have loaded yet, so the+ // effect's first run already happened without them. If this fails, bump the+ // delay — otherwise the test wouldn't actually exercise the re-run.+ expect(getFetchedTimelines(store.getState())).toHaveLength(0);+ expect(getVisibleTimelineEventIds(store.getState())).toHaveLength(0);++ // The timelines request resolves.+ await waitFor(() => {+ expect(getFetchedTimelines(store.getState())).toHaveLength(1);+ });++ // Once loaded, the event must become visible on the chart. Without the fix+ // the effect never re-runs and this stays empty — that's the bug. The DOM+ // query forces React to flush the re-render triggered by the late resolve.+ await waitFor(+ () => {+ // Reading the DOM forces testing-library to flush React's pending+ // re-render from the late timelines resolve (queryByTestId, so it+ // doesn't throw if the chart subtree errored out under jsdom).+ screen.queryByTestId("test-container");+ expect(getVisibleTimelineEventIds(store.getState())).toContain(+ EVENT_ID,+ );+ },+ { timeout: 5000 },+ );+ });+});diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsxindex 2441a68ba6b..f06140856a0 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx@@ -346,7 +346,10 @@ type QueryBuilderInnerProps = ReduxProps &function QueryBuilderInner(props: QueryBuilderInnerProps) {useFavicon({ favicon: props.pageFavicon ?? null });- useListTimelinesQuery({ include: "events" });+ const { data: fetchedTimelines, isSuccess: areTimelinesLoaded } =+ useListTimelinesQuery({+ include: "events",+ });const { data: bookmarks = [], isSuccess: areBookmarksLoaded } =useListBookmarksQuery();const [createBookmarkMutation] = useCreateBookmarkMutation();@@ -510,14 +513,22 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {]);useEffect(() => {- if (areBookmarksLoaded && hasQuestion) {+ // Gate on the timelines actually being loaded (not just bookmarks), and+ // re-run when they arrive: showTimelinesForCollection reads the fetched+ // timelines from the store at dispatch time, so running it before the+ // `/api/timeline` request resolves dispatches an empty set and the chart+ // never receives its events. This restores the pre-#73674 `allLoaded`+ // guarantee that was lost when the Timelines.loadList HOC was removed.+ if (areBookmarksLoaded && areTimelinesLoaded && hasQuestion) {showTimelinesForCollection(collectionId);}}, [areBookmarksLoaded,+ areTimelinesLoaded,hasQuestion,collectionId,showTimelinesForCollection,+ fetchedTimelines,]);useEffect(() => {diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsxindex 36c824a01d2..9478d9063ef 100644--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx@@ -38,7 +38,7 @@ import { LOAD_COMPLETE_FAVICON } from "metabase/common/hooks/constants";import { serializeCardForUrl } from "metabase/common/utils/card";import { createMockState } from "metabase/redux/store/mocks";import { checkNotNull } from "metabase/utils/types";-import type { Card, Dataset, UnsavedCard } from "metabase-types/api";+import type { Card, Dataset, Timeline, UnsavedCard } from "metabase-types/api";import {createMockCard,createMockCardQueryMetadata,@@ -237,6 +237,10 @@ interface SetupOpts {// Loosely typed to match react-router's `component` prop: the real// NewModelOptions receives router-injected props (location) the stub omits.newModelOptionsComponent?: ComponentType<any>;+ timelines?: Timeline[];+ // Delay (ms) for the /api/timeline response, used to control its resolution+ // order relative to the question/bookmarks load.+ timelinesDelay?: number;}export const setup = async ({@@ -250,6 +254,8 @@ export const setup = async ({: `#${serializeCardForUrl(card)}`}`,newModelOptionsComponent = TestNewModelOptions,+ timelines = [],+ timelinesDelay,}: SetupOpts) => {setupUserMetabotPermissionsEndpoint();setupDatabasesEndpoints([TEST_DB]);@@ -258,7 +264,7 @@ export const setup = async ({setupPropertiesEndpoints(createMockSettings());setupCollectionsEndpoints({ collections: [] });setupBookmarksEndpoints([]);- setupTimelinesEndpoints([]);+ setupTimelinesEndpoints(timelines, timelinesDelay);setupCollectionByIdEndpoint({ collections: [TEST_COLLECTION] });setupFieldValuesEndpoint(createMockFieldValues({ field_id: Number(ORDERS.QUANTITY) }),@@ -288,7 +294,7 @@ export const setup = async ({const mockEventListener = jest.spyOn(window, "addEventListener");- const { container, history } = renderWithProviders(+ const { container, history, store } = renderWithProviders(<div><Route><Route path="/" component={TestHome} />@@ -334,6 +340,7 @@ export const setup = async ({container,history: checkNotNull(history),mockEventListener,+ store,};};diff --git a/frontend/test/__support__/server-mocks/timeline.ts b/frontend/test/__support__/server-mocks/timeline.tsindex 88a7fec2db1..6721eeada8d 100644--- a/frontend/test/__support__/server-mocks/timeline.ts+++ b/frontend/test/__support__/server-mocks/timeline.ts@@ -2,6 +2,10 @@ import fetchMock from "fetch-mock";import type { Timeline } from "metabase-types/api";-export function setupTimelinesEndpoints(timelines: Timeline[]) {- fetchMock.get("path:/api/timeline", timelines);+export function setupTimelinesEndpoints(timelines: Timeline[], delay?: number) {+ fetchMock.get(+ "path:/api/timeline",+ timelines,+ delay != null ? { delay } : undefined,+ );}