π OpenHands: AI-Driven Development
fix(settings): don't retry a 4xx answer when saving settings (#18490)
Engel Nysta2d7b0442533
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.tsindex eef2f3476e..759b8be83b 100644--- a/__tests__/api/settings-service.test.ts+++ b/__tests__/api/settings-service.test.ts@@ -296,6 +296,26 @@ describe("SettingsService", () => {expect(requestedBackends).toEqual(["a", "a", "b"]);});+ it("rejects a settings save the server answers with 422 after one request", async () => {+ let patchCount = 0;+ server.use(+ http.patch("*/api/settings", () => {+ patchCount += 1;+ return HttpResponse.json(+ { detail: "Settings validation failed" },+ { status: 422 },+ );+ }),+ );++ await expect(+ SettingsService.saveSettings({+ agent_settings_diff: { condenser: { max_size: -5 } },+ }),+ ).rejects.toMatchObject({ status: 422 });+ expect(patchCount).toBe(1);+ });+it("skips API call when no diffs are provided to saveSettings", async () => {const fetchSpy = vi.spyOn(SettingsService, "fetchSettingsFromApi");@@ -1258,7 +1278,8 @@ describe("SettingsService", () => {).rejects.toBeDefined();expect(getCount).toBe(0);- expect(patchBodies).toHaveLength(3);+ // A 400 is the server rejecting the payload, so it is sent once.+ expect(patchBodies).toHaveLength(1);expect(patchBodies).not.toContainEqual({agent_settings_diff: { mcp_config: null },});diff --git a/__tests__/api/with-retry.test.ts b/__tests__/api/with-retry.test.tsnew file mode 100644index 0000000000..c99aea398c--- /dev/null+++ b/__tests__/api/with-retry.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AxiosError, AxiosHeaders } from "axios";+import { HttpError } from "@openhands/typescript-client";++import { isRetryableError, withRetry } from "#/api/with-retry";++const axiosErrorWithStatus = (status: number) =>+ new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {+ status,+ statusText: "",+ data: {},+ headers: {},+ config: { headers: new AxiosHeaders() },+ });++describe("isRetryableError", () => {+ it.each([400, 401, 403, 404, 409, 422])(+ "does not retry a %i answer",+ (status) => {+ expect(isRetryableError(new HttpError(status, ""))).toBe(false);+ expect(isRetryableError(axiosErrorWithStatus(status))).toBe(false);+ },+ );++ it.each([408, 429, 500, 502, 503])("retries a %i answer", (status) => {+ expect(isRetryableError(new HttpError(status, ""))).toBe(true);+ expect(isRetryableError(axiosErrorWithStatus(status))).toBe(true);+ });++ it("retries failures the server never answered", () => {+ expect(isRetryableError(new TypeError("Failed to fetch"))).toBe(true);+ expect(isRetryableError(new AxiosError("Network Error"))).toBe(true);+ expect(isRetryableError("boom")).toBe(true);+ });+});++describe("withRetry", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("throws a 4xx answer after the first attempt", async () => {+ const error = new HttpError(422, "Unprocessable Entity", {+ detail: "Settings validation failed",+ });+ const fn = vi.fn().mockRejectedValue(error);++ await expect(withRetry(fn)).rejects.toBe(error);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it("retries a 5xx answer with backoff until it succeeds", async () => {+ vi.useFakeTimers();+ const fn = vi+ .fn()+ .mockRejectedValueOnce(new HttpError(503, "Service Unavailable"))+ .mockRejectedValueOnce(new HttpError(503, "Service Unavailable"))+ .mockResolvedValue("ok");++ const result = withRetry(fn);+ await vi.runAllTimersAsync();++ await expect(result).resolves.toBe("ok");+ expect(fn).toHaveBeenCalledTimes(3);+ });++ it("gives up after the last attempt on a retryable error", async () => {+ vi.useFakeTimers();+ const error = new HttpError(500, "Internal Server Error");+ const fn = vi.fn().mockRejectedValue(error);++ const assertion = expect(withRetry(fn)).rejects.toBe(error);+ await vi.runAllTimersAsync();+ await assertion;+ expect(fn).toHaveBeenCalledTimes(3);+ });+});diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.tsindex e29ab26ddd..bed02805ce 100644--- a/src/api/settings-service/settings-service.api.ts+++ b/src/api/settings-service/settings-service.api.ts@@ -23,6 +23,7 @@ import {getAgentServerClientOptions,type AgentServerClientOptions,} from "../agent-server-client-options";+import { withRetry } from "../with-retry";/*** Fields the agent-server stores under `misc_settings.app_preferences` (see@@ -140,33 +141,6 @@ const mergeRecords = (next: Record<string, SettingsValue> | null | undefined,) => ({ ...(base ?? {}), ...(next ?? {}) });-/**- * Retry helper for API calls with exponential backoff.- */-async function withRetry<T>(- fn: () => Promise<T>,- maxRetries: number = 3,- baseDelayMs: number = 500,-): Promise<T> {- for (let attempt = 0; attempt < maxRetries; attempt += 1) {- try {- return await fn();- } catch (error) {- if (attempt >= maxRetries - 1) {- throw error;- }-- const delay = baseDelayMs * 2 ** attempt;-- await new Promise<void>((resolve) => {- setTimeout(resolve, delay);- });- }- }-- throw new Error("Retry attempts exhausted");-}-const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutestype SettingsExposureMode = "redacted" | "encrypted";diff --git a/src/api/with-retry.ts b/src/api/with-retry.tsindex d22f104664..83a002a010 100644--- a/src/api/with-retry.ts+++ b/src/api/with-retry.ts@@ -1,5 +1,37 @@/**- * Retry helper for API calls with exponential backoff.+ * The HTTP status a failed call answered with, from either transport the app+ * uses: the shared TypeScript client's `HttpError` (`status`) or Axios+ * (`response.status`). `undefined` when the server never answered, e.g. a+ * network error or a timeout.+ */+function getHttpStatus(error: unknown): number | undefined {+ if (typeof error !== "object" || error === null) return undefined;+ const { response, status } = error as {+ response?: { status?: unknown };+ status?: unknown;+ };+ if (typeof response?.status === "number") return response.status;+ if (typeof status === "number") return status;+ return undefined;+}++/**+ * Whether a failed call may succeed if sent again. A 4xx answer is the+ * server rejecting the request itself (validation, auth, not found), so the+ * same request gets the same answer; only 408 (timeout) and 429 (rate limit)+ * among them are worth another try. Server errors (5xx) and failures with no+ * answer at all can be transient.+ */+export function isRetryableError(error: unknown): boolean {+ const status = getHttpStatus(error);+ if (status === undefined) return true;+ if (status === 408 || status === 429) return true;+ return status < 400 || status >= 500;+}++/**+ * Retry helper for API calls with exponential backoff. Errors that+ * {@link isRetryableError} rejects are thrown on the first attempt.*/export async function withRetry<T>(fn: () => Promise<T>,@@ -10,7 +42,7 @@ export async function withRetry<T>(try {return await fn();} catch (error) {- if (attempt >= maxRetries - 1) {+ if (attempt >= maxRetries - 1 || !isRetryableError(error)) {throw error;}