You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2025/07/23 21:48:17 UTC

(superset) branch add-retries-native-filters updated (a30d7268b7 -> 39de2c5ef2)

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

beto pushed a change to branch add-retries-native-filters
in repository https://gitbox.apache.org/repos/asf/superset.git


 discard a30d7268b7 Push fix down the stack to client
     new 39de2c5ef2 Push fix down the stack to client

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (a30d7268b7)
            \
             N -- N -- N   refs/heads/add-retries-native-filters (39de2c5ef2)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 superset/charts/data/api.py | 6 ------
 1 file changed, 6 deletions(-)


(superset) 01/01: Push fix down the stack to client

Posted by be...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

beto pushed a commit to branch add-retries-native-filters
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 39de2c5ef23c0feaa449e29c514599a7de672bc3
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Wed Jul 23 17:42:53 2025 -0400

    Push fix down the stack to client
---
 .../src/components/Chart/chartAction.js            |  67 ++-------
 superset-frontend/src/setup/setupClient.ts         |   9 ++
 .../src/utils/retryWithExponentialBackoff.test.ts  | 163 ---------------------
 .../src/utils/retryWithExponentialBackoff.ts       |  84 -----------
 superset/config.py                                 |  17 +--
 superset/views/base.py                             |   8 +-
 6 files changed, 32 insertions(+), 316 deletions(-)

diff --git a/superset-frontend/src/components/Chart/chartAction.js b/superset-frontend/src/components/Chart/chartAction.js
index 2e09f9ffaa..10e45b385a 100644
--- a/superset-frontend/src/components/Chart/chartAction.js
+++ b/superset-frontend/src/components/Chart/chartAction.js
@@ -44,8 +44,6 @@ import { waitForAsyncData } from 'src/middleware/asyncEvent';
 import { ensureAppRoot } from 'src/utils/pathUtils';
 import { safeStringify } from 'src/utils/safeStringify';
 import { extendedDayjs } from '@superset-ui/core/utils/dates';
-import { retryWithStaggeredDelay } from 'src/utils/retryWithExponentialBackoff';
-import getBootstrapData from 'src/utils/getBootstrapData';
 
 export const CHART_UPDATE_STARTED = 'CHART_UPDATE_STARTED';
 export function chartUpdateStarted(queryController, latestQueryFormData, key) {
@@ -213,7 +211,6 @@ export async function getChartDataRequest({
   method = 'POST',
   requestParams = {},
   ownState = {},
-  retry = true,
 }) {
   let querySettings = {
     ...requestParams,
@@ -226,66 +223,28 @@ export async function getChartDataRequest({
       credentials: 'include',
     };
   }
-
   const [useLegacyApi, parseMethod] = getQuerySettings(formData);
-
-  // Create a function that performs the actual request
-  const performRequest = () => {
-    if (useLegacyApi) {
-      return legacyChartDataRequest(
-        formData,
-        resultFormat,
-        resultType,
-        force,
-        method,
-        querySettings,
-        parseMethod,
-      );
-    }
-    return v1ChartDataRequest(
+  if (useLegacyApi) {
+    return legacyChartDataRequest(
       formData,
       resultFormat,
       resultType,
       force,
+      method,
       querySettings,
-      setDataMask,
-      ownState,
       parseMethod,
     );
-  };
-
-  // If retry is enabled, wrap the request with retry logic
-  if (retry) {
-    const bootstrapData = getBootstrapData();
-    const retryConfig = bootstrapData.common.conf;
-
-    return retryWithStaggeredDelay(performRequest, {
-      maxRetries: retryConfig.NATIVE_FILTER_RETRY_MAX_ATTEMPTS || 3,
-      initialDelay: retryConfig.NATIVE_FILTER_RETRY_INITIAL_DELAY || 1000,
-      maxDelay: retryConfig.NATIVE_FILTER_RETRY_MAX_DELAY || 10000,
-      backoffMultiplier:
-        retryConfig.NATIVE_FILTER_RETRY_BACKOFF_MULTIPLIER || 2,
-      // Add random stagger to prevent multiple requests from hitting the DB simultaneously
-      staggerOffset:
-        Math.random() *
-        (retryConfig.NATIVE_FILTER_RETRY_STAGGER_MAX_OFFSET || 2000),
-      shouldRetry: error => {
-        if (!error?.response) return true; // Network error
-        const status = error.response?.status;
-        return status === 502;
-      },
-      onRetry: (attempt, delay, error) => {
-        // eslint-disable-next-line no-console
-        console.warn(
-          `Chart data request retry attempt ${attempt} after ${delay}ms delay`,
-          error,
-        );
-      },
-    });
   }
-
-  // Otherwise, just perform the request normally
-  return performRequest();
+  return v1ChartDataRequest(
+    formData,
+    resultFormat,
+    resultType,
+    force,
+    querySettings,
+    setDataMask,
+    ownState,
+    parseMethod,
+  );
 }
 
 export function runAnnotationQuery({
diff --git a/superset-frontend/src/setup/setupClient.ts b/superset-frontend/src/setup/setupClient.ts
index c6f2399436..8ab5acc2ef 100644
--- a/superset-frontend/src/setup/setupClient.ts
+++ b/superset-frontend/src/setup/setupClient.ts
@@ -31,12 +31,21 @@ function getDefaultConfiguration(): ClientConfig {
     bootstrapData.common.conf.JWT_ACCESS_CSRF_COOKIE_NAME;
   const cookieCSRFToken = parseCookie()[jwtAccessCsrfCookieName] || '';
 
+  // Configure retry behavior from backend settings
+  const retryConfig = bootstrapData.common.conf;
+  const fetchRetryOptions = {
+    retries: retryConfig.SUPERSET_CLIENT_RETRY_ATTEMPTS || 3,
+    retryDelay: retryConfig.SUPERSET_CLIENT_RETRY_DELAY || 1000,
+    retryOn: retryConfig.SUPERSET_CLIENT_RETRY_STATUS_CODES || [502, 503, 504],
+  };
+
   return {
     protocol: ['http:', 'https:'].includes(window?.location?.protocol)
       ? (window?.location?.protocol as 'http:' | 'https:')
       : undefined,
     host: window.location?.host || '',
     csrfToken: csrfToken || cookieCSRFToken,
+    fetchRetryOptions,
   };
 }
 
diff --git a/superset-frontend/src/utils/retryWithExponentialBackoff.test.ts b/superset-frontend/src/utils/retryWithExponentialBackoff.test.ts
deleted file mode 100644
index cd9414647d..0000000000
--- a/superset-frontend/src/utils/retryWithExponentialBackoff.test.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * 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.
- */
-
-import {
-  retryWithExponentialBackoff,
-  retryWithStaggeredDelay,
-} from './retryWithExponentialBackoff';
-
-describe('retryWithExponentialBackoff', () => {
-  it('should return successful result without retry', async () => {
-    const mockFn = jest.fn().mockResolvedValue('success');
-
-    const result = await retryWithExponentialBackoff(mockFn);
-
-    expect(result).toBe('success');
-    expect(mockFn).toHaveBeenCalledTimes(1);
-  });
-
-  it('should retry on failure with exponential backoff', async () => {
-    jest.useFakeTimers();
-
-    const mockFn = jest
-      .fn()
-      .mockRejectedValueOnce(new Error('fail 1'))
-      .mockRejectedValueOnce(new Error('fail 2'))
-      .mockResolvedValue('success');
-
-    const onRetry = jest.fn();
-
-    const promise = retryWithExponentialBackoff(mockFn, {
-      maxRetries: 3,
-      initialDelay: 1000,
-      onRetry,
-    });
-
-    // First attempt fails immediately
-    await Promise.resolve();
-    expect(mockFn).toHaveBeenCalledTimes(1);
-
-    // Advance time and flush promises for first retry
-    await jest.advanceTimersByTimeAsync(1000);
-    expect(mockFn).toHaveBeenCalledTimes(2);
-    expect(onRetry).toHaveBeenCalledWith(1, 1000, new Error('fail 1'));
-
-    // Advance time and flush promises for second retry
-    await jest.advanceTimersByTimeAsync(2000);
-    expect(mockFn).toHaveBeenCalledTimes(3);
-    expect(onRetry).toHaveBeenCalledWith(2, 2000, new Error('fail 2'));
-
-    const result = await promise;
-    expect(result).toBe('success');
-
-    jest.useRealTimers();
-  });
-
-  it('should respect maxRetries limit', async () => {
-    const mockFn = jest.fn().mockRejectedValue(new Error('always fails'));
-
-    const promise = retryWithExponentialBackoff(mockFn, {
-      maxRetries: 2,
-      initialDelay: 100,
-    });
-
-    await expect(promise).rejects.toThrow('always fails');
-    expect(mockFn).toHaveBeenCalledTimes(3); // initial + 2 retries
-  });
-
-  it('should respect shouldRetry condition', async () => {
-    const error = new Error('do not retry');
-    const mockFn = jest.fn().mockRejectedValue(error);
-
-    const promise = retryWithExponentialBackoff(mockFn, {
-      maxRetries: 3,
-      shouldRetry: err => err.message !== 'do not retry',
-    });
-
-    await expect(promise).rejects.toThrow('do not retry');
-    expect(mockFn).toHaveBeenCalledTimes(1);
-  });
-
-  it('should respect maxDelay limit', async () => {
-    const mockFn = jest.fn().mockRejectedValue(new Error('fail'));
-    const onRetry = jest.fn();
-
-    await expect(
-      retryWithExponentialBackoff(mockFn, {
-        maxRetries: 4,
-        initialDelay: 1000,
-        maxDelay: 3000,
-        backoffMultiplier: 2,
-        onRetry,
-      }),
-    ).rejects.toThrow('fail');
-
-    // Check that delays are capped at maxDelay
-    expect(onRetry).toHaveBeenCalledTimes(4);
-    expect(onRetry).toHaveBeenCalledWith(1, 1000, expect.any(Error));
-    expect(onRetry).toHaveBeenCalledWith(2, 2000, expect.any(Error));
-    expect(onRetry).toHaveBeenCalledWith(3, 3000, expect.any(Error)); // capped
-    expect(onRetry).toHaveBeenCalledWith(4, 3000, expect.any(Error)); // capped at maxDelay
-  });
-});
-
-describe('retryWithStaggeredDelay', () => {
-  it('should add stagger delay on first attempt', async () => {
-    jest.useFakeTimers();
-
-    const mockFn = jest.fn().mockResolvedValue('success');
-
-    const promise = retryWithStaggeredDelay(mockFn, {
-      staggerOffset: 500,
-    });
-
-    expect(mockFn).not.toHaveBeenCalled();
-
-    // Advance past stagger delay
-    await jest.advanceTimersByTimeAsync(500);
-
-    const result = await promise;
-    expect(result).toBe('success');
-    expect(mockFn).toHaveBeenCalledTimes(1);
-
-    jest.useRealTimers();
-  });
-
-  it('should apply random stagger when not specified', async () => {
-    jest.useFakeTimers();
-
-    const mockFn = jest.fn().mockResolvedValue('success');
-
-    // Mock Math.random to return a predictable value
-    const originalRandom = Math.random;
-    Math.random = jest.fn().mockReturnValue(0.5);
-
-    const promise = retryWithStaggeredDelay(mockFn);
-
-    // Should wait for ~250ms (0.5 * 500)
-    await jest.advanceTimersByTimeAsync(250);
-
-    const result = await promise;
-    expect(result).toBe('success');
-    expect(mockFn).toHaveBeenCalledTimes(1);
-
-    Math.random = originalRandom;
-    jest.useRealTimers();
-  });
-});
diff --git a/superset-frontend/src/utils/retryWithExponentialBackoff.ts b/superset-frontend/src/utils/retryWithExponentialBackoff.ts
deleted file mode 100644
index 0741fa869a..0000000000
--- a/superset-frontend/src/utils/retryWithExponentialBackoff.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * 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.
- */
-
-export interface RetryOptions {
-  maxRetries?: number;
-  initialDelay?: number;
-  maxDelay?: number;
-  backoffMultiplier?: number;
-  shouldRetry?: (error: any) => boolean;
-  onRetry?: (attemptNumber: number, delay: number, error: any) => void;
-}
-
-const DEFAULT_OPTIONS: Required<RetryOptions> = {
-  maxRetries: 3,
-  initialDelay: 1000,
-  maxDelay: 30000,
-  backoffMultiplier: 2,
-  shouldRetry: () => true,
-  onRetry: () => {},
-};
-
-export async function retryWithExponentialBackoff<T>(
-  fn: () => Promise<T>,
-  options: RetryOptions = {},
-): Promise<T> {
-  const config = { ...DEFAULT_OPTIONS, ...options };
-  let lastError: any;
-
-  for (let attempt = 0; attempt <= config.maxRetries; attempt += 1) {
-    try {
-      // eslint-disable-next-line no-await-in-loop
-      return await fn();
-    } catch (error) {
-      lastError = error;
-
-      if (attempt === config.maxRetries || !config.shouldRetry(error)) {
-        throw error;
-      }
-
-      const baseDelay =
-        config.initialDelay * Math.pow(config.backoffMultiplier, attempt);
-      const delay = Math.min(baseDelay, config.maxDelay);
-
-      config.onRetry(attempt + 1, delay, error);
-
-      // eslint-disable-next-line no-await-in-loop
-      await new Promise(resolve => setTimeout(resolve, delay));
-    }
-  }
-
-  throw lastError;
-}
-
-export function retryWithStaggeredDelay<T>(
-  fn: () => Promise<T>,
-  options: RetryOptions & { staggerOffset?: number } = {},
-): Promise<T> {
-  // Add random jitter to stagger requests
-  const staggerOffset = options.staggerOffset || Math.random() * 500;
-
-  return retryWithExponentialBackoff(async () => {
-    // Add initial stagger delay on first attempt
-    if (staggerOffset > 0) {
-      await new Promise(resolve => setTimeout(resolve, staggerOffset));
-    }
-    return fn();
-  }, options);
-}
diff --git a/superset/config.py b/superset/config.py
index 35f094af0f..7e43f431bd 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -167,16 +167,13 @@ NATIVE_FILTER_DEFAULT_ROW_LIMIT = 1000
 # max rows retrieved by filter select auto complete
 FILTER_SELECT_ROW_LIMIT = 10000
 
-# Native filter retry configuration
-# When dashboard native filters fail to load their values (e.g., due to transient
-# database issues), these settings control the retry behavior with exponential backoff.
-# This helps prevent "Cannot load filter" errors caused by temporary database overload.
-NATIVE_FILTER_RETRY_MAX_ATTEMPTS = 3  # Maximum number of retry attempts
-NATIVE_FILTER_RETRY_INITIAL_DELAY = 1000  # Initial retry delay in milliseconds
-NATIVE_FILTER_RETRY_MAX_DELAY = 10000  # Maximum retry delay in milliseconds
-NATIVE_FILTER_RETRY_BACKOFF_MULTIPLIER = 2  # Multiplier for exponential backoff
-# Random stagger offset prevents multiple filters from hitting the DB simultaneously
-NATIVE_FILTER_RETRY_STAGGER_MAX_OFFSET = 2000  # Maximum random stagger in milliseconds
+# SupersetClient HTTP retry configuration
+# Controls retry behavior for all HTTP requests made through SupersetClient
+# This helps handle transient server errors (like 502 Bad Gateway) automatically
+SUPERSET_CLIENT_RETRY_ATTEMPTS = 3  # Maximum number of retry attempts
+SUPERSET_CLIENT_RETRY_DELAY = 1000  # Initial retry delay in milliseconds
+# HTTP status codes that should trigger retries (502, 503, 504 gateway errors)
+SUPERSET_CLIENT_RETRY_STATUS_CODES = [502, 503, 504]
 # default time filter in explore
 # values may be "Last day", "Last week", "<ISO date> : now", etc.
 DEFAULT_TIME_FILTER = NO_TIME_RANGE
diff --git a/superset/views/base.py b/superset/views/base.py
index f7da8d04cc..e32bdd1b7c 100644
--- a/superset/views/base.py
+++ b/superset/views/base.py
@@ -112,11 +112,9 @@ FRONTEND_CONF_KEYS = (
     "ALERT_REPORTS_DEFAULT_RETENTION",
     "ALERT_REPORTS_DEFAULT_WORKING_TIMEOUT",
     "NATIVE_FILTER_DEFAULT_ROW_LIMIT",
-    "NATIVE_FILTER_RETRY_MAX_ATTEMPTS",
-    "NATIVE_FILTER_RETRY_INITIAL_DELAY",
-    "NATIVE_FILTER_RETRY_MAX_DELAY",
-    "NATIVE_FILTER_RETRY_BACKOFF_MULTIPLIER",
-    "NATIVE_FILTER_RETRY_STAGGER_MAX_OFFSET",
+    "SUPERSET_CLIENT_RETRY_ATTEMPTS",
+    "SUPERSET_CLIENT_RETRY_DELAY",
+    "SUPERSET_CLIENT_RETRY_STATUS_CODES",
     "PREVENT_UNSAFE_DEFAULT_URLS_ON_DATASET",
     "JWT_ACCESS_CSRF_COOKIE_NAME",
     "SQLLAB_QUERY_RESULT_TIMEOUT",