Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(queue): own the submission-retry record in one Queue module (#10310)

Josh Corbett21331d5e2e97
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index ddb22eed96..9ad5a679ad 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -687,6 +687,7 @@
"source:src/features/queue/core/promptBatch.ts",
"source:src/features/queue/core/queueActivity.ts",
"source:src/features/queue/core/retryReport.ts",
+ "source:src/features/queue/core/submissionRetry.ts",
"source:src/features/queue/core/submissionRules.ts",
"source:src/features/queue/core/types.ts",
"source:src/features/queue/data/activeProgressTargetStore.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 7cb08c7774..cb7cd661d6 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -592,6 +592,7 @@
"source:src/features/queue/core/promptBatch.ts",
"source:src/features/queue/core/queueActivity.ts",
"source:src/features/queue/core/retryReport.ts",
+ "source:src/features/queue/core/submissionRetry.ts",
"source:src/features/queue/core/submissionRules.ts",
"source:src/features/queue/data/events.ts",
"source:src/features/queue/data/httpRealtimeQueueBackend.ts",
@@ -1203,6 +1204,7 @@
"source:src/features/queue/core/promptBatch.ts",
"source:src/features/queue/core/queueActivity.ts",
"source:src/features/queue/core/retryReport.ts",
+ "source:src/features/queue/core/submissionRetry.ts",
"source:src/features/queue/core/submissionRules.ts",
"source:src/features/queue/core/types.ts",
"source:src/features/queue/data/activeProgressTargetStore.ts",
@@ -2254,6 +2256,7 @@
"source:src/features/queue/core/promptBatch.ts",
"source:src/features/queue/core/queueActivity.ts",
"source:src/features/queue/core/retryReport.ts",
+ "source:src/features/queue/core/submissionRetry.ts",
"source:src/features/queue/core/submissionRules.ts",
"source:src/features/queue/core/types.ts",
"source:src/features/queue/data/activeProgressTargetStore.ts",
@@ -3633,6 +3636,7 @@
"source:src/features/queue/core/promptBatch.ts",
"source:src/features/queue/core/queueActivity.ts",
"source:src/features/queue/core/retryReport.ts",
+ "source:src/features/queue/core/submissionRetry.ts",
"source:src/features/queue/core/submissionRules.ts",
"source:src/features/queue/core/types.ts",
"source:src/features/queue/data/activeProgressTargetStore.ts",
diff --git a/invokeai/frontend/webv2/src/features/queue/README.md b/invokeai/frontend/webv2/src/features/queue/README.md
index d03425d6e8..61193c46bd 100644
--- a/invokeai/frontend/webv2/src/features/queue/README.md
+++ b/invokeai/frontend/webv2/src/features/queue/README.md
@@ -14,7 +14,7 @@ A reopened run claims as `run:<project, run>` after its tab holds the existing b
## Submission recovery
-A run the backend has not accepted keeps resubmitting, and records its latest failed attempt on the run (`QueueItem.submissionRetry`, cleared once the backend accepts the run or the run ends). Each failure is reconciled before the run submits again, and the run waits from that failure by its own consecutive failures, whatever their reason: 1 s, doubling to at most 15 s. A reconcile never shortens that wait. When the connection comes back after a disconnect, each run this tab is waiting to submit then goes within a random share of 2 s, or sooner if its own wait ends first, so a restarting server and every tab do not get them all at once. The record names why the attempt failed: `unavailable` for 408, 429, 502, 503 and 504; `unreachable` when the request got no answer (`fetch` rejected or timed out); `error` for any other failure that is not a 5xx, such as an answer that could not be read, which may still have committed the batch; all three retry without limit. Any other 5xx is a `server-error` and counts toward a budget: three consecutive ones, the last at least 10 seconds after the first (five attempts at this pace), fail the run with the server's message, unless the reconcile that follows the last finds the backend accepted it after all. Any other failure starts that count over, and so does an attempt starting more than 5 minutes after the run's previous failure, measured from the attempt's start so a slow answer cannot reset its own count; minutes, because a hidden tab's timers may fire only once a minute. The recorded message keeps at most its first 500 characters, ending with an ellipsis when cut, since a 5xx without a JSON body is the whole response page. The whole record travels with the run in the queue-run journal, written again after every failed attempt (so the pace bounds those writes), and a reload or a restarted runtime continues the budget and the remaining wait; restoring bounds the message again and drops a record it cannot read, such as one with a reason it does not know, but keeps the run. Both are judged from the recorded failure times; a clock set back before them restarts the 10 seconds without resetting the count and waits at most one delay.
+A run the backend has not accepted keeps resubmitting, and records its latest failed attempt on the run (`QueueItem.submissionRetry`, cleared once the backend accepts the run or the run ends). Each failure is reconciled before the run submits again, and the run waits from that failure by its own consecutive failures, whatever their reason: 1 s, doubling to at most 15 s. A reconcile never shortens that wait. When the connection comes back after a disconnect, each run this tab is waiting to submit then goes within a random share of 2 s, or sooner if its own wait ends first, so a restarting server and every tab do not get them all at once. The record names why the attempt failed: `unavailable` for 408, 429, 502, 503 and 504; `unreachable` when the request got no answer (`fetch` rejected or timed out); `error` for any other failure that is not a 5xx, such as an answer that could not be read, which may still have committed the batch; all three retry without limit. Any other 5xx is a `server-error` and counts toward a budget: three consecutive ones, the last at least 10 seconds after the first (five attempts at this pace), fail the run with the server's message, unless the reconcile that follows the last finds the backend accepted it after all. Any other failure starts that count over, and so does an attempt starting more than 5 minutes after the run's previous failure, measured from the attempt's start so a slow answer cannot reset its own count; minutes, because a hidden tab's timers may fire only once a minute. The recorded message keeps at most its first 500 characters, ending with an ellipsis when cut, since a 5xx without a JSON body is the whole response page. The whole record travels with the run in the queue-run journal, written again after every failed attempt (so the pace bounds those writes), and a reload or a restarted runtime continues the budget and the remaining wait; restoring bounds the message again and drops a record it cannot read, such as one with a reason it does not know, but keeps the run. Both are judged from the recorded failure times; a clock set back before them restarts the 10 seconds without resetting the count and waits at most one delay. `core/submissionRetry.ts` owns these rules (create, pace, exhausted, clear, equality, restore); the runtime keeps the timers and reconnect spread, and the Workbench reducer and run restoration use it through `@features/queue/contracts`.
## Utility operations
diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.ts
index 24d198b85b..9bbe282844 100644
--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts
@@ -57,6 +57,7 @@ export {
isBackendSubmittableSourceId,
shouldSubmitPendingQueueItem,
} from './core/submissionRules';
+export { isSameSubmissionRetry, restoreSubmissionRetry, withoutSubmissionRetry } from './core/submissionRetry';
export {
extractGenerationMeta,
extractNamedGenerationMeta,
diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.test.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.test.ts
new file mode 100644
index 0000000000..26063a0d6c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.test.ts
@@ -0,0 +1,74 @@
+import type { QueueSubmissionRetry } from '@features/queue/core/historyTypes';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ createSubmissionRetry,
+ isRejectedSubmissionStatus,
+ restoreSubmissionRetry,
+ type QueueSubmissionFailure,
+} from './submissionRetry';
+
+const serverError: QueueSubmissionFailure = { message: 'graph validation crashed', status: 500, unanswered: false };
+const unavailable: QueueSubmissionFailure = { message: 'unavailable', status: 503, unanswered: false };
+
+const persisted: QueueSubmissionRetry = {
+ failedAt: 12_000,
+ failureCount: 3,
+ message: 'graph validation crashed',
+ reason: 'server-error',
+ serverErrorCount: 2,
+ serverErrorSince: 1_000,
+ status: 500,
+};
+
+describe('createSubmissionRetry', () => {
+ // Keyed by reason, so a new reason needs a case.
+ const failures: Record<QueueSubmissionRetry['reason'], QueueSubmissionFailure> = {
+ error: { message: 'Invalid queue enqueue response', status: null, unanswered: false },
+ 'server-error': serverError,
+ unavailable,
+ unreachable: { message: 'Failed to fetch', status: null, unanswered: true },
+ };
+
+ it.each(Object.entries(failures))('keeps a %s retry through persistence and restore', (reason, failure) => {
+ const retry = createSubmissionRetry(failure, undefined, { attemptStartedAt: 1_000, now: 1_000 });
+
+ expect(retry.reason).toBe(reason);
+ expect(restoreSubmissionRetry(JSON.parse(JSON.stringify(retry)))).toEqual(retry);
+ });
+});
+
+describe('isRejectedSubmissionStatus', () => {
+ it.each([
+ [400, true],
+ [422, true],
+ [408, false],
+ [429, false],
+ [500, false],
+ ])('fails the run on %i: %s', (status, rejected) => {
+ expect(isRejectedSubmissionStatus(status)).toBe(rejected);
+ });
+});
+
+describe('restoreSubmissionRetry', () => {
+ it.each([
+ { name: 'a server error that is not counted', value: { ...persisted, serverErrorCount: 0 } },
+ { name: 'a streak starting after its latest failure', value: { ...persisted, serverErrorSince: 13_000 } },
+ { name: 'fewer failures than server errors', value: { ...persisted, failureCount: 1 } },
+ // As a later build might write it.
+ { name: 'a reason this build does not know', value: { ...persisted, reason: 'throttled' } },
+ { name: 'no record', value: null },
+ ])('drops $name', ({ value }) => {
+ expect(restoreSubmissionRetry(value)).toBeUndefined();
+ });
+
+ it('bounds the message again, as records from before the bound may hold a whole response', () => {
+ const page = `<html>${'x'.repeat(5_000)}</html>`;
+
+ expect(restoreSubmissionRetry({ ...persisted, message: page })).toEqual({
+ ...persisted,
+ message: `${page.slice(0, 499)}…`,
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.ts
new file mode 100644
index 0000000000..a1a2c7773c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRetry.ts
@@ -0,0 +1,155 @@
+import type { QueueSubmissionRetry } from '@features/queue/core/historyTypes';
+
+export interface QueueSubmissionFailure {
+ message: string;
+ status: number | null;
+ /** `fetch` rejected, was aborted or timed out. */
+ unanswered: boolean;
+}
+
+// Keyed by reason, so a new reason fails to compile until restore accepts it.
+const SUBMISSION_RETRY_REASONS: Readonly<Record<QueueSubmissionRetry['reason'], true>> = {
+ error: true,
+ 'server-error': true,
+ unavailable: true,
+ unreachable: true,
+};
+
+// A 5xx usually means the request itself is bad, so a run gives up after 3 consecutive 500s over at least 10 s.
+const MAX_SERVER_ERROR_SUBMISSIONS = 3;
+const MIN_SERVER_ERROR_WINDOW_MS = 10_000;
+// Minutes, not retry delays: a hidden tab's timers fire about once a minute and must not reset a streak.
+const SERVER_ERROR_STREAK_GAP_MS = 5 * 60_000;
+const UNAVAILABLE_STATUSES = [408, 429, 502, 503, 504];
+// Waits run from the recorded failure, so a reload keeps them; wall-clock jumps never wait longer than one delay.
+const SUBMISSION_RETRY_BASE_MS = 1_000;
+const SUBMISSION_RETRY_MAX_MS = 15_000;
+
+// A 5xx without a JSON body is the whole response, and the record is persisted on every attempt.
+const MAX_SUBMISSION_RETRY_MESSAGE_LENGTH = 500;
+
+const boundMessage = (message: string): string => {
+ if (message.length <= MAX_SUBMISSION_RETRY_MESSAGE_LENGTH) {
+ return message;
+ }
+ const kept = message.slice(0, MAX_SUBMISSION_RETRY_MESSAGE_LENGTH - 1);
+ return `${/[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept}…`;
+};
+
+const getFailureReason = ({ status, unanswered }: QueueSubmissionFailure): QueueSubmissionRetry['reason'] => {
+ if (status === null) {
+ return unanswered ? 'unreachable' : 'error';
+ }
+ if (UNAVAILABLE_STATUSES.includes(status)) {
+ return 'unavailable';
+ }
+ return status >= 500 ? 'server-error' : 'error';
+};
+
+/** A 4xx the same submission would get again; 408 and 429 retry. */
+export const isRejectedSubmissionStatus = (status: number): boolean =>
+ status >= 400 && status < 500 && !UNAVAILABLE_STATUSES.includes(status);
+
+/** The gap is measured from the attempt's start, so a slow answer cannot reset its own streak. */
+export const createSubmissionRetry = (
+ failure: QueueSubmissionFailure,
+ previous: QueueSubmissionRetry | undefined,
+ { attemptStartedAt, now }: { attemptStartedAt: number; now: number }
+): QueueSubmissionRetry => {
+ const base = {
+ failedAt: now,
+ failureCount: (previous?.failureCount ?? 0) + 1,
+ message: boundMessage(failure.message),
+ status: failure.status,
+ };
+ const reason = getFailureReason(failure);
+ if (reason !== 'server-error') {
+ return { ...base, reason, serverErrorCount: 0, serverErrorSince: null };
+ }
+ const streak =
+ previous?.reason === 'server-error' && attemptStartedAt - previous.failedAt <= SERVER_ERROR_STREAK_GAP_MS
+ ? previous
+ : undefined;
+ const since = streak?.serverErrorSince ?? null;
+ return {
+ ...base,
+ reason,
+ serverErrorCount: (streak?.serverErrorCount ?? 0) + 1,
+ serverErrorSince: since !== null && since <= now ? since : now,
+ };
+};
+
+export const getSubmissionRetryDelayMs = ({ failureCount }: QueueSubmissionRetry): number =>
+ Math.min(SUBMISSION_RETRY_BASE_MS * 2 ** Math.max(failureCount - 1, 0), SUBMISSION_RETRY_MAX_MS);
+
+export const getSubmissionRetryWaitMs = (retry: QueueSubmissionRetry, now: number): number => {
+ const delayMs = getSubmissionRetryDelayMs(retry);
+ return Math.min(Math.max(retry.failedAt + delayMs - now, 0), delayMs);
+};
+
+export const isSubmissionRetryExhausted = (retry: QueueSubmissionRetry): boolean =>
+ retry.reason === 'server-error' &&
+ retry.serverErrorSince !== null &&
+ retry.serverErrorCount >= MAX_SERVER_ERROR_SUBMISSIONS &&
+ retry.failedAt - retry.serverErrorSince >= MIN_SERVER_ERROR_WINDOW_MS;
+
+export const isSameSubmissionRetry = (left: QueueSubmissionRetry | undefined, right: QueueSubmissionRetry): boolean =>
+ left !== undefined &&
+ left.reason === right.reason &&
+ left.failureCount === right.failureCount &&
+ left.serverErrorCount === right.serverErrorCount &&
+ left.serverErrorSince === right.serverErrorSince &&
+ left.status === right.status &&
+ left.message === right.message &&
+ left.failedAt === right.failedAt;
+
+export const withoutSubmissionRetry = <T extends { submissionRetry?: QueueSubmissionRetry }>(
+ item: T
+): Omit<T, 'submissionRetry'> => {
+ if (item.submissionRetry === undefined) {
+ return item;
+ }
+ const { submissionRetry: _, ...rest } = item;
+ return rest;
+};
+
+const isSubmissionRetryReason = (value: unknown): value is QueueSubmissionRetry['reason'] =>
+ typeof value === 'string' && Object.hasOwn(SUBMISSION_RETRY_REASONS, value);
+const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
+const isCount = (value: unknown): value is number => Number.isSafeInteger(value);
+
+/** Drops a record with broken invariants or an unknown reason; older records may hold an unbounded message. */
+export const restoreSubmissionRetry = (value: unknown): QueueSubmissionRetry | undefined => {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ return undefined;
+ }
+ const { failedAt, failureCount, message, reason, serverErrorCount, serverErrorSince, status } = value as Record<
+ string,
+ unknown
+ >;
+ if (
+ !isSubmissionRetryReason(reason) ||
+ typeof message !== 'string' ||
+ !isFiniteNumber(failedAt) ||
+ (status !== null && !(isCount(status) && status >= 100 && status <= 599)) ||
+ !isCount(serverErrorCount) ||
+ serverErrorCount < 0 ||
+ !isCount(failureCount) ||
+ failureCount < Math.max(serverErrorCount, 1) ||
+ (reason === 'server-error') !== serverErrorCount > 0 ||
+ (serverErrorCount === 0
+ ? serverErrorSince !== null
+ : !isFiniteNumber(serverErrorSince) || serverErrorSince > failedAt)
+ ) {
+ return undefined;
+ }
+ return {
+ failedAt,
+ failureCount,
+ message: boundMessage(message),
+ reason,
+ serverErrorCount,
+ serverErrorSince: serverErrorSince as number | null,
+ status,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts
index 35ce0fb04b..af044a26c0 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts
@@ -37,22 +37,3 @@ export const isBackendSubmittableSourceId = (sourceId: QueueSourceId): boolean =
*/
export const shouldSubmitPendingQueueItem = (queueItem: QueueItem): boolean =>
queueItem.status === 'pending' && isBackendSubmittableSourceId(queueItem.snapshot.sourceId);
-
-/**
- * The longest failure message a submission retry keeps. A 5xx without a JSON body is the whole response (an HTML page,
- * a traceback), and the retry is written to state and recovery storage on every attempt. The final failure shows the
- * message as the run's error, so it keeps the leading text rather than one line.
- */
-const MAX_SUBMISSION_RETRY_MESSAGE_LENGTH = 500;
-
-/**
- * The message cut to MAX_SUBMISSION_RETRY_MESSAGE_LENGTH, ending with an ellipsis when cut. The cut never keeps half of
- * a surrogate pair.
- */
-export const boundSubmissionRetryMessage = (message: string): string => {
- if (message.length <= MAX_SUBMISSION_RETRY_MESSAGE_LENGTH) {
- return message;
- }
- const kept = message.slice(0, MAX_SUBMISSION_RETRY_MESSAGE_LENGTH - 1);
- return `${/[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept}…`;
-};
diff --git a/invokeai/frontend/webv2/src/features/queue/index.ts b/invokeai/frontend/webv2/src/features/queue/index.ts
index 6d899d62c3..880c21770e 100644
--- a/invokeai/frontend/webv2/src/features/queue/index.ts
+++ b/invokeai/frontend/webv2/src/features/queue/index.ts
@@ -41,7 +41,6 @@ export {
} from './core/historySummary';
export {
BACKEND_SUBMITTABLE_SOURCE_IDS,
- boundSubmissionRetryMessage,
getQueueSourceResultSelection,
isBackendSubmittableSourceId,
shouldSubmitPendingQueueItem,
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index 4ab9cfca28..9d8fff7347 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -1166,6 +1166,37 @@ describe('queue runtime', () => {
await runtime.dispose();
});
+ it('keeps the 500 streak of a run whose answer took longer than five minutes to come', async () => {
+ vi.useFakeTimers();
+ const workbench = createWorkbenchQueueHistory();
+ const startedAt = Date.now();
+ const slowServerError = () =>
+ new Promise((_resolve, reject) => {
+ setTimeout(() => reject(new ApiError('graph validation crashed', 500)), 6 * 60_000);
+ });
+ const enqueueGenerate = vi
+ .fn()
+ .mockRejectedValueOnce(new ApiError('graph validation crashed', 500))
+ .mockImplementation(slowServerError);
+ const runtime = createQueueRuntime({
+ ...runtimeServices,
+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),
+ history: workbench.history,
+ journal: createTestJournal(),
+ });
+
+ runtime.start();
+ // The second attempt starts at 1 s and its 500 arrives six minutes later.
+ await vi.advanceTimersByTimeAsync(6 * 60_000 + 2_000);
+
+ expect(enqueueGenerate).toHaveBeenCalledTimes(2);
+ expect(workbench.getRun()).toMatchObject({
+ status: 'pending',
+ submissionRetry: { failureCount: 2, serverErrorCount: 2, serverErrorSince: startedAt },
+ });
+ await runtime.dispose();
+ });
+
it.each([
{ error: new ApiError('request timeout', 408), reason: 'unavailable', status: 408 },
{ error: new TypeError('Failed to fetch'), reason: 'unreachable', status: null },
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 1d1e44226a..03f96c9534 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -22,10 +22,14 @@ import {
type QueueWorkflowSeed,
} from '@features/queue/core/promptBatch';
import {
- boundSubmissionRetryMessage,
- QUEUE_SOURCE_RESULT_NODE_IDS,
- shouldSubmitPendingQueueItem,
-} from '@features/queue/core/submissionRules';
+ createSubmissionRetry,
+ getSubmissionRetryDelayMs,
+ getSubmissionRetryWaitMs,
+ isRejectedSubmissionStatus,
+ isSubmissionRetryExhausted,
+ type QueueSubmissionFailure,
+} from '@features/queue/core/submissionRetry';
+import { QUEUE_SOURCE_RESULT_NODE_IDS, shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';
import {
buildQueueItemOrigin,
isTerminalBackendStatus,
@@ -420,75 +424,17 @@ const getJournalSignature = (item: QueueItem): string =>
item.submissionRetry,
]);
-/**
- * Enqueue 5xx usually means a bad request: fail after this many consecutive 500s spanning MIN_SERVER_ERROR_WINDOW_MS.
- * 502/503/504/408/429 stay transient.
- */
-const MAX_SERVER_ERROR_SUBMISSIONS = 3;
-const MIN_SERVER_ERROR_WINDOW_MS = 10_000;
-/** Minutes, not retry delays: a hidden tab's timers may fire only once a minute and must not reset a 500 streak. */
-const SERVER_ERROR_STREAK_GAP_MS = 5 * 60_000;
-const UNAVAILABLE_STATUSES = [408, 429, 502, 503, 504];
-/**
- * Backoff from `failedAt`: 1 s doubling to 15 s; on reconnect waits shrink to a random share of RECONNECT_SPREAD_MS.
- * A wait never exceeds its delay, so a clock change delays a run at most once; exhaustion reads recorded times only.
- */
-const SUBMISSION_RETRY_BASE_MS = 1_000;
-const SUBMISSION_RETRY_MAX_MS = 15_000;
+// On reconnect, waiting runs submit at random within this spread so a restarting server is not hit all at once.
const RECONNECT_SPREAD_MS = 2_000;
-const getSubmissionRetryDelayMs = (failureCount: number): number =>
- Math.min(SUBMISSION_RETRY_BASE_MS * 2 ** Math.max(failureCount - 1, 0), SUBMISSION_RETRY_MAX_MS);
-const getSubmissionWaitMs = (retry: QueueSubmissionRetry, now: number): number => {
- const delayMs = getSubmissionRetryDelayMs(retry.failureCount);
- return Math.min(Math.max(retry.failedAt + delayMs - now, 0), delayMs);
-};
-const isDeterministicServerError = (error: unknown): error is ApiError =>
- error instanceof ApiError && error.status >= 500 && !UNAVAILABLE_STATUSES.includes(error.status);
/** `fetch` rejects with a TypeError when the request gets no answer, and a DOMException when it is aborted. */
const isTransportFailure = (error: unknown): boolean =>
error instanceof TypeError ||
(error instanceof DOMException && ['AbortError', 'NetworkError', 'TimeoutError'].includes(error.name));
-const getRetryReason = (error: unknown): Exclude<QueueSubmissionRetry['reason'], 'server-error'> => {
- if (error instanceof ApiError) {
- return UNAVAILABLE_STATUSES.includes(error.status) ? 'unavailable' : 'error';
- }
- return isTransportFailure(error) ? 'unreachable' : 'error';
-};
-
-/** The streak gap is measured from the attempt's start, so a slow answer cannot reset its own streak. */
-const getSubmissionRetry = (
- error: unknown,
- previous: QueueSubmissionRetry | undefined,
- { attemptStartedAt, now }: { attemptStartedAt: number; now: number }
-): QueueSubmissionRetry => {
- const base = {
- failedAt: now,
- failureCount: (previous?.failureCount ?? 0) + 1,
- message: boundSubmissionRetryMessage(toErrorMessage(error)),
- status: error instanceof ApiError ? error.status : null,
- };
- if (!isDeterministicServerError(error)) {
- return { ...base, reason: getRetryReason(error), serverErrorCount: 0, serverErrorSince: null };
- }
- const streak =
- previous?.reason === 'server-error' && attemptStartedAt - previous.failedAt <= SERVER_ERROR_STREAK_GAP_MS
- ? previous
- : undefined;
- const since = streak?.serverErrorSince ?? null;
- return {
- ...base,
- reason: 'server-error',
- serverErrorCount: (streak?.serverErrorCount ?? 0) + 1,
- serverErrorSince: since !== null && since <= now ? since : now,
- };
-};
-
-const isSubmissionRetryExhausted = (retry: QueueSubmissionRetry): boolean =>
- retry.reason === 'server-error' &&
- retry.serverErrorSince !== null &&
- retry.serverErrorCount >= MAX_SERVER_ERROR_SUBMISSIONS &&
- retry.failedAt - retry.serverErrorSince >= MIN_SERVER_ERROR_WINDOW_MS;
+const toSubmissionFailure = (error: unknown): QueueSubmissionFailure =>
+ error instanceof ApiError
+ ? { message: toErrorMessage(error), status: error.status, unanswered: false }
+ : { message: toErrorMessage(error), status: null, unanswered: isTransportFailure(error) };
const NO_CANCEL_REQUESTS: QueueCancelRequestPort = { wasRequestedHere: () => false };
@@ -567,7 +513,7 @@ export const createQueueRuntime = ({
let reconcileRetryDelayMs = 100;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let submissionTimer: { dueAt: number; timer: ReturnType<typeof setTimeout> } | undefined;
- /** Fixed when the failure is first seen and shortened on reconnect; see SUBMISSION_RETRY_BASE_MS. */
+ // Fixed when a failure is first seen, shortened on reconnect.
const submissionDueTimes = new Map<string, { dueAt: number; failedAt: number }>();
let sawDisconnect = false;
let renewTimer: ReturnType<typeof setInterval> | undefined;
@@ -2143,12 +2089,7 @@ export const createQueueRuntime = ({
}
return;
}
- if (
- error instanceof ApiError &&
- error.status >= 400 &&
- error.status < 500 &&
- ![408, 429].includes(error.status)
- ) {
+ if (error instanceof ApiError && isRejectedSubmissionStatus(error.status)) {
commands.setStatus({
error: toErrorMessage(error),
projectId: project.id,
@@ -2162,8 +2103,8 @@ export const createQueueRuntime = ({
commands.recordSubmissionRetry({
projectId: project.id,
queueItemId: currentQueueItem.id,
- retry: getSubmissionRetry(
- error,
+ retry: createSubmissionRetry(
+ toSubmissionFailure(error),
failedTarget?.project.id === project.id ? failedTarget.queueItem?.submissionRetry : undefined,
{ attemptStartedAt, now: Date.now() }
),
@@ -2315,8 +2256,8 @@ export const createQueueRuntime = ({
const getRemainingSubmissionWaitMs = (key: string, retry: QueueSubmissionRetry, now: number): number => {
let due = submissionDueTimes.get(key);
- if (!due || due.failedAt !== retry.failedAt || due.dueAt - now > getSubmissionRetryDelayMs(retry.failureCount)) {
- due = { dueAt: now + getSubmissionWaitMs(retry, now), failedAt: retry.failedAt };
+ if (!due || due.failedAt !== retry.failedAt || due.dueAt - now > getSubmissionRetryDelayMs(retry)) {
+ due = { dueAt: now + getSubmissionRetryWaitMs(retry, now), failedAt: retry.failedAt };
submissionDueTimes.set(key, due);
}
return Math.max(due.dueAt - now, 0);
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts
index b7b36e9bb8..ebf9556cd7 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts
@@ -205,7 +205,7 @@ describe('IndexedDB queue run journal', () => {
]);
});
- it('keeps the failed submission of a run not yet accepted, and drops a malformed or stale one without losing the run', async () => {
+ it('keeps the failed submission of a run not yet accepted, and drops an unreadable or stale one without losing the run', async () => {
const { journal } = await createJournal();
const store = createWorkbenchStore();
const projectId = store.getState().activeProjectId;
@@ -219,46 +219,19 @@ describe('IndexedDB queue run journal', () => {
status: 500,
};
const retrying = createItem({ submissionRetry: retry });
- // A server error must be counted, and its window cannot start after the failure it ends with.
- const miscounted = createItem({ id: 'queue-item-2', submissionRetry: { ...retry, serverErrorCount: 0 } });
- const backwards = createItem({ id: 'queue-item-3', submissionRetry: { ...retry, serverErrorSince: 13_000 } });
- // Every server error is a failed submission.
- const undercounted = createItem({ id: 'queue-item-5', submissionRetry: { ...retry, failureCount: 1 } });
// A run the backend accepted has no submission left to retry.
const accepted = createItem({
backendItemIds: [11],
- id: 'queue-item-4',
+ id: 'queue-item-2',
status: 'running',
submissionRetry: retry,
});
- // A failure that is neither a server error nor a transport failure keeps its own reason.
- const otherError = {
- ...retry,
- message: 'Invalid queue enqueue response',
- reason: 'error' as const,
- serverErrorCount: 0,
- serverErrorSince: null,
- status: null,
- };
- const unreadable = createItem({ id: 'queue-item-6', submissionRetry: otherError });
- // A reason this build does not know, as a later build might write it.
+ // As a later build might write it.
const unknownReason = createItem({
- id: 'queue-item-7',
- submissionRetry: { ...otherError, reason: 'throttled' } as unknown as WorkbenchQueueItem['submissionRetry'],
+ id: 'queue-item-3',
+ submissionRetry: { ...retry, reason: 'throttled' } as unknown as WorkbenchQueueItem['submissionRetry'],
});
- // Written before messages were bounded: a whole HTML error page.
- const page = `<html>${'x'.repeat(5_000)}</html>`;
- const longMessage = createItem({ id: 'queue-item-8', submissionRetry: { ...retry, message: page } });
- for (const item of [
- retrying,
- miscounted,
- backwards,
- undercounted,
- accepted,
- unreadable,
- unknownReason,
- longMessage,
- ]) {
+ for (const item of [retrying, accepted, unknownReason]) {
await journal.record(projectId, item);
}
@@ -274,12 +247,7 @@ describe('IndexedDB queue run journal', () => {
status: 'pending',
submissionRetry: retry,
});
- expect(restored.find((item) => item.id === unreadable.id)).toMatchObject({ submissionRetry: otherError });
- expect(restored.find((item) => item.id === longMessage.id)?.submissionRetry).toEqual({
- ...retry,
- message: `${page.slice(0, 499)}…`,
- });
- for (const item of [miscounted, backwards, undercounted, accepted, unknownReason]) {
+ for (const item of [accepted, unknownReason]) {
const restoredItem = restored.find((candidate) => candidate.id === item.id);
expect(restoredItem).toMatchObject({ status: item.status });
expect(restoredItem).not.toHaveProperty('submissionRetry');
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
index 3491a15bba..abe4d341e3 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
@@ -1,8 +1,8 @@
-import type { QueueSubmissionRetry } from '@features/queue/contracts';
import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';
import { cloneGenerateWidgetValues, normalizeGenerateWidgetValues } from '@features/generation/settings';
-import { boundSubmissionRetryMessage, MAX_QUEUE_BATCH_ITEMS } from '@features/queue';
+import { MAX_QUEUE_BATCH_ITEMS } from '@features/queue';
+import { restoreSubmissionRetry } from '@features/queue/contracts';
import { cloneVideoWidgetValues, normalizeVideoWidgetValues } from '@features/video';
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -15,44 +15,6 @@ const isBackendItemIdList = (value: unknown): value is number[] =>
new Set(value).size === value.length &&
value.every((item) => Number.isSafeInteger(item) && item > 0);
-/**
- * A retry record only means something with its invariants intact; anything else, including a reason a later build
- * added, is dropped, never the run. Its message is bounded again, as records from before the bound may hold a whole
- * response body.
- */
-const normalizeSubmissionRetry = (value: unknown): QueueSubmissionRetry | undefined => {
- if (!isRecord(value)) {
- return undefined;
- }
- const { failedAt, failureCount, message, reason, serverErrorCount, serverErrorSince, status } = value;
- if (
- (reason !== 'error' && reason !== 'server-error' && reason !== 'unavailable' && reason !== 'unreachable') ||
- typeof message !== 'string' ||
- !isFiniteNumber(failedAt) ||
- (status !== null && !(Number.isSafeInteger(status) && (status as number) >= 100 && (status as number) <= 599)) ||
- !Number.isSafeInteger(serverErrorCount) ||
- (serverErrorCount as number) < 0 ||
- // Server errors are among the consecutive failures, and the latest failure is one of them.
- !Number.isSafeInteger(failureCount) ||
- (failureCount as number) < Math.max(serverErrorCount as number, 1) ||
- (reason === 'server-error') !== (serverErrorCount as number) > 0 ||
- (serverErrorCount === 0
- ? serverErrorSince !== null
- : !isFiniteNumber(serverErrorSince) || serverErrorSince > failedAt)
- ) {
- return undefined;
- }
- return {
- failedAt,
- failureCount: failureCount as number,
- message: boundSubmissionRetryMessage(message),
- reason,
- serverErrorCount: serverErrorCount as number,
- serverErrorSince: serverErrorSince as number | null,
- status: status as number | null,
- };
-};
-
export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem | null => {
if (
!isRecord(value) ||
@@ -143,7 +105,7 @@ export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem |
// Only a run the backend has not accepted is still being submitted.
const submissionRetry =
- value.status === 'pending' && !backendItemIds?.length ? normalizeSubmissionRetry(value.submissionRetry) : undefined;
+ value.status === 'pending' && !backendItemIds?.length ? restoreSubmissionRetry(value.submissionRetry) : undefined;
let recall: WorkbenchQueueItem['snapshot']['recall'];
try {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 4b5eb3482b..e4cfca9bb0 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -175,8 +175,10 @@ import { getQueueSourceResultSelection, MAX_QUEUE_BATCH_ITEMS } from '@features/
import {
getAutoSwitchFollowedLive,
getQueueItemSnapshotLabel,
+ isSameSubmissionRetry,
pickAutoSwitch,
selectsLandedResult,
+ withoutSubmissionRetry,
} from '@features/queue/contracts';
import {
clearDeletedUpscaleInput,
@@ -3726,24 +3728,6 @@ const reopenQueueItemForRetry = (
});
};
-const isSameSubmissionRetry = (left: QueueSubmissionRetry | undefined, right: QueueSubmissionRetry): boolean =>
- left !== undefined &&
- left.reason === right.reason &&
- left.failureCount === right.failureCount &&
- left.serverErrorCount === right.serverErrorCount &&
- left.serverErrorSince === right.serverErrorSince &&
- left.status === right.status &&
- left.message === right.message &&
- left.failedAt === right.failedAt;
-
-const withoutSubmissionRetry = (item: QueueItem): QueueItem => {
- if (item.submissionRetry === undefined) {
- return item;
- }
- const { submissionRetry: _, ...rest } = item;
- return rest;
-};
-
const mergeBackendItemId = (ids: number[] | undefined, backendItemId: number): number[] =>
ids?.includes(backendItemId) ? ids : [...(ids ?? []), backendItemId];
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index fcc840e667..727584dc0d 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -364,6 +364,7 @@ const GALLERY_STATE_MODULES = [
'/features/queue/core/historySnapshot.ts',
'/features/queue/core/historySummary.ts',
'/features/queue/core/progressRail.ts',
+ '/features/queue/core/submissionRetry.ts',
'/features/queue/core/submissionRules.ts',
'/features/queue/data/events.ts',
] as const;