This is an automated email from the ASF dual-hosted git repository.

aminghadersohi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new e60f79ffe28 fix(drill-by): keep the clicked time bucket when drilling 
from a grained temporal axis (#45612)
e60f79ffe28 is described below

commit e60f79ffe2838cf0a543f906a4d5f1c6c4713652
Author: Amin Ghadersohi <[email protected]>
AuthorDate: Mon Nov 16 04:23:05 2026 +0000

    fix(drill-by): keep the clicked time bucket when drilling from a grained 
temporal axis (#45612)
    
    Co-authored-by: Evan Rusackas <[email protected]>
---
 docs/docs/using-superset/exploring-data.mdx        |  32 ++
 .../test/query/convertFilter.test.ts               |  18 +
 .../src/MixedTimeseries/EchartsMixedTimeseries.tsx |  65 ++-
 .../src/MixedTimeseries/transformProps.ts          |   1 +
 .../src/MixedTimeseries/types.ts                   |   1 +
 .../src/Timeseries/EchartsTimeseries.test.tsx      | 144 ++++++-
 .../src/Timeseries/EchartsTimeseries.tsx           |  95 +++--
 .../src/utils/xAxisDrillByFilter.ts                |  97 +++++
 .../EchartsMixedTimeseries.test.tsx                | 224 ++++++++++-
 .../test/Timeseries/EchartsTimeseries.test.tsx     | 165 ++++++++
 .../test/utils/xAxisDrillByFilter.test.ts          | 134 +++++++
 .../components/Chart/DrillBy/DrillByModal.test.tsx | 417 +++++++++++++++++++-
 .../src/components/Chart/DrillBy/DrillByModal.tsx  |  62 +--
 .../Chart/DrillBy/DrillByTemporalFilters.test.tsx  |  68 +++-
 .../FilterControl/AdhocFilter/AdhocFilter.test.ts  |  62 +++
 .../controls/FilterControl/AdhocFilter/index.ts    |  20 +-
 .../AdhocFilterEditPopover.test.tsx                |  15 +
 .../FilterControl/AdhocFilterEditPopover/index.tsx |   6 +-
 ...AdhocFilterEditPopoverSimpleTabContent.test.tsx |  41 ++
 superset/common/query_context_factory.py           |  11 +
 superset/models/helpers.py                         |  50 ++-
 superset/translations/ar/LC_MESSAGES/messages.po   |   4 +
 superset/translations/ca/LC_MESSAGES/messages.po   |   4 +
 superset/translations/cs/LC_MESSAGES/messages.po   |   4 +
 superset/translations/de/LC_MESSAGES/messages.po   |   4 +
 superset/translations/en/LC_MESSAGES/messages.po   |   4 +
 superset/translations/es/LC_MESSAGES/messages.po   |   4 +
 superset/translations/fa/LC_MESSAGES/messages.po   |   4 +
 superset/translations/fi/LC_MESSAGES/messages.po   |   4 +
 superset/translations/fr/LC_MESSAGES/messages.po   |   4 +
 superset/translations/it/LC_MESSAGES/messages.po   |   4 +
 superset/translations/ja/LC_MESSAGES/messages.po   |   4 +
 superset/translations/ko/LC_MESSAGES/messages.po   |   4 +
 superset/translations/lv/LC_MESSAGES/messages.po   |   4 +
 superset/translations/messages.pot                 |   4 +
 superset/translations/mi/LC_MESSAGES/messages.po   |   4 +
 superset/translations/nl/LC_MESSAGES/messages.po   |   4 +
 superset/translations/pl/LC_MESSAGES/messages.po   |   4 +
 superset/translations/pt/LC_MESSAGES/messages.po   |   4 +
 .../translations/pt_BR/LC_MESSAGES/messages.po     |   4 +
 superset/translations/ro/LC_MESSAGES/messages.po   |   4 +
 superset/translations/ru/LC_MESSAGES/messages.po   |   4 +
 superset/translations/sk/LC_MESSAGES/messages.po   |   4 +
 superset/translations/sl/LC_MESSAGES/messages.po   |   4 +
 superset/translations/sr/LC_MESSAGES/messages.po   |   4 +
 .../translations/sr_Latn/LC_MESSAGES/messages.po   |   4 +
 superset/translations/ta/LC_MESSAGES/messages.po   |   4 +
 superset/translations/th/LC_MESSAGES/messages.po   |   4 +
 superset/translations/tr/LC_MESSAGES/messages.po   |   4 +
 superset/translations/uk/LC_MESSAGES/messages.po   |   4 +
 superset/translations/zh/LC_MESSAGES/messages.po   |   4 +
 .../translations/zh_TW/LC_MESSAGES/messages.po     |   4 +
 .../unit_tests/common/test_drill_by_time_column.py | 438 +++++++++++++++++++++
 .../common/test_query_context_factory.py           |  50 +++
 tests/unit_tests/core_tests.py                     |  22 ++
 .../mcp_service/chart/test_chart_utils.py          |  16 +
 56 files changed, 2286 insertions(+), 92 deletions(-)

diff --git a/docs/docs/using-superset/exploring-data.mdx 
b/docs/docs/using-superset/exploring-data.mdx
index 426561aaf27..05e5c3fd413 100644
--- a/docs/docs/using-superset/exploring-data.mdx
+++ b/docs/docs/using-superset/exploring-data.mdx
@@ -489,6 +489,29 @@ The **Custom** time range picker accepts natural language 
expressions alongside
 
 These expressions are evaluated at query time, so saved charts always display 
data relative to the current date.
 
+### Drill By Time Buckets
+
+On time-series charts, **Drill by** from a grained temporal axis keeps the 
clicked
+time bucket, such as a day, week, month, quarter, or year, rather than 
querying the
+chart's entire time range. The drill returns exactly the rows the clicked bar 
or
+point counts: it keeps every time setting of the chart as it is (saved, 
dashboard and
+legacy time ranges, Time Range filters on any date column, the Time Column, 
including
+a dashboard Time Column filter) and adds the bucket as a match on the grained 
axis,
+like Drill to detail does. The backend compares the bucket the chart grouped 
by, with
+the same grain, Time Column, dataset Hours offset and Custom SQL axis 
expression, and
+no time range replaces it. A dashboard **Time grain** filter overrides the 
chart's
+saved grain when determining the clicked bucket. The breadcrumb uses the 
bucket's
+formatted label, including when the temporal axis is forced categorical. Line 
and
+area charts can drill into a bucket without enabling markers, and Mixed 
Timeseries
+uses the clicked query's bucket. Nested drills add their filters to the 
bucket. The
+drill's downloads and **Edit chart** use the same filters; in Explore the 
bucket
+filter shows the bucket start and keeps its grain until its column, operator, 
value,
+or expression type is changed. Picking a date range removes the bucket grain 
and filters the raw dates.
+The Custom SQL tab is unavailable while a filter carries a bucket grain, since 
the
+bucket comparison has no portable raw SQL representation.
+For Custom SQL axes, invalid numeric bucket timestamps (non-finite or outside 
the
+supported datetime range) return a query validation error.
+
 ### Sunburst cross-filtering
 
 Sunburst cross-filters use the underlying hierarchy values, not the formatted
@@ -538,10 +561,19 @@ Other chart types, including Table
 and time-series charts, discard filters on the replaced column, including drill
 predicates that may carry the new column's bucket.
 
+For time-series and Mixed charts, **Edit chart** preserves a drilled time 
bucket even
+when the chart was saved with only a legacy Time Column. The bucket uses the 
dashboard
+Time Column override when present. On a forced-categorical temporal axis, a 
markerless
+Mixed-series click selects the displayed month even when the two queries have 
different months.
+
 Drill-generated filters display their ISO time grain in brackets (for example, 
`[P1M]`).
 Editing the filter's column, operator, value, or expression type clears the 
bucket grain;
 unchanged duplicates retain it.
 
+API temporal-range filters with a time grain compare bounds against the grained
+x-axis column. With a Time Column override, the range follows the selected
+Time Column instead of adding a second range on the original x-axis.
+
 :::resources
 
 - [Chart Walkthroughs](https://docs.preset.io/docs/chart-walkthroughs) - 
Detailed guides for most chart types
diff --git 
a/superset-frontend/packages/superset-ui-core/test/query/convertFilter.test.ts 
b/superset-frontend/packages/superset-ui-core/test/query/convertFilter.test.ts
index 07918c21593..aa1a4f9c0bd 100644
--- 
a/superset-frontend/packages/superset-ui-core/test/query/convertFilter.test.ts
+++ 
b/superset-frontend/packages/superset-ui-core/test/query/convertFilter.test.ts
@@ -49,6 +49,24 @@ describe('convertFilter', () => {
     });
   });
 
+  test('should keep the time grain of a binary filter', () => {
+    expect(
+      convertFilter({
+        expressionType: 'SIMPLE',
+        clause: 'WHERE',
+        subject: 'order_date',
+        operator: '==',
+        comparator: 1727740800000 as unknown as string,
+        timeGrain: TimeGranularity.MONTH,
+      }),
+    ).toEqual({
+      col: 'order_date',
+      op: '==',
+      val: 1727740800000,
+      grain: TimeGranularity.MONTH,
+    });
+  });
+
   test('should convert set filter', () => {
     expect(
       convertFilter({
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx
 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx
index 8844d82e576..f6d27b3dfc7 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useCallback } from 'react';
+import { useCallback, useRef } from 'react';
 import {
   AxisType,
   BinaryQueryObjectFilterClause,
@@ -26,10 +26,17 @@ import {
   getNumberFormatter,
   getTimeFormatter,
 } from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
 import { EchartsMixedTimeseriesChartTransformedProps } from './types';
 import Echart from '../components/Echart';
-import { EventHandlers } from '../types';
+import { EchartsHandler, EventHandlers } from '../types';
 import { formatSeriesName } from '../utils/series';
+import {
+  getCategoryAxisValues,
+  getTemporalBucketDrillByFilter,
+  getTimeAxisDrillByValue,
+  parseTemporalValue,
+} from '../utils/xAxisDrillByFilter';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
 
 export default function EchartsMixedTimeseries({
@@ -49,11 +56,15 @@ export default function EchartsMixedTimeseries({
   onFocusedSeries,
   xValueFormatter,
   xAxis,
+  resolvedTimeGrain,
   refs,
   coltypeMapping,
   onLegendStateChanged,
   onLegendScroll,
 }: EchartsMixedTimeseriesChartTransformedProps) {
+  const echartRef = useRef<EchartsHandler | null>(null);
+  // eslint-disable-next-line no-param-reassign
+  refs.echartRef = echartRef;
   const isFirstQuery = useCallback(
     (seriesIndex: number) => seriesIndex < seriesBreakdown,
     [seriesBreakdown],
@@ -211,6 +222,54 @@ export default function EchartsMixedTimeseries({
             });
           });
         }
+        const xAxisFilters: BinaryQueryObjectFilterClause[] = [];
+        const xAxisColumn =
+          xAxis.label === DTTM_ALIAS
+            ? (formData.extraFormData?.granularity_sqla ??
+              formData.granularitySqla)
+            : xAxis.label;
+        const isTemporalCategory =
+          xAxis.type === AxisType.Category &&
+          coltypeMapping?.[getColumnLabel(xAxis.label)] ===
+            GenericDataType.Temporal;
+        if (
+          (xAxis.type === AxisType.Time || isTemporalCategory) &&
+          xAxisColumn
+        ) {
+          const xValue = getTimeAxisDrillByValue(
+            data,
+            Array.isArray(echartOptions.series)
+              ? echartOptions.series[seriesIndex]
+              : echartOptions.series,
+            data
+              ? undefined
+              : echartRef.current
+                  ?.getEchartInstance()
+                  ?.convertFromPixel({ seriesIndex }, [
+                    eventParams.event.offsetX,
+                    eventParams.event.offsetY,
+                  ]),
+            0,
+            isTemporalCategory,
+            isTemporalCategory && data === undefined
+              ? getCategoryAxisValues(echartRef.current?.getEchartInstance(), 
0)
+              : undefined,
+          );
+          const filter = getTemporalBucketDrillByFilter(
+            // Persist a real column for legacy charts: Explore populates
+            // x_axis on edit, so '__timestamp' would stop resolving there.
+            xAxisColumn,
+            xValue,
+            resolvedTimeGrain,
+            getTimeFormatter(
+              undefined,
+              resolvedTimeGrain,
+            )(parseTemporalValue(xValue)),
+          );
+          if (filter?.grain) {
+            xAxisFilters.push(filter);
+          }
+        }
         const hasCrossFilter =
           (isFirst && groupby.length > 0) || (!isFirst && groupbyB.length > 0);
 
@@ -223,6 +282,7 @@ export default function EchartsMixedTimeseries({
             filters: drillByFilters,
             groupbyFieldName: isFirst ? 'groupby' : 'groupby_b',
             adhocFilterFieldName: isFirst ? 'adhoc_filters' : 
'adhoc_filters_b',
+            ...(xAxisFilters.length > 0 && { xAxisFilters }),
           },
         });
       }
@@ -232,6 +292,7 @@ export default function EchartsMixedTimeseries({
   return (
     <Echart
       refs={refs}
+      ref={echartRef}
       height={height}
       width={width}
       echartOptions={echartOptions}
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
index 121a543aa4d..6c945a019cf 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
@@ -1160,6 +1160,7 @@ export default function transformProps(
     groupby,
     groupbyB,
     seriesBreakdown: rawSeriesA.length,
+    resolvedTimeGrain,
     selectedValues: filterState.selectedValues || [],
     onContextMenu,
     onFocusedSeries,
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/types.ts 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/types.ts
index de1a267aefd..fe72d2b5d97 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/types.ts
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/types.ts
@@ -176,6 +176,7 @@ export type EchartsMixedTimeseriesChartTransformedProps =
       groupbyB: QueryFormColumn[];
       labelMapB: Record<string, string[]>;
       seriesBreakdown: number;
+      resolvedTimeGrain?: TimeGranularity;
       xValueFormatter: TimeFormatter | StringConstructor;
       xAxis: {
         label: string;
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.test.tsx
 
b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.test.tsx
index 7adeb7d35ed..697fbbc4bdd 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.test.tsx
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.test.tsx
@@ -25,6 +25,7 @@ import {
   AxisType,
   createTimeRangeFromGranularity,
   DTTM_ALIAS,
+  getTimeFormatter,
   TimeGranularity,
 } from '@superset-ui/core';
 import { GenericDataType } from '@apache-superset/core/common';
@@ -1477,6 +1478,7 @@ test('drillBy filters by time bucket when a categorical 
axis is forced onto a te
     {
       ...defaultProps,
       onContextMenu: onContextMenuMock,
+      resolvedTimeGrain: TimeGranularity.MONTH,
       formData: {
         ...defaultFormData,
         xAxisForceCategorical: true,
@@ -1509,9 +1511,10 @@ test('drillBy filters by time bucket when a categorical 
axis is forced onto a te
   expect(drillBy.xAxisFilters).toEqual([
     {
       col: 'order_date',
-      op: 'TEMPORAL_RANGE',
-      val: '2021-02-01T00:00:00 : 2021-03-01T00:00:00',
-      formattedVal: '2021-02-01T00:00:00',
+      op: '==',
+      val: Date.UTC(2021, 1, 1),
+      grain: TimeGranularity.MONTH,
+      formattedVal: 'Feb 2021',
     },
   ]);
 });
@@ -1563,6 +1566,141 @@ test('drillBy uses the swapped data index for a 
horizontal time-based axis', asy
   ]);
 });
 
+test('Drill by uses the dashboard time grain for the clicked time-axis 
bucket', async () => {
+  const onContextMenu = jest.fn();
+  render(
+    <EchartsTimeseries
+      {...defaultProps}
+      onContextMenu={onContextMenu}
+      resolvedTimeGrain={TimeGranularity.YEAR}
+      xValueFormatter={getTimeFormatter('%Y')}
+      formData={{
+        ...defaultFormData,
+        granularitySqla: 'order_date',
+        timeGrainSqla: TimeGranularity.MONTH,
+        extraFormData: { time_grain_sqla: TimeGranularity.YEAR },
+      }}
+      xAxis={{ label: DTTM_ALIAS, type: AxisType.Time }}
+    />,
+  );
+
+  await getLatestEchartProps().eventHandlers?.contextmenu?.({
+    componentType: 'series',
+    seriesName: 'Sales',
+    data: [Date.UTC(2003, 0, 1), 1000],
+    name: '2003',
+    event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
+  });
+
+  expect(onContextMenu).toHaveBeenCalledTimes(1);
+  const { drillBy, drillToDetail } = onContextMenu.mock.calls[0][2];
+  // A legacy '__timestamp' bucket resolves to the time column the query
+  // groups by, including a dashboard Time Column override.
+  expect(drillBy.xAxisFilters).toEqual([
+    {
+      col: 'order_date',
+      op: '==',
+      val: Date.UTC(2003, 0, 1),
+      grain: TimeGranularity.YEAR,
+      formattedVal: '2003',
+    },
+  ]);
+  expect(drillToDetail).toContainEqual(
+    expect.objectContaining({ grain: TimeGranularity.YEAR }),
+  );
+});
+
+test.each([
+  [AxisType.Time, TimeGranularity.DAY, OrientationType.Horizontal],
+  [AxisType.Category, TimeGranularity.DAY, OrientationType.Vertical],
+  [AxisType.Category, TimeGranularity.MONTH, OrientationType.Horizontal],
+])(
+  'Drill by uses the dashboard grain after a cross-filter on a %s axis saved 
with %s grain (%s)',
+  async (axisType, savedGrain, orientation) => {
+    const onContextMenu = jest.fn();
+    const timestamp = Date.UTC(2003, 0, 1);
+    render(
+      <EchartsTimeseries
+        {...defaultProps}
+        onContextMenu={onContextMenu}
+        resolvedTimeGrain={TimeGranularity.YEAR}
+        xValueFormatter={getTimeFormatter('%Y')}
+        formData={{
+          ...defaultFormData,
+          orientation,
+          timeGrainSqla: savedGrain,
+          xAxisForceCategorical: axisType === AxisType.Category,
+          extraFormData: {
+            time_grain_sqla: TimeGranularity.YEAR,
+            time_range: '2003-10-01 : 2003-11-01',
+            filters: [{ col: 'deal_size', op: 'IN', val: ['Small'] }],
+          },
+        }}
+        coltypeMapping={{ order_date: GenericDataType.Temporal }}
+        xAxis={{ label: 'order_date', type: axisType }}
+      />,
+    );
+
+    await getLatestEchartProps().eventHandlers?.contextmenu?.({
+      componentType: 'series',
+      seriesName: 'Sales',
+      data:
+        orientation === OrientationType.Horizontal
+          ? [65, timestamp]
+          : [timestamp, 65],
+      name: '2003',
+      event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
+    });
+
+    expect(onContextMenu).toHaveBeenCalledTimes(1);
+    expect(onContextMenu.mock.calls[0][2].drillBy.xAxisFilters).toEqual([
+      {
+        col: 'order_date',
+        op: '==',
+        val: Date.UTC(2003, 0, 1),
+        grain: TimeGranularity.YEAR,
+        formattedVal: '2003',
+      },
+    ]);
+  },
+);
+
+test.each([undefined, 'ship_date'])(
+  'legacy Drill by emits a resolvable bucket column for Edit chart with Time 
Column %s',
+  async timeColumn => {
+    const onContextMenu = jest.fn();
+    render(
+      <EchartsTimeseries
+        {...defaultProps}
+        onContextMenu={onContextMenu}
+        resolvedTimeGrain={TimeGranularity.MONTH}
+        xValueFormatter={getTimeFormatter('%b %Y')}
+        formData={{
+          ...defaultFormData,
+          granularitySqla: 'order_date',
+          extraFormData: timeColumn ? { granularity_sqla: timeColumn } : {},
+        }}
+        xAxis={{ label: DTTM_ALIAS, type: AxisType.Time }}
+      />,
+    );
+    await getLatestEchartProps().eventHandlers?.contextmenu?.({
+      componentType: 'series',
+      seriesName: 'Sales',
+      data: [Date.UTC(2024, 1, 1), 10],
+      event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
+    });
+    expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+      {
+        col: timeColumn ?? 'order_date',
+        op: '==',
+        val: Date.UTC(2024, 1, 1),
+        grain: TimeGranularity.MONTH,
+        formattedVal: 'Feb 2024',
+      },
+    ]);
+  },
+);
+
 const makeVerticalLegend = (orientation: LegendOrientation) =>
   ({
     grid: { bottom: 20, top: 20 },
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx
 
b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx
index 82c7cdfded2..de682163d1e 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx
@@ -56,7 +56,12 @@ import {
   TimeseriesCustomLegend,
 } from './types';
 import { formatSeriesName } from '../utils/series';
-import { getTemporalXAxisDrillByFilter } from '../utils/xAxisDrillByFilter';
+import {
+  getCategoryAxisValues,
+  getTemporalBucketDrillByFilter,
+  getTimeAxisDrillByValue,
+  parseTemporalValue,
+} from '../utils/xAxisDrillByFilter';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
 import { ExtraControls } from '../components/ExtraControls';
 import TimeseriesLegend from './TimeseriesLegend';
@@ -692,42 +697,74 @@ export default function EchartsTimeseries({
         const xAxisFilters: BinaryQueryObjectFilterClause[] = [];
         const xAxisCol =
           // if the xAxis is '__timestamp', granularity_sqla will be the 
column of filter
-          xAxis.label === DTTM_ALIAS ? formData.granularitySqla : xAxis.label;
-        if (data && xAxis.type === AxisType.Time && xAxisCol) {
-          // For horizontal orientation the [x, value] pair is swapped
-          const xValue = Array.isArray(data) ? data[xAxisValueIndex] : data;
-          const xAxisFilter = getTemporalXAxisDrillByFilter(
+          xAxis.label === DTTM_ALIAS
+            ? (formData.extraFormData?.granularity_sqla ??
+              formData.granularitySqla)
+            : xAxis.label;
+        const isTemporalCategory =
+          xAxis.type === AxisType.Category &&
+          coltypeMapping?.[getColumnLabel(xAxis.label)] ===
+            GenericDataType.Temporal;
+        if ((xAxis.type === AxisType.Time || isTemporalCategory) && xAxisCol) {
+          // A markerless line/area event identifies the series but no point.
+          // Snap its pixel coordinate to an actual bucket in that series.
+          const series = ensureIsArray(echartOptions.series)[
+            eventParams.seriesIndex
+          ];
+          const xValue = getTimeAxisDrillByValue(
+            data ??
+              (isTemporalCategory && eventParams.name
+                ? eventParams.name
+                : undefined),
+            series,
+            data
+              ? undefined
+              : echartRef.current
+                  ?.getEchartInstance()
+                  ?.convertFromPixel({ seriesIndex: eventParams.seriesIndex }, 
[
+                    eventParams.event.offsetX,
+                    eventParams.event.offsetY,
+                  ]),
+            xAxisValueIndex,
+            isTemporalCategory,
+            isTemporalCategory && data === undefined
+              ? getCategoryAxisValues(
+                  echartRef.current?.getEchartInstance(),
+                  xAxisValueIndex,
+                )
+              : undefined,
+          );
+          const xAxisFilter = getTemporalBucketDrillByFilter(
+            // Persist a real column for legacy charts: Explore populates
+            // x_axis on edit, so '__timestamp' would stop resolving there.
             xAxisCol,
             xValue,
-            formData.timeGrainSqla,
-            String(xValueFormatter(xValue as number)),
+            resolvedTimeGrain,
+            isTemporalCategory
+              ? getTimeFormatter(
+                  undefined,
+                  resolvedTimeGrain,
+                )(parseTemporalValue(xValue))
+              : String(xValueFormatter(xValue as number)),
           );
-          if (xAxisFilter) {
+          if (
+            xAxisFilter &&
+            (data !== undefined ||
+              (isTemporalCategory && eventParams.name) ||
+              xAxisFilter.grain)
+          ) {
             xAxisFilters.push(xAxisFilter);
           }
         } else if (xAxis.type === AxisType.Category && xAxisCol) {
           const categoryAxisValue = getXAxisValue(data, eventParams.name);
           if (categoryAxisValue !== undefined) {
-            // A category axis can still sit on a temporal column when the
-            // axis is forced categorical; filter by time bucket in that case
-            const xAxisFilter =
-              coltypeMapping?.[getColumnLabel(xAxis.label)] ===
-              GenericDataType.Temporal
-                ? getTemporalXAxisDrillByFilter(
-                    xAxisCol,
-                    categoryAxisValue,
-                    formData.timeGrainSqla,
-                    String(eventParams.name ?? categoryAxisValue),
-                  )
-                : {
-                    col: xAxisCol,
-                    op: '==' as const,
-                    val: categoryAxisValue,
-                    formattedVal: String(categoryAxisValue),
-                  };
-            if (xAxisFilter) {
-              xAxisFilters.push(xAxisFilter);
-            }
+            const xAxisFilter = {
+              col: xAxisCol,
+              op: '==' as const,
+              val: categoryAxisValue,
+              formattedVal: String(categoryAxisValue),
+            };
+            xAxisFilters.push(xAxisFilter);
           }
         }
 
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter.ts
 
b/superset-frontend/plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter.ts
index 57419d196a7..f2e3aa6e83f 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter.ts
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter.ts
@@ -22,6 +22,26 @@ import {
   TimeGranularity,
 } from '@superset-ui/core';
 
+import type { EChartsType } from 'echarts/core';
+import type GlobalModel from 'echarts/types/src/model/Global';
+import type { CartesianAxisModel } from 
'echarts/types/src/coord/cartesian/AxisModel';
+
+/** Read the category domain ECharts collected across all series on the axis. 
*/
+export const getCategoryAxisValues = (
+  chart: EChartsType | undefined,
+  valueIndex = 0,
+): readonly unknown[] | undefined => {
+  // ECharts omits auto-collected categories from getOption(). Use the axis
+  // model so a sparse series shares the same domain as the rendered axis.
+  const model = (
+    chart as unknown as { getModel: () => GlobalModel } | undefined
+  )?.getModel();
+  const axis = model?.getComponent(valueIndex === 1 ? 'yAxis' : 'xAxis', 0) as
+    | CartesianAxisModel
+    | undefined;
+  return axis?.getCategories();
+};
+
 const DAY_MS = 24 * 60 * 60 * 1000;
 
 /**
@@ -165,3 +185,80 @@ export const getTemporalXAxisDrillByFilter = (
     formattedVal,
   };
 };
+
+/**
+ * Build the Drill by filter for a clicked temporal bucket. With a time grain
+ * it matches the grained column, like Drill to detail: the backend compares
+ * the bucket the chart grouped by (same grain, Hours offset and Time Column)
+ * and, unlike a TEMPORAL_RANGE, never replaces it with a query time range, so
+ * the drill keeps every other filter of the chart as the chart applied it.
+ * Without a grain it falls back to an exact match on the timestamp.
+ */
+export const getTemporalBucketDrillByFilter = (
+  col: QueryFormColumn,
+  value: unknown,
+  grain?: TimeGranularity,
+  formattedVal?: string,
+): BinaryQueryObjectFilterClause | undefined => {
+  const bucket = parseTemporalValue(value);
+  if (!col || !bucket) {
+    return undefined;
+  }
+  return grain
+    ? { col, op: '==', val: bucket.getTime(), grain, formattedVal }
+    : { col, op: '==', val: formatNaiveDateTime(bucket), formattedVal };
+};
+
+/** Resolve a markerless line/area click to a real bucket in that series. */
+export const getTimeAxisDrillByValue = (
+  data: unknown,
+  series: unknown,
+  coordinate: unknown,
+  valueIndex = 0,
+  categorical = false,
+  axisCategories: readonly unknown[] = [],
+): unknown => {
+  if (Array.isArray(data)) {
+    return data[valueIndex];
+  }
+  if (typeof data === 'number' || typeof data === 'string') {
+    return data;
+  }
+  const axisValue = Array.isArray(coordinate)
+    ? coordinate[valueIndex]
+    : coordinate;
+  if (
+    typeof axisValue !== 'number' ||
+    !Number.isFinite(axisValue) ||
+    typeof series !== 'object' ||
+    series === null ||
+    !('data' in series) ||
+    !Array.isArray(series.data)
+  ) {
+    return undefined;
+  }
+  if (categorical) {
+    const category = axisCategories[Math.round(axisValue)];
+    if (category === undefined) {
+      return undefined;
+    }
+    const point: unknown = series.data.find(
+      (item: unknown) =>
+        Array.isArray(item) && String(item[valueIndex]) === String(category),
+    );
+    return Array.isArray(point) ? point[valueIndex] : undefined;
+  }
+  let nearest: number | undefined;
+  series.data.forEach((point: unknown) => {
+    const value = Array.isArray(point) ? point[valueIndex] : undefined;
+    if (
+      typeof value === 'number' &&
+      Number.isFinite(value) &&
+      (nearest === undefined ||
+        Math.abs(value - axisValue) < Math.abs(nearest - axisValue))
+    ) {
+      nearest = value;
+    }
+  });
+  return nearest;
+};
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/test/MixedTimeseries/EchartsMixedTimeseries.test.tsx
 
b/superset-frontend/plugins/plugin-chart-echarts/test/MixedTimeseries/EchartsMixedTimeseries.test.tsx
index 08eee33b9af..6a339afecf1 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/test/MixedTimeseries/EchartsMixedTimeseries.test.tsx
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/test/MixedTimeseries/EchartsMixedTimeseries.test.tsx
@@ -19,8 +19,10 @@
 import { render } from '@testing-library/react';
 import {
   ChartDataResponseResult,
+  DTTM_ALIAS,
   DataRecord,
   VizType,
+  TimeGranularity,
 } from '@superset-ui/core';
 import { GenericDataType } from '@apache-superset/core/common';
 import transformProps from '../../src/MixedTimeseries/transformProps';
@@ -30,15 +32,25 @@ import {
   EchartsMixedTimeseriesFormData,
   EchartsMixedTimeseriesProps,
 } from '../../src/MixedTimeseries/types';
-import Echart from '../../src/components/Echart';
+import { EchartsProps } from '../../src/types';
 import { createEchartsTimeseriesTestChartProps } from '../helpers';
 
-jest.mock('../../src/components/Echart', () => ({
-  __esModule: true,
-  default: jest.fn(() => null),
-}));
-
-const mockedEchart = jest.mocked(Echart);
+const mockedEchart = jest.fn<void, [EchartsProps]>();
+const mockMixedChart = { convertFromPixel: jest.fn(), getModel: jest.fn() };
+jest.mock('../../src/components/Echart', () => {
+  const { forwardRef, useImperativeHandle } =
+    jest.requireActual<typeof import('react')>('react');
+  return {
+    __esModule: true,
+    default: forwardRef((props: EchartsProps, ref) => {
+      mockedEchart(props);
+      useImperativeHandle(ref, () => ({
+        getEchartInstance: () => mockMixedChart,
+      }));
+      return null;
+    }),
+  };
+});
 
 const ts1 = 1704067200000;
 const ts2 = 1704153600000;
@@ -84,15 +96,15 @@ function createQueryData(): ChartDataResponseResult {
 
 function setup(
   formDataOverrides: Partial<EchartsMixedTimeseriesFormData> = {},
+  queriesData = [createQueryData(), createQueryData()],
 ) {
-  const queryData = createQueryData();
   const chartProps = createEchartsTimeseriesTestChartProps<
     EchartsMixedTimeseriesFormData,
     EchartsMixedTimeseriesProps
   >({
     defaultFormData: DEFAULT_FORM_DATA as EchartsMixedTimeseriesFormData,
     defaultVizType: 'mixed_timeseries',
-    defaultQueriesData: [queryData, queryData],
+    defaultQueriesData: queriesData,
     formData: {
       colorScheme: 'bnbColors',
       metrics: ['sum__num'],
@@ -103,7 +115,7 @@ function setup(
       viz_type: VizType.MixedTimeseries,
       ...formDataOverrides,
     },
-    queriesData: [queryData, queryData],
+    queriesData,
   });
   const transformed = transformProps(chartProps);
   const setDataMask = jest.fn();
@@ -119,12 +131,17 @@ function setup(
     />,
   );
   const lastCall = mockedEchart.mock.calls[mockedEchart.mock.calls.length - 1];
-  const { eventHandlers } = lastCall[0] as any;
+  const { eventHandlers = {} } = lastCall[0];
   return { eventHandlers, setDataMask, onContextMenu, onFocusedSeries };
 }
 
 beforeEach(() => {
   mockedEchart.mockClear();
+  mockMixedChart.getModel.mockReturnValue({
+    getComponent: jest
+      .fn()
+      .mockReturnValue({ getCategories: () => [ts1, ts2] }),
+  });
 });
 
 test('EchartsMixedTimeseries click emits cross-filter with tail-anchored 
dimension values', () => {
@@ -218,6 +235,189 @@ test('EchartsMixedTimeseries hover focuses and unfocuses 
the series', () => {
   eventHandlers.mouseover({ seriesName: 'sum__num, boy' });
   expect(onFocusedSeries).toHaveBeenLastCalledWith('sum__num, boy');
 
-  eventHandlers.mouseout();
+  eventHandlers.mouseout({});
   expect(onFocusedSeries).toHaveBeenLastCalledWith(null);
 });
+
+test.each([0, 2])(
+  'Mixed Timeseries Drill by carries the bucket for query series %s',
+  async seriesIndex => {
+    const { eventHandlers, onContextMenu } = setup({
+      timeGrainSqla: TimeGranularity.MONTH,
+    });
+    await eventHandlers.contextmenu({
+      data: [ts1, 1],
+      seriesName: 'sum__num, boy',
+      seriesIndex,
+      name: '',
+      event: { stop: jest.fn(), event: { clientX: 11, clientY: 22 } },
+    });
+    expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+      expect.objectContaining({
+        col: 'ds',
+        op: '==',
+        val: Date.UTC(2024, 0, 1),
+        grain: TimeGranularity.MONTH,
+      }),
+    ]);
+    expect(onContextMenu.mock.lastCall[2].drillBy.adhocFilterFieldName).toBe(
+      seriesIndex === 0 ? 'adhoc_filters' : 'adhoc_filters_b',
+    );
+  },
+);
+
+test.each([0, 2])(
+  'Mixed Timeseries markerless Drill by snaps query series %s to its bucket',
+  async seriesIndex => {
+    const { eventHandlers, onContextMenu } = setup({
+      timeGrainSqla: TimeGranularity.MONTH,
+    });
+    mockMixedChart.convertFromPixel.mockReturnValue([ts1 + 1000, 1]);
+    await eventHandlers.contextmenu({
+      seriesName: 'sum__num, boy',
+      seriesIndex,
+      event: {
+        stop: jest.fn(),
+        offsetX: 20,
+        offsetY: 30,
+        event: { clientX: 11, clientY: 22 },
+      },
+    });
+    expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+      expect.objectContaining({
+        col: 'ds',
+        op: '==',
+        val: Date.UTC(2024, 0, 1),
+        grain: TimeGranularity.MONTH,
+      }),
+    ]);
+  },
+);
+
+test('Mixed Timeseries forced categorical temporal Drill by keeps a readable 
bucket', async () => {
+  const { eventHandlers, onContextMenu } = setup({
+    timeGrainSqla: TimeGranularity.MONTH,
+    xAxisForceCategorical: true,
+  });
+  mockMixedChart.convertFromPixel.mockReturnValue([0, 1]);
+  await eventHandlers.contextmenu({
+    seriesName: 'sum__num, boy',
+    seriesIndex: 0,
+    event: {
+      stop: jest.fn(),
+      offsetX: 20,
+      offsetY: 30,
+      event: { clientX: 11, clientY: 22 },
+    },
+  });
+  expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+    {
+      col: 'ds',
+      op: '==',
+      val: Date.UTC(2024, 0, 1),
+      grain: TimeGranularity.MONTH,
+      formattedVal: 'Jan 2024',
+    },
+  ]);
+});
+
+test('ungrained Mixed Timeseries Drill by keeps its series-only scope', async 
() => {
+  const { eventHandlers, onContextMenu } = setup({ timeGrainSqla: undefined });
+  await eventHandlers.contextmenu({
+    data: [ts1, 1],
+    seriesName: 'sum__num, boy',
+    seriesIndex: 0,
+    event: { stop: jest.fn(), event: { clientX: 11, clientY: 22 } },
+  });
+  expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toBeUndefined();
+  expect(onContextMenu.mock.lastCall[2].drillBy.filters).toEqual([
+    expect.objectContaining({ col: 'gender', op: '==', val: 'boy' }),
+  ]);
+});
+
+test.each([undefined, 'ship_date'])(
+  'legacy Mixed Drill by emits a resolvable bucket column for Edit chart with 
Time Column %s',
+  async timeColumn => {
+    const query = createQueryData();
+    const legacyQuery = {
+      ...query,
+      data: query.data.map(({ ds, ...row }) => ({ ...row, [DTTM_ALIAS]: ds })),
+      colnames: [DTTM_ALIAS, ...query.colnames.slice(1)],
+    };
+    const { eventHandlers, onContextMenu } = setup(
+      {
+        x_axis: undefined,
+        granularity_sqla: 'order_date',
+        granularitySqla: 'order_date',
+        timeGrainSqla: TimeGranularity.MONTH,
+        extraFormData: timeColumn ? { granularity_sqla: timeColumn } : {},
+      },
+      [legacyQuery, legacyQuery],
+    );
+    await eventHandlers.contextmenu({
+      data: [ts1, 1],
+      seriesName: 'sum__num, boy',
+      seriesIndex: 2,
+      event: { stop: jest.fn(), event: { clientX: 11, clientY: 22 } },
+    });
+    expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+      {
+        col: timeColumn ?? 'order_date',
+        op: '==',
+        val: ts1,
+        grain: TimeGranularity.MONTH,
+        formattedVal: 'Jan 2024',
+      },
+    ]);
+  },
+);
+
+test('Mixed categorical markerless Drill by uses shared axis categories for a 
sparse query B', async () => {
+  for (const categoryIndex of [1, 2, 0]) {
+    const timestamps = [0, 1, 2].map(month => Date.UTC(2024, month, 1));
+    const query = createQueryData();
+    const queryA = {
+      ...query,
+      data: timestamps.map(ds => ({
+        ds,
+        'sum__num, boy': 1,
+        'sum__num, girl': 2,
+      })),
+    };
+    const queryB = { ...queryA, data: queryA.data.slice(1) };
+    const { eventHandlers, onContextMenu } = setup(
+      { timeGrainSqla: TimeGranularity.MONTH, xAxisForceCategorical: true },
+      [queryA, queryB],
+    );
+    mockMixedChart.getModel.mockReturnValue({
+      getComponent: jest
+        .fn()
+        .mockReturnValue({ getCategories: () => timestamps }),
+    });
+    mockMixedChart.convertFromPixel.mockReturnValue([categoryIndex, 1]);
+    await eventHandlers.contextmenu({
+      seriesName: 'sum__num, boy',
+      seriesIndex: 2,
+      event: {
+        stop: jest.fn(),
+        offsetX: 20,
+        offsetY: 30,
+        event: { clientX: 11, clientY: 22 },
+      },
+    });
+    const filters = onContextMenu.mock.lastCall[2].drillBy.xAxisFilters;
+    if (categoryIndex === 0) {
+      expect(filters).toBeUndefined();
+    } else {
+      expect(filters).toEqual([
+        {
+          col: 'ds',
+          op: '==',
+          val: timestamps[categoryIndex],
+          grain: TimeGranularity.MONTH,
+          formattedVal: categoryIndex === 1 ? 'Feb 2024' : 'Mar 2024',
+        },
+      ]);
+    }
+  }
+});
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/EchartsTimeseries.test.tsx
 
b/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/EchartsTimeseries.test.tsx
index 46e81e48a63..93c42acfe61 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/EchartsTimeseries.test.tsx
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/EchartsTimeseries.test.tsx
@@ -20,6 +20,7 @@ import { fireEvent, render, screen, waitFor } from 
'@testing-library/react';
 import '@testing-library/jest-dom';
 import { AxisType, DTTM_ALIAS, TimeGranularity } from '@superset-ui/core';
 import { supersetTheme, ThemeProvider } from '@apache-superset/core/theme';
+import { GenericDataType } from '@apache-superset/core/common';
 import { logging } from '@apache-superset/core/utils';
 import type { ECElementEvent } from 'echarts/types/src/util/types';
 import EchartsTimeseries from '../../src/Timeseries/EchartsTimeseries';
@@ -941,6 +942,170 @@ test.each([undefined, 'PT6H' as TimeGranularity])(
   },
 );
 
+test.each(['line', 'area', 'categorical line'])(
+  'Drill by snaps a markerless %s to the clicked temporal bucket',
+  async seriesType => {
+    const onContextMenu = jest.fn();
+    const timestamp = Date.UTC(2003, 9, 1);
+    renderTimeseries({
+      onContextMenu,
+      groupby: [],
+      resolvedTimeGrain: TimeGranularity.MONTH,
+      formData: { ...DEFAULT_FORM_DATA, granularitySqla: 'order_date' },
+      xAxis: {
+        label: 'order_date',
+        type:
+          seriesType === 'categorical line' ? AxisType.Category : 
AxisType.Time,
+      },
+      coltypeMapping: { order_date: GenericDataType.Temporal },
+      echartOptions: {
+        series: [
+          {
+            type: 'line',
+            showSymbol: false,
+            ...(seriesType === 'area' ? { areaStyle: {} } : {}),
+            data: [
+              [Date.UTC(2003, 8, 1), 100],
+              [timestamp, 158],
+              [Date.UTC(2003, 10, 1), 120],
+            ],
+          },
+        ],
+      },
+    });
+    mockChart.getModel.mockReturnValue({
+      getComponent: jest.fn().mockReturnValue({
+        getCategories: () => [
+          Date.UTC(2003, 8, 1),
+          timestamp,
+          Date.UTC(2003, 10, 1),
+        ],
+      }),
+    });
+    mockChart.convertFromPixel.mockReturnValue([
+      seriesType === 'categorical line' ? 1 : timestamp + 86400000,
+      158,
+    ]);
+    await getLatestEchartProps().eventHandlers?.contextmenu?.({
+      componentType: 'series',
+      seriesIndex: 0,
+      seriesName: 'Sales',
+      name: '',
+      event: {
+        stop: jest.fn(),
+        offsetX: 100,
+        offsetY: 50,
+        event: { clientX: 10, clientY: 20 },
+      },
+    });
+    expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+      expect.objectContaining({
+        col: 'order_date',
+        op: '==',
+        val: timestamp,
+        grain: TimeGranularity.MONTH,
+      }),
+    ]);
+  },
+);
+
+test('forced categorical temporal Drill by formats the bucket instead of an 
epoch label', async () => {
+  const onContextMenu = jest.fn();
+  const timestamp = Date.UTC(2003, 9, 1);
+  renderTimeseries({
+    onContextMenu,
+    groupby: [],
+    resolvedTimeGrain: TimeGranularity.MONTH,
+    formData: { ...DEFAULT_FORM_DATA, xAxisForceCategorical: true },
+    xAxis: { label: 'order_date', type: AxisType.Category },
+    coltypeMapping: { order_date: GenericDataType.Temporal },
+  });
+  await getLatestEchartProps().eventHandlers?.contextmenu?.({
+    componentType: 'series',
+    seriesIndex: 0,
+    seriesName: 'Sales',
+    data: [timestamp, 158],
+    name: String(timestamp),
+    event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
+  });
+  expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters[0]).toEqual({
+    col: 'order_date',
+    op: '==',
+    val: timestamp,
+    grain: TimeGranularity.MONTH,
+    formattedVal: 'Oct 2003',
+  });
+});
+
+test('ungrained markerless Timeseries Drill by keeps its series-only scope', 
async () => {
+  const onContextMenu = jest.fn();
+  renderTimeseries({
+    onContextMenu,
+    groupby: [],
+    formData: {
+      ...DEFAULT_FORM_DATA,
+      granularitySqla: 'order_date',
+      timeGrainSqla: undefined,
+    },
+    xAxis: { label: 'order_date', type: AxisType.Time },
+    echartOptions: {
+      series: [
+        {
+          type: 'line',
+          showSymbol: false,
+          data: [[Date.UTC(2003, 9, 1), 158]],
+        },
+      ],
+    },
+  });
+  mockChart.convertFromPixel.mockReturnValue([Date.UTC(2003, 9, 1), 158]);
+  await getLatestEchartProps().eventHandlers?.contextmenu?.({
+    componentType: 'series',
+    seriesIndex: 0,
+    seriesName: 'Sales',
+    event: {
+      stop: jest.fn(),
+      offsetX: 100,
+      offsetY: 50,
+      event: { clientX: 10, clientY: 20 },
+    },
+  });
+  expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toBeUndefined();
+});
+
+test('ungrained forced-categorical temporal Drill by formats the timestamp 
label', async () => {
+  const onContextMenu = jest.fn();
+  const timestamp = Date.UTC(2003, 9, 1);
+  renderTimeseries({
+    onContextMenu,
+    groupby: [],
+    resolvedTimeGrain: undefined,
+    formData: {
+      ...DEFAULT_FORM_DATA,
+      timeGrainSqla: undefined,
+      xAxisForceCategorical: true,
+    },
+    xAxis: { label: 'order_date', type: AxisType.Category },
+    coltypeMapping: { order_date: GenericDataType.Temporal },
+  });
+  await getLatestEchartProps().eventHandlers?.contextmenu?.({
+    componentType: 'series',
+    seriesIndex: 0,
+    seriesName: 'Sales',
+    data: [timestamp, 158],
+    name: String(timestamp),
+    event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
+  });
+  expect(onContextMenu.mock.lastCall[2].drillBy.xAxisFilters).toEqual([
+    {
+      col: 'order_date',
+      op: '==',
+      val: '2003-10-01T00:00:00',
+      formattedVal: '2003-10-01 00:00:00',
+    },
+  ]);
+});
+
 test('drill to detail skips a metric-prefixed series tuple part when building 
dimension filters', async () => {
   const onContextMenu = jest.fn();
   renderTimeseries({
diff --git 
a/superset-frontend/plugins/plugin-chart-echarts/test/utils/xAxisDrillByFilter.test.ts
 
b/superset-frontend/plugins/plugin-chart-echarts/test/utils/xAxisDrillByFilter.test.ts
index ac8054b7686..4b90e43b217 100644
--- 
a/superset-frontend/plugins/plugin-chart-echarts/test/utils/xAxisDrillByFilter.test.ts
+++ 
b/superset-frontend/plugins/plugin-chart-echarts/test/utils/xAxisDrillByFilter.test.ts
@@ -16,10 +16,17 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { init, use } from 'echarts/core';
+import { LineChart } from 'echarts/charts';
+import { GridComponent } from 'echarts/components';
+import { SVGRenderer } from 'echarts/renderers';
 import { TimeGranularity } from '@superset-ui/core';
 import {
   formatNaiveDateTime,
+  getTemporalBucketDrillByFilter,
   getTemporalXAxisDrillByFilter,
+  getCategoryAxisValues,
+  getTimeAxisDrillByValue,
   getTimeBucketRange,
 } from '../../src/utils/xAxisDrillByFilter';
 
@@ -236,3 +243,130 @@ test('getTemporalXAxisDrillByFilter returns undefined for 
unusable input', () =>
     getTemporalXAxisDrillByFilter('', 1609459200000, TimeGranularity.DAY),
   ).toBeUndefined();
 });
+
+test('markerless bucket lookup preserves point values and horizontal 
coordinates', () => {
+  expect(getTimeAxisDrillByValue([1000, 5], undefined, undefined)).toBe(1000);
+  expect(getTimeAxisDrillByValue(1000, undefined, undefined)).toBe(1000);
+  expect(getTimeAxisDrillByValue('2024-01-01', undefined, undefined)).toBe(
+    '2024-01-01',
+  );
+  expect(
+    getTimeAxisDrillByValue(
+      undefined,
+      {
+        data: [
+          [5, 1000],
+          [6, 2000],
+        ],
+      },
+      [5, 1800],
+      1,
+    ),
+  ).toBe(2000);
+  expect(
+    getTimeAxisDrillByValue(undefined, { data: [] }, [1800, 5]),
+  ).toBeUndefined();
+  expect(
+    getTimeAxisDrillByValue(undefined, { data: [[1000, 5]] }, [NaN, 5]),
+  ).toBeUndefined();
+  expect(
+    getTimeAxisDrillByValue(undefined, undefined, [1000, 5]),
+  ).toBeUndefined();
+});
+
+test.each([
+  TimeGranularity.MONTH,
+  TimeGranularity.WEEK_ENDING_SATURDAY,
+  'PT6H' as TimeGranularity,
+])(
+  'getTemporalBucketDrillByFilter matches the %s bucket of the clicked label',
+  grain => {
+    const label = Date.UTC(2024, 9, 5, 6);
+    // Epoch milliseconds, a naive UTC string and a Date are the same bucket.
+    [label, '2024-10-05T06:00:00', new Date(label)].forEach(value =>
+      expect(
+        getTemporalBucketDrillByFilter('order_date', value, grain, 'Oct'),
+      ).toEqual({
+        col: 'order_date',
+        op: '==',
+        val: label,
+        grain,
+        formattedVal: 'Oct',
+      }),
+    );
+  },
+);
+
+test('getTemporalBucketDrillByFilter falls back to the exact timestamp without 
a grain', () => {
+  expect(
+    getTemporalBucketDrillByFilter('order_date', Date.UTC(2024, 9, 5, 6)),
+  ).toEqual({ col: 'order_date', op: '==', val: '2024-10-05T06:00:00' });
+});
+
+test('getTemporalBucketDrillByFilter returns undefined for unusable input', () 
=> {
+  expect(
+    getTemporalBucketDrillByFilter('order_date', 'not a date', 'P1M'),
+  ).toBeUndefined();
+  expect(
+    getTemporalBucketDrillByFilter('', Date.UTC(2024, 9, 5), 'P1M'),
+  ).toBeUndefined();
+});
+
+test.each([0, 1])(
+  'categorical bucket lookup matches the axis domain rather than sparse series 
offsets (%s)',
+  valueIndex => {
+    const timestamps = [0, 1, 2].map(month => Date.UTC(2024, month, 1));
+    const series = {
+      data: timestamps
+        .slice(1)
+        .map(timestamp =>
+          valueIndex === 0 ? [timestamp, 10] : [10, timestamp],
+        ),
+    };
+    const lookup = (index: number) =>
+      getTimeAxisDrillByValue(
+        undefined,
+        series,
+        valueIndex === 0 ? [index, 10] : [10, index],
+        valueIndex,
+        true,
+        timestamps.map(String),
+      );
+    expect(lookup(1)).toBe(timestamps[1]);
+    expect(lookup(2)).toBe(timestamps[2]);
+    expect(lookup(0)).toBeUndefined();
+    expect(lookup(3)).toBeUndefined();
+    expect(lookup(-1)).toBeUndefined();
+  },
+);
+
+test.each([false, true])(
+  'category domain includes all queries on the rendered temporal axis 
(horizontal: %s)',
+  horizontal => {
+    use([LineChart, GridComponent, SVGRenderer]);
+    const chart = init(document.createElement('div'), undefined, {
+      renderer: 'svg',
+      ssr: true,
+      width: 400,
+      height: 300,
+    });
+    const timestamps = [0, 1, 2].map(month => Date.UTC(2024, month, 1));
+    const valueIndex = horizontal ? 1 : 0;
+    try {
+      chart.setOption({
+        animation: false,
+        xAxis: { type: horizontal ? 'value' : 'category' },
+        yAxis: { type: horizontal ? 'category' : 'value' },
+        series: [timestamps, timestamps.slice(1)].map(values => ({
+          type: 'line',
+          data: values.map(value => (horizontal ? [10, value] : [value, 10])),
+        })),
+      });
+      expect(getCategoryAxisValues(chart, valueIndex)?.map(String)).toEqual(
+        timestamps.map(String),
+      );
+    } finally {
+      chart.dispose();
+    }
+  },
+);
diff --git 
a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.test.tsx 
b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.test.tsx
index 12ae22ee3ac..42c0374e488 100644
--- a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.test.tsx
+++ b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.test.tsx
@@ -21,6 +21,13 @@ import { useState } from 'react';
 import fetchMock from 'fetch-mock';
 import { omit, omitBy } from 'lodash-es';
 import {
+  buildQueryObject,
+  QueryData,
+  QueryFormData,
+  QueryObject,
+} from '@superset-ui/core';
+import {
+  act,
   render,
   screen,
   userEvent,
@@ -31,6 +38,9 @@ import chartQueries, { sliceId } from 
'spec/fixtures/mockChartQueries';
 import mockState from 'spec/fixtures/mockState';
 import { setupAGGridModules } from 
'@superset-ui/core/components/ThemedAgGridReact';
 import { DashboardPageIdContext } from 
'src/dashboard/containers/DashboardPage';
+import * as chartActions from '../chartAction';
+import * as contextMenu from '../ChartContextMenu/useContextMenu';
+import * as resultsTableView from './useResultsTableView';
 import DrillByModal, { DrillByModalProps } from './DrillByModal';
 
 setupAGGridModules();
@@ -133,6 +143,7 @@ const renderModal = async (
 };
 
 beforeEach(() => {
+  jest.spyOn(chartActions, 'requestChartDataResolved');
   fetchMock
     .post(CHART_DATA_ENDPOINT, { body: {} }, { name: CHART_DATA_ENDPOINT })
     .post(
@@ -142,7 +153,19 @@ beforeEach(() => {
     );
 });
 
-afterEach(() => fetchMock.removeRoutes().clearHistory());
+afterEach(async () => {
+  // Await query building as well as fetches before clearing the request 
history.
+  await act(async () => {
+    await Promise.allSettled(
+      jest
+        .spyOn(chartActions, 'requestChartDataResolved')
+        .mock.results.map(result => result.value),
+    );
+    await fetchMock.callHistory.flush(true);
+  });
+  fetchMock.removeRoutes().clearHistory();
+  jest.restoreAllMocks();
+});
 
 test('should render the title', async () => {
   await renderModal();
@@ -231,6 +254,398 @@ test('should generate Explore url', async () => {
   ).toHaveAttribute('href', '/explore/?form_data_key=123&dashboard_page_id=1');
 });
 
+const OCT_2003 = Date.UTC(2003, 9, 1);
+// The filter the Timeseries plugin sends for a click on the Oct 2003 bar.
+const oct2003BucketFilter = {
+  col: 'ds',
+  op: '==' as const,
+  val: OCT_2003,
+  grain: 'P1M' as const,
+  formattedVal: 'Oct 2003',
+};
+const oct2003AdhocFilter = {
+  expressionType: 'SIMPLE',
+  clause: 'WHERE',
+  operator: '==',
+  operatorId: 'EQUALS',
+  subject: 'ds',
+  comparator: OCT_2003,
+  timeGrain: 'P1M',
+};
+
+const getLastChartDataFormData = () =>
+  JSON.parse(
+    fetchMock.callHistory.lastCall(CHART_DATA_ENDPOINT)?.options
+      ?.body as string,
+  ).form_data;
+
+const getLastChartDataQuery = (): QueryObject =>
+  JSON.parse(
+    fetchMock.callHistory.lastCall(CHART_DATA_ENDPOINT)?.options
+      ?.body as string,
+  ).queries[0];
+
+const temporalAdhocFilter = (subject: string, comparator: string) => ({
+  clause: 'WHERE' as const,
+  expressionType: 'SIMPLE' as const,
+  operator: 'TEMPORAL_RANGE' as const,
+  subject,
+  comparator,
+});
+
+const RANGE = '2003-10-15 : 2005-01-01';
+const shipFilter = temporalAdhocFilter('ship_date', '2003-01-01 : 2004-06-01');
+const xAxisNoFilter = {
+  col: 'ds',
+  op: 'TEMPORAL_RANGE' as const,
+  val: 'No filter',
+};
+
+// Time setups whose rules the backend applies to the chart and the drill.
+const timeSetups: [string, Partial<QueryFormData>][] = [
+  ['no time range', {}],
+  ['a saved time range', { time_range: RANGE }],
+  [
+    'a dashboard time range',
+    { time_range: 'No filter', extra_form_data: { time_range: RANGE } },
+  ],
+  [
+    'a legacy dashboard time range',
+    {
+      time_range: 'No filter',
+      extra_filters: [{ col: '__time_range', op: '==', val: RANGE }],
+    },
+  ],
+  [
+    'a time column and a dashboard x-axis filter',
+    {
+      time_range: RANGE,
+      granularity_sqla: 'ds',
+      extra_form_data: { filters: [xAxisNoFilter] },
+    },
+  ],
+  [
+    'a time column and a legacy x-axis filter',
+    {
+      time_range: RANGE,
+      granularity_sqla: 'ds',
+      extra_filters: [xAxisNoFilter],
+    },
+  ],
+  [
+    'a dashboard time column',
+    { extra_form_data: { time_range: RANGE, granularity_sqla: 'ship_date' } },
+  ],
+  [
+    'a custom SQL x-axis',
+    {
+      x_axis: { expressionType: 'SQL', sqlExpression: 'ds', label: 'ds' },
+      time_range: RANGE,
+    },
+  ],
+];
+
+test.each(timeSetups)(
+  'Drill by from a temporal bucket keeps the time filters of %s and adds the 
bucket',
+  async (_, setup) => {
+    const chartFormData = {
+      ...omit(formData, 'time_range', 'granularity'),
+      x_axis: 'ds',
+      adhoc_filters: [shipFilter],
+      ...setup,
+    } as QueryFormData;
+    await renderModal({
+      column: { column_name: 'name', verbose_name: null },
+      formData: chartFormData,
+      drillByConfig: {
+        filters: [oct2003BucketFilter],
+        groupbyFieldName: 'groupby',
+      },
+    });
+    await waitFor(() =>
+      expect(fetchMock.callHistory.called(CHART_DATA_ENDPOINT)).toBe(true),
+    );
+
+    const drilledFormData = getLastChartDataFormData();
+    // Every time setting of the chart is passed through untouched, so the
+    // backend applies the same time rules to the drill as to the chart.
+    [
+      'x_axis',
+      'time_range',
+      'granularity_sqla',
+      'extra_form_data',
+      'extra_filters',
+    ].forEach(key => expect(drilledFormData[key]).toEqual(chartFormData[key]));
+    expect(drilledFormData.adhoc_filters).toEqual([
+      shipFilter,
+      oct2003AdhocFilter,
+    ]);
+    const chartQuery = buildQueryObject(chartFormData);
+    const query = getLastChartDataQuery();
+    expect(query.time_range).toEqual(chartQuery.time_range);
+    expect(query.granularity).toEqual(chartQuery.granularity);
+    // The bucket is a grained equality, which no query time range replaces.
+    expect(query.filters).toEqual([
+      ...(chartQuery.filters ?? []),
+      { col: 'ds', op: '==', val: OCT_2003, grain: 'P1M' },
+    ]);
+  },
+);
+
+test('temporal drill sends the same bucket filter to the query, CSV and 
Explore', async () => {
+  exportChartMock.mockClear();
+  fetchMock.removeRoute(CHART_DATA_ENDPOINT);
+  fetchMock.post(CHART_DATA_ENDPOINT, {
+    result: [
+      {
+        data: [{ name: 'bucket', count: 67 }],
+        colnames: ['name', 'count'],
+        coltypes: [1, 0],
+      },
+    ],
+  });
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    formData: {
+      ...formData,
+      x_axis: 'ds',
+      time_range: RANGE,
+      adhoc_filters: [shipFilter],
+    },
+    drillByConfig: {
+      filters: [oct2003BucketFilter],
+      groupbyFieldName: 'groupby',
+    },
+  });
+  await waitFor(() =>
+    expect(fetchMock.callHistory.called(CHART_DATA_ENDPOINT)).toBe(true),
+  );
+  const drilledFormData = getLastChartDataFormData();
+  const tableRadio = await screen.findByRole('radio', { name: /table/i });
+  await userEvent.click(tableRadio.closest('label') ?? tableRadio);
+  await userEvent.click(
+    await screen.findByRole('button', { name: 'Download' }),
+  );
+  await userEvent.click(await screen.findByText('Export to CSV'));
+  const exported = exportChartMock.mock.lastCall[0];
+  expect(exported.resultFormat).toBe('csv');
+  expect(exported.formData.adhoc_filters).toEqual(
+    drilledFormData.adhoc_filters,
+  );
+  expect(buildQueryObject(exported.formData).filters).toEqual(
+    getLastChartDataQuery().filters,
+  );
+  const explorePayload = JSON.parse(
+    JSON.parse(
+      fetchMock.callHistory.lastCall(FORM_DATA_KEY_ENDPOINT)?.options
+        ?.body as string,
+    ).form_data,
+  );
+  expect(explorePayload.adhoc_filters).toEqual([
+    shipFilter,
+    oct2003AdhocFilter,
+  ]);
+  expect(explorePayload.time_range).toBe(RANGE);
+});
+
+test('nested temporal drills keep the outer bucket beside the new filters', 
async () => {
+  const selection = jest.spyOn(contextMenu, 'useContextMenu');
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    formData: { ...formData, x_axis: 'ds', time_range: RANGE },
+    drillByConfig: {
+      filters: [oct2003BucketFilter],
+      groupbyFieldName: 'groupby',
+    },
+  });
+  await waitFor(() =>
+    expect(fetchMock.callHistory.called(CHART_DATA_ENDPOINT)).toBe(true),
+  );
+  const shipBucket = {
+    col: 'ship_date',
+    op: '==' as const,
+    val: Date.UTC(2004, 0, 1),
+    grain: 'P1M' as const,
+    formattedVal: 'Jan 2004',
+  };
+  act(() =>
+    selection.mock.lastCall?.[2]?.(
+      { column_name: 'gender', verbose_name: null },
+      {
+        filters: [shipBucket, { col: 'name', op: '==', val: 'Joe' }],
+        groupbyFieldName: 'groupby',
+      },
+    ),
+  );
+  await waitFor(() =>
+    expect(getLastChartDataFormData().groupby).toEqual(['gender']),
+  );
+  expect(getLastChartDataQuery().time_range).toBe(RANGE);
+  expect(getLastChartDataQuery().filters).toEqual([
+    { col: 'ds', op: '==', val: OCT_2003, grain: 'P1M' },
+    { col: 'ship_date', op: '==', val: Date.UTC(2004, 0, 1), grain: 'P1M' },
+    { col: 'name', op: '==', val: 'Joe' },
+  ]);
+});
+
+test('Mixed Timeseries query B drills add the bucket to its own filters', 
async () => {
+  const request = jest
+    .spyOn(chartActions, 'requestChartDataResolved')
+    .mockResolvedValue([]);
+  const savedB = temporalAdhocFilter('ds', RANGE);
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    formData: {
+      ...omit(formData, 'time_range'),
+      adhoc_filters: [],
+      groupby_b: ['ds'],
+      adhoc_filters_b: [savedB],
+    },
+    drillByConfig: {
+      filters: [oct2003BucketFilter],
+      groupbyFieldName: 'groupby_b',
+      adhocFilterFieldName: 'adhoc_filters_b',
+    },
+  });
+  await waitFor(() => expect(request).toHaveBeenCalled());
+  const drilled = request.mock.lastCall?.[0].formData;
+  expect(drilled?.adhoc_filters_b).toEqual([savedB, oct2003AdhocFilter]);
+  expect(drilled?.adhoc_filters).toEqual([]);
+  expect(drilled?.time_range).toBeUndefined();
+});
+
+test('Drill by from a grained temporal bucket shows one bucket label in the 
breadcrumb', async () => {
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    drillByConfig: {
+      filters: [oct2003BucketFilter],
+      groupbyFieldName: 'groupby',
+    },
+  });
+
+  const breadcrumbItems = screen.getAllByTestId('drill-by-breadcrumb-item');
+  await waitFor(() =>
+    expect(within(breadcrumbItems[0]).getByText(/\(Oct 
2003\)$/)).toBeVisible(),
+  );
+  expect(screen.getAllByText(/\(Oct 2003\)$/)).toHaveLength(1);
+  expect(breadcrumbItems[0]).not.toHaveTextContent(String(OCT_2003));
+});
+
+test('categorical Drill by keeps the chart and dashboard time range', async () 
=> {
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    formData: {
+      ...formData,
+      time_range: 'Last year',
+      extra_form_data: { time_range: '2003-01-01 : 2005-01-01' },
+    },
+    drillByConfig: {
+      filters: [{ col: 'gender', op: '==', val: 'boy' }],
+      groupbyFieldName: 'groupby',
+    },
+  });
+  await waitFor(() =>
+    expect(fetchMock.callHistory.called(CHART_DATA_ENDPOINT)).toBe(true),
+  );
+
+  const drilledFormData = getLastChartDataFormData();
+  expect(drilledFormData.time_range).toEqual('Last year');
+  expect(drilledFormData.extra_form_data.time_range).toEqual(
+    '2003-01-01 : 2005-01-01',
+  );
+});
+
+/** A response for a superseded drill must not replace the current one. */
+async function assertLateRequestIgnored(
+  requestKind: 'initial' | 'reload',
+  outcome: 'success' | 'error',
+): Promise<void> {
+  let resolveOldRequest!: (value: QueryData[]) => void;
+  let rejectOldRequest!: (reason: Error) => void;
+  const oldRequest = new Promise<QueryData[]>((resolve, reject) => {
+    resolveOldRequest = resolve;
+    rejectOldRequest = reject;
+  });
+  let resolveNewRequest!: (value: QueryData[]) => void;
+  const newRequest = new Promise<QueryData[]>(resolve => {
+    resolveNewRequest = resolve;
+  });
+  const request = jest.spyOn(chartActions, 'requestChartDataResolved');
+  if (requestKind === 'reload') {
+    request.mockResolvedValueOnce([]);
+  }
+  request.mockReturnValueOnce(oldRequest).mockReturnValueOnce(newRequest);
+  const selection = jest.spyOn(contextMenu, 'useContextMenu');
+  const results = jest.spyOn(resultsTableView, 'useResultsTableView');
+
+  await renderModal({
+    column: { column_name: 'name', verbose_name: null },
+    formData: { ...formData, time_range: 'Last year' },
+  });
+  if (requestKind === 'reload') {
+    await waitFor(() =>
+      expect(screen.queryByLabelText('Loading')).not.toBeInTheDocument(),
+    );
+    act(() => results.mock.lastCall?.[5]?.());
+  }
+  await waitFor(() =>
+    expect(request).toHaveBeenCalledTimes(requestKind === 'reload' ? 2 : 1),
+  );
+  const oldSignal = request.mock.lastCall?.[1];
+  act(() =>
+    selection.mock.lastCall?.[2]?.(
+      { column_name: 'gender', verbose_name: null },
+      { filters: [oct2003BucketFilter], groupbyFieldName: 'groupby' },
+    ),
+  );
+  await waitFor(() =>
+    expect(request).toHaveBeenCalledTimes(requestKind === 'reload' ? 3 : 2),
+  );
+  expect(oldSignal?.aborted).toBe(true);
+
+  await act(async () => {
+    if (outcome === 'success') {
+      resolveOldRequest([]);
+    } else {
+      rejectOldRequest(new Error('superseded request failed'));
+    }
+  });
+  expect(screen.getByLabelText('Loading')).toBeInTheDocument();
+  expect(results.mock.lastCall?.[0]).toBeUndefined();
+  expect(screen.queryByTestId('drill-by-chart')).not.toBeInTheDocument();
+
+  expect(request.mock.lastCall?.[0].formData.adhoc_filters).toContainEqual(
+    oct2003AdhocFilter,
+  );
+  await act(async () => resolveNewRequest([]));
+  expect(screen.queryByLabelText('Loading')).not.toBeInTheDocument();
+  expect(screen.getByTestId('drill-by-chart')).toBeInTheDocument();
+}
+
+test('ignores a stale initial success after a further drill', async () => {
+  await expect(
+    assertLateRequestIgnored('initial', 'success'),
+  ).resolves.toBeUndefined();
+});
+
+test('ignores a stale initial error after a further drill', async () => {
+  await expect(
+    assertLateRequestIgnored('initial', 'error'),
+  ).resolves.toBeUndefined();
+});
+
+test('ignores a stale reload success after a further drill', async () => {
+  await expect(
+    assertLateRequestIgnored('reload', 'success'),
+  ).resolves.toBeUndefined();
+});
+
+test('ignores a stale reload error after a further drill', async () => {
+  await expect(
+    assertLateRequestIgnored('reload', 'error'),
+  ).resolves.toBeUndefined();
+});
+
 test('should render radio buttons', async () => {
   await renderModal();
   const chartRadio = screen.getByRole('radio', { name: /chart/i });
diff --git a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx 
b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
index f09e3597e06..9f027c3d2e0 100644
--- a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
+++ b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
@@ -17,7 +17,14 @@
  * under the License.
  */
 
-import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
+import {
+  useCallback,
+  useContext,
+  useEffect,
+  useMemo,
+  useRef,
+  useState,
+} from 'react';
 import { t } from '@apache-superset/core/translation';
 import {
   BinaryQueryObjectFilterClause,
@@ -401,22 +408,38 @@ export default function DrillByModal({
     [handleDownload],
   );
 
+  const chartDataController = useRef<AbortController>();
   const handleReload = useCallback(() => {
+    chartDataController.current?.abort();
     setChartDataResult(undefined);
     setIsChartDataLoading(true);
 
-    requestChartDataResolved({
-      formData: drilledFormData,
-      requestParams: { async_mode_override: asyncModeOverride },
-    })
+    const controller = new AbortController();
+    chartDataController.current = controller;
+    requestChartDataResolved(
+      {
+        formData: drilledFormData,
+        requestParams: {
+          async_mode_override: asyncModeOverride,
+          signal: controller.signal,
+        },
+      },
+      controller.signal,
+    )
       .then(queriesResponse => {
-        setChartDataResult(queriesResponse);
+        if (!controller.signal.aborted) {
+          setChartDataResult(queriesResponse);
+        }
       })
       .catch(() => {
-        addDangerToast(t('Failed to load chart data.'));
+        if (!controller.signal.aborted) {
+          addDangerToast(t('Failed to load chart data.'));
+        }
       })
       .finally(() => {
-        setIsChartDataLoading(false);
+        if (!controller.signal.aborted) {
+          setIsChartDataLoading(false);
+        }
       });
   }, [addDangerToast, asyncModeOverride, drilledFormData]);
 
@@ -491,24 +514,11 @@ export default function DrillByModal({
   });
 
   useEffect(() => {
-    if (drilledFormData) {
-      setIsChartDataLoading(true);
-      setChartDataResult(undefined);
-      requestChartDataResolved({
-        formData: drilledFormData,
-        requestParams: { async_mode_override: asyncModeOverride },
-      })
-        .then(queriesResponse => {
-          setChartDataResult(queriesResponse);
-        })
-        .catch(() => {
-          addDangerToast(t('Failed to load chart data.'));
-        })
-        .finally(() => {
-          setIsChartDataLoading(false);
-        });
-    }
-  }, [addDangerToast, asyncModeOverride, drilledFormData]);
+    handleReload();
+    return () => {
+      chartDataController.current?.abort();
+    };
+  }, [handleReload]);
   const { metadataBar } = useDatasetMetadataBar({ dataset });
 
   return (
diff --git 
a/superset-frontend/src/components/Chart/DrillBy/DrillByTemporalFilters.test.tsx
 
b/superset-frontend/src/components/Chart/DrillBy/DrillByTemporalFilters.test.tsx
index 053fa081f6a..7ca6ef84aad 100644
--- 
a/superset-frontend/src/components/Chart/DrillBy/DrillByTemporalFilters.test.tsx
+++ 
b/superset-frontend/src/components/Chart/DrillBy/DrillByTemporalFilters.test.tsx
@@ -36,7 +36,7 @@ import {
   EchartsSunburstChartProps,
   EchartsSunburstFormData,
 } from '../../../../plugins/plugin-chart-echarts/src/Sunburst/types';
-import { getTemporalXAxisDrillByFilter } from 
'../../../../plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter';
+import { getTemporalBucketDrillByFilter } from 
'../../../../plugins/plugin-chart-echarts/src/utils/xAxisDrillByFilter';
 import type { EchartsProps } from 
'../../../../plugins/plugin-chart-echarts/src/types';
 import DrillByModal from './DrillByModal';
 
@@ -169,7 +169,7 @@ afterEach(() => {
   mockEchart.mockClear();
 });
 
-test('Sunburst Drill by on a grained segment queries the whole bucket', async 
() => {
+test('Sunburst Drill by on a grained segment queries the grained bucket', 
async () => {
   const filters = sunburstDrillByFilters('order_date');
   const body = await drillByRequest(
     sunburstFormData('order_date'),
@@ -188,6 +188,45 @@ test('Sunburst Drill by on a grained segment queries the 
whole bucket', async ()
   );
 });
 
+test.each(['chart', 'dashboard'])(
+  'Sunburst Drill by keeps the %s time range beside its grained bucket',
+  async source => {
+    const range = '2024-10-15 : 2024-12-01';
+    const body = await drillByRequest(
+      {
+        ...sunburstFormData('order_date'),
+        adhoc_filters: [
+          {
+            clause: 'WHERE',
+            expressionType: 'SIMPLE',
+            operator: 'TEMPORAL_RANGE',
+            subject: 'order_date',
+            comparator: 'No filter',
+          },
+        ],
+        time_range: source === 'chart' ? range : 'No filter',
+        ...(source === 'dashboard' && {
+          extra_form_data: { time_range: range },
+        }),
+      },
+      sunburstDrillByFilters('order_date'),
+      'columns',
+    );
+    // The backend applies the range to the chart's own date filter as it
+    // does for the chart, and the bucket narrows that result.
+    expect(body.queries[0].time_range).toBe(range);
+    expect(body.queries[0].filters).toEqual([
+      { col: 'order_date', op: 'TEMPORAL_RANGE', val: 'No filter' },
+      {
+        col: 'order_date',
+        op: '==',
+        val: Date.UTC(2024, 9, 1),
+        grain: TimeGranularity.MONTH,
+      },
+    ]);
+  },
+);
+
 test('Sunburst Drill by on an adhoc temporal segment writes a quoted ISO 
datetime', async () => {
   const filters = sunburstDrillByFilters(ADHOC_ORDER_DATE);
   const body = await drillByRequest(
@@ -204,7 +243,7 @@ test('Sunburst Drill by on an adhoc temporal segment writes 
a quoted ISO datetim
   );
 });
 
-test('Timeseries Drill by on an adhoc x-axis label sends an ISO datetime, not 
an epoch', async () => {
+test('Timeseries Drill by on an adhoc x-axis label sends its grained bucket', 
async () => {
   const xAxis: QueryFormColumn = {
     expressionType: 'SQL',
     sqlExpression: "DATE_TRUNC('day', order_date)",
@@ -212,8 +251,8 @@ test('Timeseries Drill by on an adhoc x-axis label sends an 
ISO datetime, not an
   };
   // Both Timeseries Drill by callers use this helper with the axis label.
   const filters = [
-    getTemporalXAxisDrillByFilter('order_day', Date.UTC(2024, 9, 7)),
-    getTemporalXAxisDrillByFilter(
+    getTemporalBucketDrillByFilter('order_day', Date.UTC(2024, 9, 7)),
+    getTemporalBucketDrillByFilter(
       'order_day',
       Date.UTC(2024, 9, 7, 6),
       'PT6H' as TimeGranularity,
@@ -232,12 +271,18 @@ test('Timeseries Drill by on an adhoc x-axis label sends 
an ISO datetime, not an
     filters,
     'groupby',
   );
-  // The backend writes an adhoc label comparator without coercion, so an
-  // epoch integer would reach SQL as `<timestamp expr> = 1728259200000`.
+  // Without a grain the backend writes an adhoc label comparator as is, so
+  // an exact match uses the ISO datetime. A grained bucket on the axis label
+  // is compared to the axis column, and the backend writes its value.
   expect(body.queries[0].filters).toEqual(
     expect.arrayContaining([
       { col: 'order_day', op: '==', val: '2024-10-07T00:00:00' },
-      { col: 'order_day', op: '==', val: '2024-10-07T06:00:00' },
+      {
+        col: 'order_day',
+        op: '==',
+        val: Date.UTC(2024, 9, 7, 6),
+        grain: 'PT6H',
+      },
     ]),
   );
 });
@@ -248,6 +293,13 @@ test('Drill by preserves the grain of an equality filter', 
async () => {
     [{ col: 'order_date', op: '==', val: 1727740800000, grain: 'P1M' }],
     'columns',
   );
+  expect(body.form_data.adhoc_filters).toContainEqual(
+    expect.objectContaining({
+      subject: 'order_date',
+      comparator: 1727740800000,
+      timeGrain: 'P1M',
+    }),
+  );
   expect(body.queries[0].filters).toContainEqual({
     col: 'order_date',
     op: '==',
diff --git 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/AdhocFilter.test.ts
 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/AdhocFilter.test.ts
index b263567391c..786e6e43e5d 100644
--- 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/AdhocFilter.test.ts
+++ 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/AdhocFilter.test.ts
@@ -475,3 +475,65 @@ test('a grained drill filter displays its grain and drops 
it on operator or SQL
     filter.duplicateWith({ expressionType: ExpressionTypes.Sql }),
   ).not.toHaveProperty('timeGrain', TimeGranularity.MONTH);
 });
+
+const bucketFilter = () =>
+  new AdhocFilter({
+    expressionType: ExpressionTypes.Simple,
+    subject: 'order_date',
+    operator: '==',
+    operatorId: Operators.Equals,
+    comparator: Date.UTC(2004, 0, 1),
+    timeGrain: TimeGranularity.MONTH,
+    clause: Clauses.Where,
+  });
+
+test('a drilled bucket filter keeps its time grain through Explore edits', () 
=> {
+  const filter = bucketFilter();
+  expect(filter.timeGrain).toBe('P1M');
+  expect(filter.duplicateWith({ clause: Clauses.Having }).timeGrain).toBe(
+    'P1M',
+  );
+  expect(filter.duplicateWith({ comparator: 0 }).timeGrain).toBeUndefined();
+  expect(filter.equals(filter.duplicateWith({}))).toBe(true);
+  // A grain belongs to the time buckets of its subject.
+  expect(
+    filter.duplicateWith({ subject: 'ship_date' }).timeGrain,
+  ).toBeUndefined();
+  expect(
+    filter.equals(new AdhocFilter({ ...filter, timeGrain: undefined })),
+  ).toBe(false);
+});
+
+test('a drilled bucket filter shows its bucket as a datetime', () => {
+  const filter = bucketFilter();
+  expect(filter.getDefaultLabel()).toBe(
+    "[P1M] order_date = '2004-01-01T00:00:00'",
+  );
+  expect(filter.getTooltipTitle()).toBe(
+    "[P1M] order_date = '2004-01-01T00:00:00'",
+  );
+});
+
+test.each(['TEMPORAL_RANGE', '!=', 'IS NULL'])(
+  'a drilled bucket filter drops its time grain when changing operator to %s',
+  operator => {
+    const filter = bucketFilter();
+    const edited = filter.duplicateWith({
+      subject: 'order_date',
+      operator,
+      comparator: '2004-01-15 : 2004-02-15',
+    });
+    expect(edited.timeGrain).toBeUndefined();
+    expect(filter.timeGrain).toBe('P1M');
+  },
+);
+
+test('a drilled bucket filter keeps its grain with an explicitly unchanged 
operator', () => {
+  expect(
+    bucketFilter().duplicateWith({
+      subject: 'order_date',
+      operator: '==',
+      comparator: Date.UTC(2004, 0, 1),
+    }).timeGrain,
+  ).toBe('P1M');
+});
diff --git 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/index.ts
 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/index.ts
index a9e1085eff4..da560a3f5f9 100644
--- 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/index.ts
+++ 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/index.ts
@@ -16,10 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import type {
-  AdhocFilter as CoreAdhocFilter,
-  TimeGranularity,
-} from '@superset-ui/core';
+import type { AdhocFilter as CoreAdhocFilter } from '@superset-ui/core';
 import {
   CUSTOM_OPERATORS,
   DISABLE_INPUT_OPERATORS,
@@ -48,7 +45,7 @@ interface AdhocFilterInput {
   operator?: string | null;
   operatorId?: string;
   comparator?: unknown;
-  timeGrain?: TimeGranularity;
+  timeGrain?: string;
   clause?: string | null;
   sqlExpression?: string | null;
   isExtra?: boolean;
@@ -67,7 +64,8 @@ export default class AdhocFilter {
   operator?: string | null;
   operatorId?: string;
   comparator?: unknown;
-  timeGrain?: TimeGranularity;
+  // Compares time buckets of the subject, e.g. a Drill by from a chart bar.
+  timeGrain?: string;
   clause?: string | null;
   sqlExpression?: string | null;
   isExtra: boolean;
@@ -228,7 +226,15 @@ export default class AdhocFilter {
   }
 
   translateToSql(params: { columns?: VerboseColumn[] } = {}): string {
-    return translateToSql(this as unknown as CoreAdhocFilter, params);
+    const { comparator, timeGrain } = this;
+    const filter =
+      timeGrain && typeof comparator === 'number' && 
Number.isFinite(comparator)
+        ? {
+            ...this,
+            comparator: new Date(comparator).toISOString().slice(0, 19),
+          }
+        : this;
+    return translateToSql(filter as unknown as CoreAdhocFilter, params);
   }
 }
 
diff --git 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/AdhocFilterEditPopover.test.tsx
 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/AdhocFilterEditPopover.test.tsx
index a69d9ebdf97..8880f249dd2 100644
--- 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/AdhocFilterEditPopover.test.tsx
+++ 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/AdhocFilterEditPopover.test.tsx
@@ -253,3 +253,18 @@ describe('AdhocFilterEditPopover', () => {
     expect(onClose).toHaveBeenCalled();
   });
 });
+
+test('a drilled bucket cannot be converted to raw Custom SQL that loses its 
grain', () => {
+  renderPopover({
+    adhocFilter: new AdhocFilter({
+      ...simpleAdhocFilter,
+      operator: '==',
+      comparator: Date.UTC(2004, 0, 1),
+      timeGrain: 'P1M',
+    }),
+  });
+  expect(screen.getByRole('tab', { name: 'Simple' })).toBeInTheDocument();
+  expect(
+    screen.queryByRole('tab', { name: 'Custom SQL' }),
+  ).not.toBeInTheDocument();
+});
diff --git 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/index.tsx
 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/index.tsx
index 58bd881066b..5acec271a46 100644
--- 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/index.tsx
+++ 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopover/index.tsx
@@ -371,6 +371,7 @@ function AdhocFilterEditPopover({
             ),
           },
           ...(datasource?.type === 'semantic_view' ||
+          adhocFilter.timeGrain ||
           [
             Operators.ContainsAny,
             Operators.ContainsAll,
@@ -382,9 +383,8 @@ function AdhocFilterEditPopover({
             Operators.LengthGreaterThanOrEqual,
             Operators.LengthLessThanOrEqual,
           ].includes(adhocFilter.operatorId as Operators)
-            ? // Hide the Custom SQL tab for element-level array operators: 
they
-              // have no portable SQL representation, and converting one would
-              // silently turn the filter into invalid raw SQL.
+            ? // Time buckets and element-level array operators have no 
portable
+              // raw SQL representation; conversion would change their meaning.
               []
             : [
                 {
diff --git 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx
 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx
index 8c65fd0cae2..e516d66c80a 100644
--- 
a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx
+++ 
b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx
@@ -36,6 +36,7 @@ import {
 } from 'src/explore/constants';
 import AdhocMetric from 
'src/explore/components/controls/MetricControl/AdhocMetric';
 import {
+  convertFilter,
   FeatureFlag,
   isFeatureEnabled,
   SupersetClient,
@@ -1580,3 +1581,43 @@ test('late suggestions cannot repopulate a different 
selection version', async (
     get.mockRestore();
   }
 });
+
+test('picking a date range on a drilled bucket filters raw dates without a 
grain', () => {
+  const drilled = new AdhocFilter({
+    expressionType: ExpressionTypes.Simple,
+    subject: 'order_date',
+    operator: '==',
+    operatorId: Operators.Equals,
+    comparator: Date.UTC(2004, 0, 1),
+    timeGrain: 'P1M',
+    clause: Clauses.Where,
+  });
+  const props = setup({ adhocFilter: drilled });
+  const { onDatePickerChange } = useSimpleTabFilterProps(
+    props as unknown as Props,
+  );
+  onDatePickerChange('order_date', '2004-01-15 : 2004-02-15');
+  const edited = props.onChange.mock.calls.at(-1)?.[0];
+  expect(edited.timeGrain).toBeUndefined();
+  expect(convertFilter(edited)).toEqual({
+    col: 'order_date',
+    op: 'TEMPORAL_RANGE',
+    val: '2004-01-15 : 2004-02-15',
+  });
+});
+
+test('changing a drilled bucket comparison operator drops its grain', () => {
+  const props = setup({
+    adhocFilter: new AdhocFilter({
+      ...simpleAdhocFilter,
+      operator: '==',
+      operatorId: Operators.Equals,
+      timeGrain: 'P1M',
+    }),
+  });
+  const { onOperatorChange } = useSimpleTabFilterProps(
+    props as unknown as Props,
+  );
+  onOperatorChange(Operators.NotEquals);
+  expect(props.onChange.mock.calls.at(-1)?.[0].timeGrain).toBeUndefined();
+});
diff --git a/superset/common/query_context_factory.py 
b/superset/common/query_context_factory.py
index 2c4617f1a18..4fd6756bd39 100644
--- a/superset/common/query_context_factory.py
+++ b/superset/common/query_context_factory.py
@@ -439,6 +439,17 @@ class QueryContextFactory:  # pylint: 
disable=too-few-public-methods
                     filter
                     for filter in query_object.filter
                     if filter["col"] != filter_to_remove
+                    or (
+                        filter["op"] != "TEMPORAL_RANGE"
+                        and filter.get("grain")
+                        and any(
+                            isinstance(column, dict)
+                            and column.get("columnType") == "BASE_AXIS"
+                            and column.get("label") == filter["col"]
+                            and column.get("timeGrain") == filter["grain"]
+                            for column in query_object.columns
+                        )
+                    )
                     or (
                         filter["op"] != "TEMPORAL_RANGE"
                         and (
diff --git a/superset/models/helpers.py b/superset/models/helpers.py
index 9ef0d02369c..e691f54b20c 100644
--- a/superset/models/helpers.py
+++ b/superset/models/helpers.py
@@ -7246,8 +7246,56 @@ class ExploreMixin:  # pylint: 
disable=too-many-public-methods
             # (inline dict or referenced by label), so it can be parenthesized
             # to guard operator precedence regardless of how it was referenced.
             is_adhoc_sqla_col = False
+            # Native type of a dataset column an adhoc filter column refers to,
+            # used to write temporal filter values as engine literals.
+            adhoc_native_type: str | None = None
+            axis_column = (
+                adhoc_columns_by_label.get(flt_col)
+                if flt_grain and isinstance(flt_col, str)
+                else None
+            )
             if flt_col == utils.DTTM_ALIAS and is_timeseries and dttm_col:
                 col_obj = dttm_col
+            elif (
+                axis_column
+                and axis_column.get("columnType") == "BASE_AXIS"
+                and axis_column.get("timeGrain") == flt_grain
+            ):
+                # A filter on the x-axis label with the axis grain selects a
+                # bucket of that axis. Compare against the axis column of this
+                # query, which carries any Time Column override, so the filter
+                # matches exactly the rows the axis groups into the bucket.
+                adhoc_filter_column = axis_column
+                sqla_col, adhoc_generic_type = self.adhoc_column_to_sqla(
+                    col=axis_column,
+                    template_processor=template_processor,
+                    apply_dataset_offset=op != 
utils.FilterOperator.TEMPORAL_RANGE,
+                )
+                if axis_tbl_column := 
columns_by_name.get(axis_column["sqlExpression"]):
+                    adhoc_native_type = axis_tbl_column.type
+                    if op == utils.FilterOperator.TEMPORAL_RANGE:
+                        # Range bounds need the axis's underlying column,
+                        # including any Time Column override.
+                        col_obj = axis_tbl_column
+                elif isinstance(val, (int, float)) and not isinstance(val, 
bool):
+                    # An expression axis has no native type to write an engine
+                    # literal for: compare the naive ISO datetime instead of
+                    # the epoch milliseconds of the bucket.
+                    try:
+                        val = (
+                            datetime.fromtimestamp(val / 1000, tz=timezone.utc)
+                            .replace(tzinfo=None)
+                            .isoformat()
+                        )
+                    except (OverflowError, OSError, ValueError) as ex:
+                        raise QueryObjectValidationError(
+                            _(
+                                "Invalid temporal filter value for column 
%(column)s",
+                                column=get_column_name(flt_col),
+                            )
+                        ) from ex
+                applied_adhoc_filters_columns.append(flt_col)
+                is_adhoc_sqla_col = True
             elif is_adhoc_column(flt_col):
                 adhoc_filter_column = cast(AdhocColumn, flt_col)
                 if flt_col.get("columnType") == "BASE_AXIS":
@@ -7345,7 +7393,7 @@ class ExploreMixin:  # pylint: 
disable=too-many-public-methods
                     and not _is_parenthesized(sqla_col)
                 ):
                     sqla_col = Grouping(sqla_col)
-                col_type = col_obj.type if col_obj else None
+                col_type = col_obj.type if col_obj else adhoc_native_type
                 col_spec = db_engine_spec.get_column_spec(native_type=col_type)
                 is_multivalue_col = bool(
                     col_spec and col_spec.generic_type == 
GenericDataType.MULTI_VALUE
diff --git a/superset/translations/ar/LC_MESSAGES/messages.po 
b/superset/translations/ar/LC_MESSAGES/messages.po
index a68169029f5..15985c8ac28 100644
--- a/superset/translations/ar/LC_MESSAGES/messages.po
+++ b/superset/translations/ar/LC_MESSAGES/messages.po
@@ -11499,6 +11499,10 @@ msgstr "حالة غير صالحة."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "معرّفات علامات تبويب غير صالحة: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ca/LC_MESSAGES/messages.po 
b/superset/translations/ca/LC_MESSAGES/messages.po
index 75f8ca459ac..9839a931167 100644
--- a/superset/translations/ca/LC_MESSAGES/messages.po
+++ b/superset/translations/ca/LC_MESSAGES/messages.po
@@ -11188,6 +11188,10 @@ msgstr "Estat invàlid."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "ID de pestanya no vàlids: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/cs/LC_MESSAGES/messages.po 
b/superset/translations/cs/LC_MESSAGES/messages.po
index 99dabe0726f..9dd8a5b8a0c 100644
--- a/superset/translations/cs/LC_MESSAGES/messages.po
+++ b/superset/translations/cs/LC_MESSAGES/messages.po
@@ -10757,6 +10757,10 @@ msgstr "Neplatný stav."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Neplatná ID karet: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/de/LC_MESSAGES/messages.po 
b/superset/translations/de/LC_MESSAGES/messages.po
index 6627961c4b3..95ebf26907a 100644
--- a/superset/translations/de/LC_MESSAGES/messages.po
+++ b/superset/translations/de/LC_MESSAGES/messages.po
@@ -9856,6 +9856,10 @@ msgstr "Ungültiger Zustand."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Ungültige Tab-IDs: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 #, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
 msgstr "Ungültige Zeitbereichsgrenze für Resample: %(value)s"
diff --git a/superset/translations/en/LC_MESSAGES/messages.po 
b/superset/translations/en/LC_MESSAGES/messages.po
index f02cf38f85c..4793f790193 100644
--- a/superset/translations/en/LC_MESSAGES/messages.po
+++ b/superset/translations/en/LC_MESSAGES/messages.po
@@ -8757,6 +8757,10 @@ msgstr ""
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr ""
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 #, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
 msgstr ""
diff --git a/superset/translations/es/LC_MESSAGES/messages.po 
b/superset/translations/es/LC_MESSAGES/messages.po
index e41f3a2a0de..b20d8eb4cc0 100644
--- a/superset/translations/es/LC_MESSAGES/messages.po
+++ b/superset/translations/es/LC_MESSAGES/messages.po
@@ -10968,6 +10968,10 @@ msgstr "Estado no válido."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "ID de pestaña no válidos: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/fa/LC_MESSAGES/messages.po 
b/superset/translations/fa/LC_MESSAGES/messages.po
index 9d97a9fe199..e4164e7db22 100644
--- a/superset/translations/fa/LC_MESSAGES/messages.po
+++ b/superset/translations/fa/LC_MESSAGES/messages.po
@@ -11178,6 +11178,10 @@ msgstr "وضعیت نامعتبر."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "شناسه‌های زبانه نامعتبر: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/fi/LC_MESSAGES/messages.po 
b/superset/translations/fi/LC_MESSAGES/messages.po
index 93065fffdfa..e8633866eaf 100644
--- a/superset/translations/fi/LC_MESSAGES/messages.po
+++ b/superset/translations/fi/LC_MESSAGES/messages.po
@@ -16428,6 +16428,10 @@ msgstr "Virheellinen tila."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Virheelliset välilehtitunnukset: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/fr/LC_MESSAGES/messages.po 
b/superset/translations/fr/LC_MESSAGES/messages.po
index 9afdbd4b744..491edf8a30e 100644
--- a/superset/translations/fr/LC_MESSAGES/messages.po
+++ b/superset/translations/fr/LC_MESSAGES/messages.po
@@ -10645,6 +10645,10 @@ msgstr "État invalide."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Identifiants d'onglet non valides : %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/it/LC_MESSAGES/messages.po 
b/superset/translations/it/LC_MESSAGES/messages.po
index 2515112b15f..5c234cb879e 100644
--- a/superset/translations/it/LC_MESSAGES/messages.po
+++ b/superset/translations/it/LC_MESSAGES/messages.po
@@ -12611,6 +12611,10 @@ msgstr "Stato non valido."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Id schede non validi: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ja/LC_MESSAGES/messages.po 
b/superset/translations/ja/LC_MESSAGES/messages.po
index c990cb864fd..6a0d561f0f1 100644
--- a/superset/translations/ja/LC_MESSAGES/messages.po
+++ b/superset/translations/ja/LC_MESSAGES/messages.po
@@ -9542,6 +9542,10 @@ msgstr "無効な状態です。"
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "無効なタブID: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ko/LC_MESSAGES/messages.po 
b/superset/translations/ko/LC_MESSAGES/messages.po
index 0eb6537660a..3f5d93a3099 100644
--- a/superset/translations/ko/LC_MESSAGES/messages.po
+++ b/superset/translations/ko/LC_MESSAGES/messages.po
@@ -14755,6 +14755,10 @@ msgstr "잘못된 상태입니다."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "잘못된 탭 ID: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/lv/LC_MESSAGES/messages.po 
b/superset/translations/lv/LC_MESSAGES/messages.po
index dbe5453d528..99cecf313ce 100644
--- a/superset/translations/lv/LC_MESSAGES/messages.po
+++ b/superset/translations/lv/LC_MESSAGES/messages.po
@@ -10633,6 +10633,10 @@ msgstr "Nederīgs stāvoklis."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Nederīgi cilņu ID: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/messages.pot 
b/superset/translations/messages.pot
index f00f952e93c..46eb919bb54 100644
--- a/superset/translations/messages.pot
+++ b/superset/translations/messages.pot
@@ -8264,6 +8264,10 @@ msgstr ""
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr ""
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 #, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
 msgstr ""
diff --git a/superset/translations/mi/LC_MESSAGES/messages.po 
b/superset/translations/mi/LC_MESSAGES/messages.po
index 5e55da4363b..47f2413500d 100644
--- a/superset/translations/mi/LC_MESSAGES/messages.po
+++ b/superset/translations/mi/LC_MESSAGES/messages.po
@@ -11098,6 +11098,10 @@ msgstr "Tūnga muhu."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Ngā ID ripa muhu: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/nl/LC_MESSAGES/messages.po 
b/superset/translations/nl/LC_MESSAGES/messages.po
index 2402a6fb151..94a9e3924f0 100644
--- a/superset/translations/nl/LC_MESSAGES/messages.po
+++ b/superset/translations/nl/LC_MESSAGES/messages.po
@@ -11461,6 +11461,10 @@ msgstr "Ongeldige status."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Ongeldige tab-id's: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/pl/LC_MESSAGES/messages.po 
b/superset/translations/pl/LC_MESSAGES/messages.po
index ef34869c687..2d8a5c0aeb4 100644
--- a/superset/translations/pl/LC_MESSAGES/messages.po
+++ b/superset/translations/pl/LC_MESSAGES/messages.po
@@ -11629,6 +11629,10 @@ msgstr "Nieprawidłowy stan."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Nieprawidłowe identyfikatory kart: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/pt/LC_MESSAGES/messages.po 
b/superset/translations/pt/LC_MESSAGES/messages.po
index 971dad5b5bd..5b69cab87b2 100644
--- a/superset/translations/pt/LC_MESSAGES/messages.po
+++ b/superset/translations/pt/LC_MESSAGES/messages.po
@@ -13026,6 +13026,10 @@ msgstr "Estado inválido."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "IDs de guia inválidos:%(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/pt_BR/LC_MESSAGES/messages.po 
b/superset/translations/pt_BR/LC_MESSAGES/messages.po
index 6de5ad40818..11b078b4311 100644
--- a/superset/translations/pt_BR/LC_MESSAGES/messages.po
+++ b/superset/translations/pt_BR/LC_MESSAGES/messages.po
@@ -11295,6 +11295,10 @@ msgstr "Estado inválido."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "IDs de guia inválidos:%(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ro/LC_MESSAGES/messages.po 
b/superset/translations/ro/LC_MESSAGES/messages.po
index 521038c4aef..81be8b4eef1 100644
--- a/superset/translations/ro/LC_MESSAGES/messages.po
+++ b/superset/translations/ro/LC_MESSAGES/messages.po
@@ -11231,6 +11231,10 @@ msgstr "Stare invalidă."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "ID-uri de file nevalide: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ru/LC_MESSAGES/messages.po 
b/superset/translations/ru/LC_MESSAGES/messages.po
index c58d62e982b..f5720e5212c 100644
--- a/superset/translations/ru/LC_MESSAGES/messages.po
+++ b/superset/translations/ru/LC_MESSAGES/messages.po
@@ -10444,6 +10444,10 @@ msgstr "Некорректное состояние"
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Некорректные ID вкладок: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/sk/LC_MESSAGES/messages.po 
b/superset/translations/sk/LC_MESSAGES/messages.po
index 7fb2650f0e4..a0d5aa5d043 100644
--- a/superset/translations/sk/LC_MESSAGES/messages.po
+++ b/superset/translations/sk/LC_MESSAGES/messages.po
@@ -11161,6 +11161,10 @@ msgstr "Neplatný stav."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Neplatná ID karet: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/sl/LC_MESSAGES/messages.po 
b/superset/translations/sl/LC_MESSAGES/messages.po
index b07709f645a..ffa69cc5247 100644
--- a/superset/translations/sl/LC_MESSAGES/messages.po
+++ b/superset/translations/sl/LC_MESSAGES/messages.po
@@ -10618,6 +10618,10 @@ msgstr "Neveljavno stanje."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Neveljavni ID-ji zavihkov: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/sr/LC_MESSAGES/messages.po 
b/superset/translations/sr/LC_MESSAGES/messages.po
index 06bbf9dcdc9..61728ff205e 100644
--- a/superset/translations/sr/LC_MESSAGES/messages.po
+++ b/superset/translations/sr/LC_MESSAGES/messages.po
@@ -12469,6 +12469,10 @@ msgstr "Неважеће стање."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Неважећи ИД-ови картица: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/sr_Latn/LC_MESSAGES/messages.po 
b/superset/translations/sr_Latn/LC_MESSAGES/messages.po
index e750466426d..4b97fe0a63e 100644
--- a/superset/translations/sr_Latn/LC_MESSAGES/messages.po
+++ b/superset/translations/sr_Latn/LC_MESSAGES/messages.po
@@ -12480,6 +12480,10 @@ msgstr "Nevažeće stanje."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Nevažeći ID-ovi kartica: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/ta/LC_MESSAGES/messages.po 
b/superset/translations/ta/LC_MESSAGES/messages.po
index 43c85d461c9..6cd5f4dc0e0 100644
--- a/superset/translations/ta/LC_MESSAGES/messages.po
+++ b/superset/translations/ta/LC_MESSAGES/messages.po
@@ -10682,6 +10682,10 @@ msgstr "தவறான நிலை."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "தவறான தாவல் ஐடிகள்: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/th/LC_MESSAGES/messages.po 
b/superset/translations/th/LC_MESSAGES/messages.po
index 53eafcf13bc..849292dd44b 100644
--- a/superset/translations/th/LC_MESSAGES/messages.po
+++ b/superset/translations/th/LC_MESSAGES/messages.po
@@ -16172,6 +16172,10 @@ msgstr "สถานะไม่ถูกต้อง"
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "ID แท็บไม่ถูกต้อง: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/tr/LC_MESSAGES/messages.po 
b/superset/translations/tr/LC_MESSAGES/messages.po
index 64577a0c0d6..c89d21f1431 100644
--- a/superset/translations/tr/LC_MESSAGES/messages.po
+++ b/superset/translations/tr/LC_MESSAGES/messages.po
@@ -10676,6 +10676,10 @@ msgstr "Invalid state."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Geçersiz sekme kimlikleri: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/uk/LC_MESSAGES/messages.po 
b/superset/translations/uk/LC_MESSAGES/messages.po
index 8460daa23a9..b1e39adb3b9 100644
--- a/superset/translations/uk/LC_MESSAGES/messages.po
+++ b/superset/translations/uk/LC_MESSAGES/messages.po
@@ -10646,6 +10646,10 @@ msgstr "Неправильний стан."
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "Некоректні ID вкладок: %(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/zh/LC_MESSAGES/messages.po 
b/superset/translations/zh/LC_MESSAGES/messages.po
index d1382c30796..fb08d3d7d39 100644
--- a/superset/translations/zh/LC_MESSAGES/messages.po
+++ b/superset/translations/zh/LC_MESSAGES/messages.po
@@ -10400,6 +10400,10 @@ msgstr "无效状态。"
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "无效的标签页ID:%(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/superset/translations/zh_TW/LC_MESSAGES/messages.po 
b/superset/translations/zh_TW/LC_MESSAGES/messages.po
index 0ea1f5a34bb..3839038ba4e 100644
--- a/superset/translations/zh_TW/LC_MESSAGES/messages.po
+++ b/superset/translations/zh_TW/LC_MESSAGES/messages.po
@@ -11219,6 +11219,10 @@ msgstr "無效狀態。"
 msgid "Invalid tab ids: %(tab_ids)s"
 msgstr "無效的標籤頁 ID:%(tab_ids)s"
 
+#, python-format
+msgid "Invalid temporal filter value for column %(column)s"
+msgstr ""
+
 # Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
 #, fuzzy, python-format
 msgid "Invalid time range boundary for resample: %(value)s"
diff --git a/tests/unit_tests/common/test_drill_by_time_column.py 
b/tests/unit_tests/common/test_drill_by_time_column.py
new file mode 100644
index 00000000000..06afe836e85
--- /dev/null
+++ b/tests/unit_tests/common/test_drill_by_time_column.py
@@ -0,0 +1,438 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Row-level contract for Drill by from a temporal bucket: a drill returns exactly
+the rows its bucket counts in the chart. The frontend keeps every time filter
+of the chart as it is and adds the clicked bucket as a grained equality filter
+on the x-axis label (``getTemporalBucketDrillByFilter`` in
+``plugin-chart-echarts``), so the backend applies the same time rules to both
+queries. The queries run through the real query object pipeline on SQLite.
+"""
+
+import sqlite3
+from copy import deepcopy
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import pytest
+from flask import Flask
+from pytest_mock import MockerFixture
+
+from superset.common.chart_data import ChartDataResultType
+from superset.common.query_context_factory import QueryContextFactory
+from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
+from superset.exceptions import QueryObjectValidationError
+from superset.models.core import Database
+
+# (order_date, ship_date, status)
+ORDERS = [
+    ("2003-11-20 10:00:00", "2003-12-05 00:00:00", "A"),
+    ("2003-12-05 10:00:00", "2003-12-20 00:00:00", "A"),
+    ("2003-12-10 10:00:00", "2004-01-10 00:00:00", "A"),
+    ("2003-12-20 10:00:00", "2004-01-05 00:00:00", "B"),
+    ("2003-12-28 10:00:00", "2004-02-01 00:00:00", "A"),
+    ("2004-01-05 10:00:00", "2004-01-20 00:00:00", "A"),
+    ("2004-01-25 10:00:00", "2004-02-10 00:00:00", "B"),
+    ("2004-02-10 10:00:00", "2004-03-01 00:00:00", "A"),
+    ("2004-02-20 10:00:00", "2004-07-01 00:00:00", "A"),
+]
+RANGE = "2004-01-01 : 2005-01-01"
+SHIP_RANGE = "2003-01-01 : 2004-06-01"
+MONTHS = ["2003-11", "2003-12", "2004-01", "2004-02"]
+
+
+def _axis(expression: str, label: str | None = None, **extra: Any) -> 
dict[str, Any]:
+    return {
+        "timeGrain": "P1M",
+        "columnType": "BASE_AXIS",
+        "sqlExpression": expression,
+        "label": label or expression,
+        "expressionType": "SQL",
+        **extra,
+    }
+
+
+X_AXIS = _axis("order_date", isColumnReference=True)
+
+
+def _temporal(col: str, val: str) -> dict[str, str]:
+    return {"col": col, "op": "TEMPORAL_RANGE", "val": val}
+
+
+def _bucket(col: str, month: str) -> dict[str, Any]:
+    """The filter a Drill by from the month bar sends."""
+    start = datetime.strptime(month, "%Y-%m").replace(tzinfo=timezone.utc)
+    return {
+        "col": col,
+        "op": "==",
+        "val": int(start.timestamp() * 1000),
+        "grain": "P1M",
+    }
+
+
[email protected]
+def executed_sql() -> list[str]:
+    return []
+
+
[email protected]
+def run_query(
+    mocker: MockerFixture, app: Flask, tmp_path: Path, executed_sql: list[str]
+) -> Any:
+    path = tmp_path / "orders.db"
+    con = sqlite3.connect(path)
+    con.execute(
+        "CREATE TABLE orders (order_date TIMESTAMP, ship_date TIMESTAMP, 
status TEXT)"
+    )
+    con.executemany("INSERT INTO orders VALUES (?, ?, ?)", ORDERS)
+    con.commit()
+    con.close()
+    mocker.patch(
+        
"superset.connectors.sqla.models.security_manager.get_guest_rls_filters",
+        return_value=[],
+    )
+    mocker.patch(
+        "superset.connectors.sqla.models.security_manager.is_guest_user",
+        return_value=False,
+    )
+    dataset = SqlaTable(
+        id=1,
+        table_name="orders",
+        columns=[
+            TableColumn(column_name="order_date", is_dttm=1, type="TIMESTAMP"),
+            TableColumn(column_name="ship_date", is_dttm=1, type="TIMESTAMP"),
+            TableColumn(column_name="status", type="TEXT"),
+        ],
+        main_dttm_col="order_date",
+        database=Database(
+            id=1, database_name="orders", sqlalchemy_uri=f"sqlite:///{path}"
+        ),
+        metrics=[SqlMetric(metric_name="count", expression="COUNT(*)")],
+    )
+    factory = QueryContextFactory()
+
+    def run(query: dict[str, Any], form_data: dict[str, Any]) -> list[Any]:
+        # Processing mutates the columns and filters (e.g. a Time Column
+        # override replaces the x-axis expression), so keep the setups intact.
+        query = deepcopy(query)
+        query_object = factory._query_object_factory.create(
+            ChartDataResultType.FULL,
+            datasource={"id": 1, "type": "table"},
+            datasource_model_instance=dataset,
+            metrics=["count"],
+            **{"is_timeseries": False, **query},
+        )
+        query_object = factory._process_query_object(dataset, form_data, 
query_object)
+        sql = dataset.get_query_str_extended(query_object.to_dict(), 
mutate=True).sql
+        executed_sql.append(sql)
+        con = sqlite3.connect(path)
+        rows = con.execute(sql).fetchall()
+        con.close()
+        return rows
+
+    with app.test_request_context():
+        yield run
+
+
+def _bar(rows: list[Any], month: str) -> int:
+    return sum(row[-1] for row in rows if str(row[0]).startswith(month))
+
+
+# Each setup is a chart query as the frontend builds it (dashboard filters
+# come before the chart's own) and the form data the backend receives.
+SETUPS: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {
+    "range_and_ship_filter": (
+        {
+            "columns": [X_AXIS],
+            "time_range": RANGE,
+            "filters": [_temporal("ship_date", SHIP_RANGE)],
+        },
+        {"x_axis": "order_date"},
+    ),
+    "time_column_and_x_axis_no_filter": (
+        {
+            "columns": [X_AXIS],
+            "granularity": "order_date",
+            "time_range": RANGE,
+            "filters": [
+                _temporal("order_date", "No filter"),
+                _temporal("ship_date", SHIP_RANGE),
+            ],
+        },
+        {"x_axis": "order_date", "granularity_sqla": "order_date"},
+    ),
+    "time_column_and_dashboard_x_axis_filter": (
+        {
+            "columns": [X_AXIS],
+            "granularity": "order_date",
+            "time_range": RANGE,
+            "filters": [
+                {**_temporal("order_date", "No filter"), "isExtra": True},
+                _temporal("ship_date", SHIP_RANGE),
+            ],
+        },
+        {
+            "x_axis": "order_date",
+            "granularity_sqla": "order_date",
+            "extra_form_data": {
+                "filters": [_temporal("order_date", "No filter")],
+            },
+        },
+    ),
+    "time_column_overrides_x_axis": (
+        {
+            "columns": [X_AXIS],
+            "granularity": "ship_date",
+            "time_range": RANGE,
+            "filters": [_temporal("ship_date", SHIP_RANGE)],
+        },
+        {"x_axis": "order_date", "granularity_sqla": "ship_date"},
+    ),
+    "custom_sql_x_axis": (
+        {
+            "columns": [_axis("order_date")],
+            "time_range": RANGE,
+            "filters": [_temporal("ship_date", SHIP_RANGE)],
+        },
+        {
+            "x_axis": {
+                "expressionType": "SQL",
+                "sqlExpression": "order_date",
+                "label": "order_date",
+            },
+        },
+    ),
+    "custom_sql_x_axis_with_own_label": (
+        {
+            "columns": [_axis("order_date", "order_month")],
+            "time_range": RANGE,
+            "filters": [_temporal("ship_date", SHIP_RANGE)],
+        },
+        {
+            "x_axis": {
+                "expressionType": "SQL",
+                "sqlExpression": "order_date",
+                "label": "order_month",
+            },
+        },
+    ),
+}
+EXPECTED_BARS = {
+    "range_and_ship_filter": [0, 3, 2, 2],
+    "time_column_and_x_axis_no_filter": [0, 0, 2, 2],
+    "time_column_and_dashboard_x_axis_filter": [0, 0, 2, 2],
+    # Bars count ship_date months: the Time Column replaces the x-axis.
+    "time_column_overrides_x_axis": [0, 0, 3, 2],
+    "custom_sql_x_axis": [0, 0, 2, 2],
+    "custom_sql_x_axis_with_own_label": [0, 0, 2, 2],
+}
+
+
[email protected]("setup", list(SETUPS))
+def test_drill_by_returns_the_rows_of_the_clicked_bucket(
+    run_query: Any, setup: str
+) -> None:
+    query, form_data = SETUPS[setup]
+    axis = query["columns"][0]["label"]
+    chart = run_query(query, form_data)
+    assert [_bar(chart, month) for month in MONTHS] == EXPECTED_BARS[setup]
+    for month in MONTHS:
+        drill = run_query(
+            {
+                **query,
+                "columns": [*query["columns"], "status"],
+                "filters": [*query["filters"], _bucket(axis, month)],
+            },
+            form_data,
+        )
+        assert sum(row[-1] for row in drill) == _bar(chart, month), month
+
+
+def test_nested_drill_narrows_only_the_bucket(run_query: Any) -> None:
+    """A further drill from a status keeps the bucket and the chart filters."""
+    query, form_data = SETUPS["time_column_and_dashboard_x_axis_filter"]
+    nested = run_query(
+        {
+            **query,
+            "columns": [X_AXIS, "status"],
+            "filters": [
+                *query["filters"],
+                _bucket("order_date", "2004-01"),
+                {"col": "status", "op": "==", "val": "A"},
+            ],
+        },
+        form_data,
+    )
+    assert sum(row[-1] for row in nested) == 1
+
+
+def test_legacy_time_column_bucket_follows_the_dashboard_time_column(
+    run_query: Any,
+) -> None:
+    """Without an x-axis the bucket filters __timestamp, i.e. the time column
+    the chart groups by, including a dashboard Time Column override."""
+    query: dict[str, Any] = {
+        "is_timeseries": True,
+        "granularity": "ship_date",
+        "time_range": RANGE,
+        "extras": {"time_grain_sqla": "P1M"},
+        "filters": [_temporal("order_date", "No filter")],
+    }
+    form_data = {
+        "granularity_sqla": "order_date",
+        "extra_form_data": {"granularity_sqla": "ship_date"},
+    }
+    chart = run_query(query, form_data)
+    assert _bar(chart, "2004-01") == 3
+    drill = run_query(
+        {
+            **query,
+            "columns": ["status"],
+            "filters": [*query["filters"], _bucket("__timestamp", "2004-01")],
+        },
+        form_data,
+    )
+    assert sum(row[-1] for row in drill) == 3
+
+
+def test_expression_x_axis_bucket_compares_an_iso_datetime(
+    run_query: Any, executed_sql: list[str]
+) -> None:
+    """An expression axis has no native type for an engine literal, so the
+    bucket is written as the naive ISO datetime, not epoch milliseconds."""
+    axis = _axis("DATETIME(order_date)", "order_ts")
+    run_query(
+        {"columns": [axis, "status"], "filters": [_bucket("order_ts", 
"2004-01")]},
+        {"x_axis": {"sqlExpression": "DATETIME(order_date)", "label": 
"order_ts"}},
+    )
+    assert "(DATETIME(order_date)) = '2004-01-01T00:00:00'" in executed_sql[-1]
+
+
+def test_time_range_filter_on_the_time_column_keeps_a_grained_bucket(
+    run_query: Any,
+) -> None:
+    """A grained bucket on the Time Column (e.g. a Sunburst level) survives the
+    Time Range filter the Time Column replaces."""
+    query: dict[str, Any] = {
+        "columns": ["status"],
+        "granularity": "order_date",
+        "time_range": RANGE,
+        "filters": [_temporal("order_date", "No filter")],
+    }
+    drill = run_query(
+        {**query, "filters": [*query["filters"], _bucket("order_date", 
"2004-01")]},
+        {"granularity_sqla": "order_date"},
+    )
+    assert sum(row[-1] for row in run_query(query, {})) == 4
+    assert sum(row[-1] for row in drill) == 2
+
+
[email protected](
+    "time_column,expected_bars",
+    [
+        (None, [0, 0, 0, 2]),
+        ("order_date", [0, 0, 1, 1]),
+        ("ship_date", [0, 0, 1, 2]),
+    ],
+)
+def test_grained_temporal_range_on_x_axis(
+    run_query: Any,
+    executed_sql: list[str],
+    time_column: str | None,
+    expected_bars: list[int],
+) -> None:
+    """A grained range on an axis uses its underlying Time Column."""
+    query: dict[str, Any] = {
+        "columns": [X_AXIS, "status"],
+        "filters": [
+            {
+                **_temporal("order_date", "2004-01-15 : 2004-02-15"),
+                "grain": "P1M",
+            },
+        ],
+    }
+    form_data = {"x_axis": "order_date"}
+    if time_column:
+        query["granularity"] = time_column
+        form_data["granularity_sqla"] = time_column
+    rows = run_query(query, form_data)
+    assert sum(row[-1] for row in rows) == sum(expected_bars)
+    assert [_bar(rows, month) for month in MONTHS] == expected_bars
+    column = time_column or "DATETIME(order_date, 'start of month')"
+    assert f"{column} >= '2004-01-15" in executed_sql[-1]
+    assert f"{column} < '2004-02-15" in executed_sql[-1]
+
+
[email protected]("axis_in_query", [True, False])
[email protected](
+    "op,val,expected",
+    [
+        ("==", _bucket("order_date", "2004-01")["val"], 2),
+        ("==", "2004-01-01T00:00:00", 0),
+        (
+            "IN",
+            [_bucket("order_date", month)["val"] for month in ["2004-01", 
"2004-02"]],
+            4,
+        ),
+        ("NOT IN", [_bucket("order_date", "2004-01")["val"]], 7),
+        ("!=", _bucket("order_date", "2004-01")["val"], 7),
+        (">=", _bucket("order_date", "2004-01")["val"], 4),
+        ("TEMPORAL_RANGE", "2004-01-15 : 2004-02-15", 2),
+    ],
+)
+def test_grained_axis_filter_operators(
+    run_query: Any, axis_in_query: bool, op: str, val: Any, expected: int
+) -> None:
+    """Axis-label and ordinary column filters preserve operator semantics."""
+    rows = run_query(
+        {
+            "columns": [X_AXIS, "status"] if axis_in_query else ["status"],
+            "filters": [{"col": "order_date", "op": op, "val": val, "grain": 
"P1M"}],
+        },
+        {"x_axis": "order_date"},
+    )
+    assert sum(row[-1] for row in rows) == expected
+
+
[email protected](
+    "value",
+    [float("nan"), float("inf"), float("-inf"), 1e30, -1e30, 10**400],
+    ids=[
+        "nan",
+        "inf",
+        "negative_inf",
+        "out_of_range",
+        "negative_out_of_range",
+        "overflow",
+    ],
+)
+def test_expression_x_axis_rejects_invalid_bucket_epoch(
+    run_query: Any, value: float | int
+) -> None:
+    """Invalid expression-axis epochs must raise a client-facing query 
error."""
+    axis = _axis("DATETIME(order_date)", "order_ts")
+    with pytest.raises(
+        QueryObjectValidationError, match="Invalid temporal filter value"
+    ):
+        run_query(
+            {
+                "columns": [axis, "status"],
+                "filters": [{**_bucket("order_ts", "2004-01"), "val": value}],
+            },
+            {"x_axis": {"sqlExpression": "DATETIME(order_date)", "label": 
"order_ts"}},
+        )
diff --git a/tests/unit_tests/common/test_query_context_factory.py 
b/tests/unit_tests/common/test_query_context_factory.py
index 3f9c996e641..e84425cf099 100644
--- a/tests/unit_tests/common/test_query_context_factory.py
+++ b/tests/unit_tests/common/test_query_context_factory.py
@@ -511,6 +511,56 @@ class TestQueryContextFactory:
         assert len(query_object.filter) == 1
         assert query_object.filter[0]["col"] == "ds"
 
+    def test_apply_granularity_keeps_grained_bucket_filters(self):
+        """A grained filter selects time buckets, not a range: the Time Column
+        override keeps it while it drops the x-axis time filters."""
+        bucket = {"col": "ds", "op": "==", "val": 1704067200000, "grain": 
"P1M"}
+        query_object = Mock(spec=QueryObject)
+        query_object.granularity = "ship_date"
+        query_object.columns = [
+            {
+                "sqlExpression": "ds",
+                "label": "ds",
+                "columnType": "BASE_AXIS",
+                "timeGrain": "P1M",
+            }
+        ]
+        query_object.post_processing = []
+        query_object.filter = [
+            {"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"},
+            dict(bucket),
+        ]
+        datasource = Mock()
+        datasource.columns = [
+            {"column_name": "ds", "is_dttm": True},
+            {"column_name": "ship_date", "is_dttm": True},
+        ]
+
+        self.factory._apply_granularity(query_object, {"x_axis": "ds"}, 
datasource)
+
+        # get_sqla_query compares it to the overridden axis column by label.
+        assert query_object.filter == [bucket]
+        assert query_object.columns[0]["sqlExpression"] == "ship_date"
+
+    def test_apply_granularity_keeps_a_grained_filter_on_the_time_column(self):
+        """Without an x-axis the Time Column's range filter is replaced, but a
+        bucket on it (e.g. a Sunburst level) is not."""
+        bucket = {"col": "ds", "op": "==", "val": 1704067200000, "grain": 
"P1M"}
+        query_object = Mock(spec=QueryObject)
+        query_object.granularity = "ds"
+        query_object.columns = ["other_col"]
+        query_object.post_processing = []
+        query_object.filter = [
+            {"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"},
+            dict(bucket),
+        ]
+        datasource = Mock()
+        datasource.columns = [{"column_name": "ds", "is_dttm": True}]
+
+        self.factory._apply_granularity(query_object, {}, datasource)
+
+        assert query_object.filter == [bucket]
+
     def test_apply_granularity_no_granularity(self):
         """Test _apply_granularity when no granularity is set"""
         query_object = Mock(spec=QueryObject)
diff --git a/tests/unit_tests/core_tests.py b/tests/unit_tests/core_tests.py
index 3acad5fb744..3cf5f262dea 100644
--- a/tests/unit_tests/core_tests.py
+++ b/tests/unit_tests/core_tests.py
@@ -261,6 +261,28 @@ def test_split_adhoc_filters_joins_sql_expressions():
     assert form_data["where"] == "(a = 1) AND (b = 2)"
 
 
+def test_split_adhoc_filters_keeps_the_grain_of_a_bucket_filter():
+    """A drilled time bucket compares the grained column, not one instant."""
+    form_data = {
+        "adhoc_filters": [
+            {
+                "expressionType": "SIMPLE",
+                "clause": "WHERE",
+                "subject": "order_date",
+                "operator": "==",
+                "comparator": 1072915200000,
+                "timeGrain": "P1M",
+            }
+        ]
+    }
+
+    split_adhoc_filters_into_base_filters(form_data)
+
+    assert form_data["filters"] == [
+        {"col": "order_date", "op": "==", "val": 1072915200000, "grain": "P1M"}
+    ]
+
+
 def test_split_adhoc_filters_preserves_jinja_templates():
     form_data = {
         "adhoc_filters": [
diff --git a/tests/unit_tests/mcp_service/chart/test_chart_utils.py 
b/tests/unit_tests/mcp_service/chart/test_chart_utils.py
index e945c79fe17..cb9afc9b8b3 100644
--- a/tests/unit_tests/mcp_service/chart/test_chart_utils.py
+++ b/tests/unit_tests/mcp_service/chart/test_chart_utils.py
@@ -2468,6 +2468,22 @@ class TestAdhocFiltersToQueryFilters:
         result = adhoc_filters_to_query_filters(adhoc)
         assert result == [{"col": "genre", "op": "==", "val": "Action"}]
 
+    def test_keeps_the_grain_of_a_drilled_bucket(self) -> None:
+        """A chart saved from a Drill by compares its time bucket by grain."""
+        adhoc = [
+            {
+                "clause": "WHERE",
+                "expressionType": "SIMPLE",
+                "subject": "order_date",
+                "operator": "==",
+                "comparator": 1072915200000,
+                "timeGrain": "P1M",
+            }
+        ]
+        assert adhoc_filters_to_query_filters(adhoc) == [
+            {"col": "order_date", "op": "==", "val": 1072915200000, "grain": 
"P1M"}
+        ]
+
     def test_converts_multiple_filters(self) -> None:
         adhoc = [
             {

Reply via email to