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.

fix(queue): recover ambiguous admission and delivery acknowledgements (#10162)

Josh Corbett48ef49440dc1
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index fdecc52c3e..d94c0b8835 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -509,6 +509,7 @@
"source:src/app/accountLifecycle.ts",
"source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
+ "source:src/app/queueStagedResults.ts",
"source:src/app/router.tsx",
"source:src/app/startupRedirect.ts",
"source:src/app/workbenchPorts.tsx",
@@ -701,6 +702,7 @@
"source:src/features/queue/runtime.ts",
"source:src/features/queue/runtime/cancelRequests.ts",
"source:src/features/queue/runtime/coordinator.ts",
+ "source:src/features/queue/runtime/deliveryClaims.ts",
"source:src/features/queue/runtime/receiptAcknowledgements.ts",
"source:src/features/queue/ui/QueueUiContext.tsx",
"source:src/features/queue/ui/currentBatchItems.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index bbb552f29b..dff52e984d 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -913,6 +913,7 @@
"source:src/app/accountLifecycle.ts",
"source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
+ "source:src/app/queueStagedResults.ts",
"source:src/app/router.tsx",
"source:src/app/startupRedirect.ts",
"source:src/app/workbenchPorts.tsx",
@@ -1213,6 +1214,7 @@
"source:src/features/queue/runtime.ts",
"source:src/features/queue/runtime/cancelRequests.ts",
"source:src/features/queue/runtime/coordinator.ts",
+ "source:src/features/queue/runtime/deliveryClaims.ts",
"source:src/features/queue/runtime/receiptAcknowledgements.ts",
"source:src/features/queue/runtime/utilityGraph.ts",
"source:src/features/queue/ui/QueueDataRuntime.tsx",
@@ -2079,6 +2081,7 @@
"source:src/app/accountLifecycle.ts",
"source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
+ "source:src/app/queueStagedResults.ts",
"source:src/app/router.tsx",
"source:src/app/startupRedirect.ts",
"source:src/app/workbenchPorts.tsx",
@@ -2387,6 +2390,7 @@
"source:src/features/queue/runtime.ts",
"source:src/features/queue/runtime/cancelRequests.ts",
"source:src/features/queue/runtime/coordinator.ts",
+ "source:src/features/queue/runtime/deliveryClaims.ts",
"source:src/features/queue/runtime/receiptAcknowledgements.ts",
"source:src/features/queue/runtime/utilityGraph.ts",
"source:src/features/queue/ui/QueueDataRuntime.tsx",
@@ -3432,6 +3436,7 @@
"source:src/app/accountLifecycle.ts",
"source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
+ "source:src/app/queueStagedResults.ts",
"source:src/app/router.tsx",
"source:src/app/startupRedirect.ts",
"source:src/app/workbenchPorts.tsx",
@@ -3733,6 +3738,7 @@
"source:src/features/queue/runtime.ts",
"source:src/features/queue/runtime/cancelRequests.ts",
"source:src/features/queue/runtime/coordinator.ts",
+ "source:src/features/queue/runtime/deliveryClaims.ts",
"source:src/features/queue/runtime/receiptAcknowledgements.ts",
"source:src/features/queue/runtime/utilityGraph.ts",
"source:src/features/queue/ui/CancelQueueItemButton.tsx",
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
index edd68aa4e0..c7a5fc1922 100644
--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
@@ -1,3 +1,4 @@
+import { getQueueStagedResults } from '@app/queueStagedResults';
import { invalidateGallery, invalidateGalleryBoardDestinations } from '@features/gallery/queries';
import { getAuthSession } from '@features/identity';
import { modelLoadActivitySink } from '@features/models';
@@ -124,6 +125,7 @@ export const QueueRuntimeAdapter = () => {
refreshBackendData: () => void invalidateGallery(queryClient),
refreshBoardDestinations: () => void invalidateGalleryBoardDestinations(queryClient),
},
+ listStagedResults: () => getQueueStagedResults(queries.getSnapshot().projects),
getSnapshot: () => {
const snapshot = queries.getSnapshot();
diff --git a/invokeai/frontend/webv2/src/app/queueStagedResults.test.ts b/invokeai/frontend/webv2/src/app/queueStagedResults.test.ts
new file mode 100644
index 0000000000..2bde2ddc3a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/queueStagedResults.test.ts
@@ -0,0 +1,43 @@
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
+import { expect, it } from 'vitest';
+
+import { getQueueStagedResults } from './queueStagedResults';
+
+it('projects real reducer candidates, including multiple outputs, while excluding absent backend provenance', () => {
+ let state = createInitialWorkbenchState();
+ const projectId = state.activeProjectId;
+ state = workbenchReducer(state, {
+ type: 'stageRetriedCanvasResults',
+ backendItemId: 99,
+ projectId,
+ queueItemId: 'run',
+ images: ['one.png', 'two.png'].map((imageName) => ({
+ imageName,
+ sourceQueueItemId: 'run',
+ queuedAt: '2026-11-05T00:00:00Z',
+ width: 64,
+ height: 64,
+ imageUrl: `/${imageName}`,
+ thumbnailUrl: `/${imageName}`,
+ })),
+ });
+ const project = state.projects.find((project) => project.id === projectId)!;
+ expect(project.canvas.stagingArea.pendingImages).toHaveLength(2);
+ const unknown = { ...project.canvas.stagingArea.pendingImages[0]!, id: 'unknown', sourceBackendItemId: undefined };
+ const projects = [
+ {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ stagingArea: {
+ ...project.canvas.stagingArea,
+ pendingImages: [...project.canvas.stagingArea.pendingImages, unknown],
+ },
+ },
+ },
+ ];
+ expect(getQueueStagedResults(projects)).toEqual([
+ { backendItemId: 99, projectId, queueItemId: 'run' },
+ { backendItemId: 99, projectId, queueItemId: 'run' },
+ ]);
+});
diff --git a/invokeai/frontend/webv2/src/app/queueStagedResults.ts b/invokeai/frontend/webv2/src/app/queueStagedResults.ts
new file mode 100644
index 0000000000..acfc5b2b61
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/queueStagedResults.ts
@@ -0,0 +1,17 @@
+import type { Project } from '@workbench/projectContracts';
+
+/** Translate persisted Canvas candidate provenance into Queue's delivery-recovery read model. */
+export const getQueueStagedResults = (projects: readonly Pick<Project, 'id' | 'canvas'>[]) =>
+ projects.flatMap((project) =>
+ project.canvas.stagingArea.pendingImages.flatMap((candidate) =>
+ candidate.sourceBackendItemId === undefined
+ ? []
+ : [
+ {
+ backendItemId: candidate.sourceBackendItemId,
+ projectId: project.id,
+ queueItemId: candidate.sourceQueueItemId,
+ },
+ ]
+ )
+ );
diff --git a/invokeai/frontend/webv2/src/features/queue/README.md b/invokeai/frontend/webv2/src/features/queue/README.md
index 5ae0e4da6d..abafa1dfc9 100644
--- a/invokeai/frontend/webv2/src/features/queue/README.md
+++ b/invokeai/frontend/webv2/src/features/queue/README.md
@@ -6,13 +6,25 @@ Queue's private `QueueBackendPort` is adapter seam; public callers use domain re
Queue exposes board-independent active backend sessions, including preparation and result settlement. Gallery progress section includes every unfinished batch slot, queued work too; Preview follows executing and settling sessions. Both use gallery-destination projections of active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions take no part in board counts, saved-image selection, or navigation. Saved outputs keep their actual backend board destinations; automatic result selection does not change browsed board or its paging window.
-Retry re-runs failed or canceled backend items under new ids; the run owning them reopens around the reruns so its captured destination receives their results. A rerun no open run adopts reaches the Gallery, or the current Canvas of a tab with its project open. Canvas reruns are staged once across every tab and browser of the account through a delivery claim the server keeps per queue item (`POST queue/{id}/i/{item_id}/delivery`): a claimant claims, stages, then confirms; a claim neither confirmed nor released lapses after two minutes. A reopened run claims its reruns as `run:<project, run>` once its tab holds the run, renews them while it lasts, and gives back what it did not stage when the tab lets the run go, so a reload restores the same claimant and a run never stages a rerun another tab staged first. A tab the browser freezes stops renewing; another tab then stages the rerun at its own current bbox. A tab staging a rerun no run adopted claims as itself, after waiting for any tab of the browser that still tracks the run, and asks again while another claimant holds the rerun. A server without the endpoint lets every tab stage.
+Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.
+
+Retry re-runs failed or canceled backend items under new ids; the run owning them reopens around the reruns so its captured destination receives their results. A rerun no open run adopts reaches the Gallery, or the current Canvas of a tab with its project open. Canvas reruns use an account-wide server delivery claim (`POST queue/{id}/i/{item_id}/delivery`): claim, stage locally, then confirm. Local staging and server acknowledgement are separate. The account runtime shares one confirmation budget per staged backend item across run/tab claimants and synchronous notifications. `runtime/deliveryClaims.ts` drains at most eight confirmation requests concurrently. A failed or lost confirmation retries idempotently at most five times with 1/2/4/8-second waits while this account's runtime is active; definitive client errors stop retries. Only actually granted live claims renew every 40 seconds: adopted claims before staging, and owned staged claims while confirmation is queued or unresolved. The latter use a separate coalesced drain of at most eight renewal requests, so a recovery backlog cannot leave a live claimant idle for its lease lifetime. Recovery/fail-open staging never marks a claim owned; deduplicated confirmation can upgrade to the actual holder without changing its retry budget. Confirmation does not claim arbitrary recovered items. Exhaustion reports that local results remain staged but another browser may deliver them again; the same candidate does not automatically restart its budget in that runtime. A later editor/project recovery may start a fresh budget. Delivery requests time out after 10 seconds. Server confirmation is claimant-independent even after a lease changes; only a response of `delivered` confirms server delivery; a lost successful response is harmless on replay. Staged work is never released. Unstaged work is released when its run ends or its project closes, while an abandoned claim lapses after two minutes. Same-account disposal releases owned unstaged claims, including late grants. Account changes fence releases as well as confirmations; abandoned leases expire. Disposal/account changes stop owned retries and renewals; they do not establish server cancellation or confirmation.
+
+A reopened run claims as `run:<project, run>` after its tab holds the existing browser run lock. A tab staging an unadopted rerun claims as itself, after waiting for the browser tab tracking the run. Another claimant waits until confirmation or lease expiry. Each image retains its producing backend item id through batch result flattening, so Canvas acknowledgement never depends on its position in the image list. Production's history adapter exposes existing Canvas candidates with their backend ids: routing must actually leave a candidate before confirmation, and candidates restored through project recovery resume acknowledgement without restaging. Live routing excludes known ordinary results from metadata recovery before staging notifies subscribers, and retains that exclusion only while their candidates survive, independently of queue history. Restored candidates are unknown and require authoritative validation. Recovery reads backend metadata serially in batches of 64, with a 10-second timeout and at most three attempts separated by 1/2-second waits. Only rows with retry ancestry, Canvas destination, and the candidate's project/run origin are confirmed; ordinary staged generations do not trigger confirmation after reload or completed-history clearing. A missing backend row cannot be recovered. An exhausted metadata batch stops recovery for that runtime and reports the need to reload the editor, rather than continuing through an outage with all remaining candidates. This adds no persisted fields. Recovery requires that the candidate survived existing project/journal persistence; a crash before that, or removal of a candidate before an offline acknowledgement and reload, has no durable delivery ledger. A frozen browser can lose its lease to another browser. Local image deduplication only protects the current project snapshot; these guarantees do not establish global exactly-once delivery. Claims intentionally fail open when the endpoint is unsupported (404), or remains unavailable for a claim lifetime, preserving availability with a risk of duplicate delivery across stale browser snapshots.
+
+## 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.
-`submitUtilityGraph` (`@features/queue/utility`) returns once the backend accepts the graph; its `settled` watch ends on the first of: a terminal status event for its origin; a re-read of its accepted items that finds a terminal status or answers 404 (`removed`), triggered by `queue_cleared`, a reconnect after a disconnect, `queue_items_canceled` naming an accepted id, or the periodic reconcile read, which re-arms while the item stays open; or an abort of its signal (`aborted`), which stops watching and leaves the backend item alone.
+## Utility operations
-Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.
+Utility graphs (`@features/queue/utility`) get a fresh operation origin/key per deliberate invocation. Admission freezes graph, origin, prepend and key, uses at most three 10-second POST attempts, and looks up the same receipt after ambiguous failures (each read also bounded to 10 seconds). Missing/unavailable receipts replay that same key after abortable 1/2-second waits between admission/receipt pairs: absence is not evidence the first POST cannot commit. Conflicts and definitive validation errors are surfaced. The backend's existing project-less idempotency contract admits one logical operation across these retries. Exhausted admission recovery explicitly reports that backend work may still be running; calling the API again is a new operation, and reload recovery is unavailable because utility operations own no persistent ledger.
+
+The runtime acknowledges a utility receipt only after retaining accepted ids, including late ids needed for best-effort cancellation or malformed-response cleanup. Acknowledgement is independent of watching and retries at most five times with 1/2/4/8-second waits and a 10-second request bound. Definitive client rejections stop acknowledgement retries. Account changes abort these requests and waits; retries never run under a replacement account. Failed final acknowledgement or reload before acknowledgement can leave a server receipt; no unbounded in-memory retry or new persistence is introduced. Acknowledged receipts use the server's existing retention policy; unacknowledged receipts have no TTL and count against the 10,000-receipt quota shared with keyed generation enqueues. Exhausted utility acknowledgement is not reclaimed automatically; filling that quota rejects all keyed enqueues with 429 until server receipts are reclaimed. Server-side expiry/reclamation of abandoned unacknowledged receipts remains a follow-up.
+
+Both utility APIs reconcile accepted status every 15 seconds while active, coalescing overlapping reconnect, clear, bulk-cancel and periodic reads with one follow-up read for events received during an outstanding read. Each production status read times out after 10 seconds: with a responsive backend, a missed terminal event is observed within one interval plus its read latency. Failed/canceled items and removed items (404) settle truthfully. Transient read failures leave the watch open for the next event/read. Three consecutive failed reads for an item spanning at least 30 seconds end the watch with a visible reconciliation error saying backend work may still be running. Event bursts cannot exhaust the budget immediately; every successful status read, including pending, in_progress and waiting, resets that item's health budget. With interval-driven immediate failures this settles at about 45 seconds after admission; hung 10-second reads settle by about 75 seconds. No cancellation is claimed by this health error. `runUtilityGraph` recovers completed output with bounded retries; malformed data fails reconciliation. There is no universal utility deadline, so model downloads, long queue waits and calibration remain supported. An explicit `timeoutMs` covers admission and waiting; before reporting timeout it performs an authoritative status read, allowing completed-output recovery to finish. Output reads/retries are separate from admission retries.
+
+`submitUtilityGraph` returns accepted ids and a `settled` promise. Aborting it stops watching and leaves accepted backend work alone. Aborting or explicitly timing out `runUtilityGraph` requests best-effort cancellation, including ids recovered after the caller stopped waiting; cancellation is never represented as confirmed. Account changes stop watches and fence late cancellation from a replacement account. Terminal paths detach listeners and stop periodic and retry timers. Rerun retry waits resolve on abort as before, remove their abort listener after ordinary completion, and clear their timer on abort.
## Actions
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 533127f257..ea87c31813 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -124,6 +124,8 @@ export interface QueueResultImage {
imageUrl: string;
isIntermediate?: boolean;
queuedAt: string;
+ /** Retained across result flattening so Canvas delivery acknowledges the item that produced each image. */
+ sourceBackendItemId?: number;
sourceQueueItemId: string;
thumbnailUrl: string;
width: number;
diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
index cbbc611fce..6c9d76c620 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
@@ -287,7 +287,7 @@ export const claimQueueItemDelivery = async (
const result = await apiFetchJson<QueueItemDeliveryResultDTO>(buildQueueUrl(`i/${itemId}/delivery`), {
body: JSON.stringify({ action, claimant }),
method: 'POST',
- signal: owner.signal,
+ signal: AbortSignal.any([owner.signal, AbortSignal.timeout(10_000)]),
});
assertAccountScopeCurrent(owner);
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
index 315838cd22..bc5bcd548f 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -1,14 +1,15 @@
import type { QueueEnqueueGenerateRequest, QueueEnqueueWorkflowRequest } from '@features/queue/core/types';
import { accountLifecycle } from '@platform/state/accountLifecycle';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
apiFetch: vi.fn(),
apiFetchJson: vi.fn(),
}));
-vi.mock('@platform/transport/http', () => ({
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
absolutizeApiUrl: (url: string) => url,
ApiError: class ApiError extends Error {
status: number;
@@ -440,16 +441,151 @@ describe('enqueueWorkflow', () => {
});
describe('enqueueUtility', () => {
+ afterEach(() => vi.useRealTimers());
+ const request = {
+ graph: { edges: [], id: 'utility', nodes: {} },
+ idempotencyKey: 'utility:operation',
+ origin: 'webv2:util:operation',
+ prepend: true,
+ };
+
+ it('recovers accepted admission from a receipt after the response is lost', async () => {
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchJson.mockRejectedValueOnce(new TypeError('lost response')).mockResolvedValueOnce({
+ batch_id: 'accepted',
+ enqueued: 1,
+ item_ids: [41],
+ requested: 1,
+ });
+ const result = await enqueueUtility(request);
+ expect(result.itemIds).toEqual([41]);
+ expect(mocks.apiFetchJson.mock.calls.map(([url]) => url)).toEqual([
+ '/api/v1/queue/default/enqueue_batch',
+ '/api/v1/queue/default/enqueue_batch/receipt?idempotency_key=utility%3Aoperation',
+ ]);
+ expect(mocks.apiFetch).not.toHaveBeenCalled();
+ });
+
+ it('replays the same frozen payload when an absent receipt races the original admission', async () => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ const { ApiError } = await import('@platform/transport/http');
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchJson
+ .mockRejectedValueOnce(new TypeError('lost response'))
+ .mockRejectedValueOnce(new ApiError('not committed yet', 404))
+ .mockResolvedValueOnce({ enqueued: 1, item_ids: [42] });
+ const mutableRequest = { ...request, graph: structuredClone(request.graph) };
+ const result = enqueueUtility(mutableRequest);
+ mutableRequest.idempotencyKey = 'replacement-key';
+ mutableRequest.graph.id = 'mutated-graph';
+ await vi.advanceTimersByTimeAsync(999);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(result).resolves.toMatchObject({ itemIds: [42] });
+ const posts = mocks.apiFetchJson.mock.calls.filter(([url]) => url.endsWith('/enqueue_batch'));
+ expect(posts).toHaveLength(2);
+ expect(mocks.apiFetchJson.mock.calls[1]![0]).toBe(
+ '/api/v1/queue/default/enqueue_batch/receipt?idempotency_key=utility%3Aoperation'
+ );
+ expect(posts[0]![1].body).toBe(posts[1]![1].body);
+ expect(JSON.parse(posts[0]![1].body)).toMatchObject({
+ batch: { idempotency_key: request.idempotencyKey, origin: request.origin },
+ prepend: true,
+ });
+ });
+
+ it('bounds admission recovery when both admission and receipts are unavailable', async () => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetchJson.mockRejectedValue(new TypeError('offline'));
+ const assertion = expect(enqueueUtility(request)).rejects.toThrow('Backend work may still be running');
+ await vi.advanceTimersByTimeAsync(3_000);
+ await assertion;
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(6);
+ });
+
+ it.each([409, 429])('does not replay definitive admission rejection (%s)', async (status) => {
+ const { enqueueUtility } = await import('./submissionApi');
+ const { ApiError } = await import('@platform/transport/http');
+ mocks.apiFetchJson.mockRejectedValue(new ApiError('conflict or receipt quota', status));
+ await expect(enqueueUtility(request)).rejects.toMatchObject({ status });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('fences admission recovery when the account changes during a lost response', async () => {
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetchJson.mockImplementationOnce(() => {
+ accountLifecycle.activate('replacement-account');
+ return Promise.reject(new TypeError('lost response'));
+ });
+ await expect(enqueueUtility(request)).rejects.toThrow('account scope');
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('acknowledges only on retention and bounds failed acknowledgement attempts', async () => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetch.mockReset().mockRejectedValue(new TypeError('offline'));
+ const result = await enqueueUtility(request);
+ expect(mocks.apiFetch).not.toHaveBeenCalled();
+ result.acknowledge();
+ result.acknowledge();
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(5);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it.each([403, 422])('stops acknowledgement after a definitive rejection (%s)', async (status) => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ const { ApiError } = await import('@platform/transport/http');
+ mocks.apiFetch.mockReset().mockRejectedValue(new ApiError('rejected', status));
+ const result = await enqueueUtility(request);
+ result.acknowledge();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('aborts the admission backoff on an account change', async () => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetchJson.mockRejectedValue(new TypeError('offline'));
+ const assertion = expect(enqueueUtility(request)).rejects.toBeDefined();
+ await vi.advanceTimersByTimeAsync(0);
+ accountLifecycle.activate('replacement-account');
+ await assertion;
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('drops acknowledgement retries on account change', async () => {
+ vi.useFakeTimers();
+ const { enqueueUtility } = await import('./submissionApi');
+ mocks.apiFetch.mockReset().mockRejectedValue(new TypeError('offline'));
+ const result = await enqueueUtility(request);
+ result.acknowledge();
+ await vi.advanceTimersByTimeAsync(0);
+ accountLifecycle.activate('replacement-account');
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
beforeEach(() => {
+ accountLifecycle.activate('utility-account');
+ mocks.apiFetch.mockReset().mockResolvedValue(undefined);
mocks.apiFetchJson.mockReset();
mocks.apiFetchJson.mockResolvedValue({ enqueued: 1, item_ids: [4] });
});
it('appends by default and prepends only when the request asks for the front of the queue', async () => {
const { enqueueUtility } = await import('./submissionApi');
- const request = { graph: { edges: [], id: 'pbr', nodes: {} }, origin: 'webv2:util:1' };
+ const request = { graph: { edges: [], id: 'pbr', nodes: {} }, origin: 'webv2:util:1', idempotencyKey: 'utility:1' };
- await expect(enqueueUtility(request)).resolves.toEqual({ enqueued: 1, itemIds: [4] });
+ await expect(enqueueUtility(request)).resolves.toMatchObject({ enqueued: 1, itemIds: [4] });
expect(getSubmittedBody()).toMatchObject({ batch: { origin: 'webv2:util:1', runs: 1 }, prepend: false });
mocks.apiFetchJson.mockClear();
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.transport.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.transport.test.ts
new file mode 100644
index 0000000000..508fff73c1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.transport.test.ts
@@ -0,0 +1,67 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { enqueueUtility } from './submissionApi';
+
+const request = {
+ graph: { edges: [], id: 'utility', nodes: {} },
+ origin: 'webv2:util:test',
+ idempotencyKey: 'utility:test',
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('utility production transport', () => {
+ it('recovers a committed hung POST after its actual timeout signal, and acknowledges the exact receipt', async () => {
+ accountLifecycle.activate('utility-transport');
+ const timeout = AbortSignal.timeout.bind(AbortSignal);
+ vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => timeout(Math.min(ms, 5)));
+ let admitted = 0;
+ let acknowledged = false;
+ let timedOut: unknown;
+ const fetch = vi.fn((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const url = String(input);
+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;
+ if (
+ url.endsWith('/enqueue_batch') &&
+ init?.method === 'POST' &&
+ body.batch.idempotency_key === request.idempotencyKey
+ ) {
+ admitted += 1;
+ return new Promise((_resolve, reject) => {
+ const abort = () => {
+ timedOut = init!.signal!.reason;
+ reject(timedOut);
+ };
+ init!.signal!.addEventListener('abort', abort, { once: true });
+ });
+ }
+ if (
+ url.includes('/enqueue_batch/receipt?') &&
+ new URL(url).searchParams.get('idempotency_key') === request.idempotencyKey
+ ) {
+ return Promise.resolve(Response.json({ batch_id: 'accepted', enqueued: 1, item_ids: [41], requested: 1 }));
+ }
+ if (
+ url.endsWith('/enqueue_batch/acknowledge') &&
+ init?.method === 'POST' &&
+ JSON.stringify(body) === JSON.stringify({ idempotency_key: request.idempotencyKey })
+ ) {
+ acknowledged = true;
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+ return Promise.resolve(Response.json({ detail: 'Invalid endpoint or body' }, { status: 422 }));
+ });
+ vi.stubGlobal('fetch', fetch);
+ const result = await enqueueUtility(request);
+ expect(timedOut).toMatchObject({ name: 'TimeoutError' });
+ expect(result.itemIds).toEqual([41]);
+ expect(admitted).toBe(1);
+ expect(acknowledged).toBe(false);
+ result.acknowledge();
+ await vi.waitFor(() => expect(acknowledged).toBe(true));
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index cbfa9fbe79..58276e6692 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -13,7 +13,7 @@ import { mapWithConcurrency } from '@platform/core/concurrency';
import { addOutputImageNames, getOutputImageNames } from '@platform/core/outputImages';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';
-import { absolutizeApiUrl, ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';
+import { absolutizeApiUrl, ApiError, apiFetch, apiFetchJson, sleep } from '@platform/transport/http';
import type { QueueImageDTO, QueueServerItemDTO, QueueVideoDTO } from './serverTypes';
@@ -119,21 +119,94 @@ export const enqueueWorkflow = async (request: QueueEnqueueWorkflowRequest): Pro
return mapEnqueueResult(result);
};
+/** One utility call owns one immutable payload/key, including every admission replay. */
export const enqueueUtility = async (request: {
graph: QueueEnqueueWorkflowRequest['graph'];
origin: string;
+ idempotencyKey: string;
/** Put the item ahead of queued generations. */
prepend?: boolean;
-}): Promise<{ enqueued: number; itemIds: number[] }> => {
- const result = await apiFetchJson<{ enqueued?: number; item_ids?: number[] }>('/api/v1/queue/default/enqueue_batch', {
- body: JSON.stringify({
- batch: { graph: request.graph, origin: request.origin, runs: 1 },
- prepend: request.prepend === true,
- }),
- method: 'POST',
+}): Promise<{ enqueued: number; itemIds: number[]; acknowledge: () => void }> => {
+ const owner = captureAccountScope();
+ const { idempotencyKey } = request;
+ const body = JSON.stringify({
+ batch: { graph: request.graph, origin: request.origin, idempotency_key: idempotencyKey, runs: 1 },
+ prepend: request.prepend === true,
});
-
- return { enqueued: result.enqueued ?? 0, itemIds: result.item_ids ?? [] };
+ const requestSignal = () => AbortSignal.any([owner.signal, AbortSignal.timeout(10_000)]);
+ // Only the runtime can decide that ids were retained (or scheduled for malformed-response cleanup).
+ let acknowledgementStarted = false;
+ const acknowledge = (): void => {
+ if (acknowledgementStarted) {
+ return;
+ }
+ acknowledgementStarted = true;
+ void (async () => {
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ assertAccountScopeCurrent(owner);
+ try {
+ await apiFetch('/api/v1/queue/default/enqueue_batch/acknowledge', {
+ body: JSON.stringify({ idempotency_key: idempotencyKey }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: requestSignal(),
+ });
+ return;
+ } catch (error) {
+ if (
+ attempt === 4 ||
+ (error instanceof ApiError && error.status < 500 && error.status !== 408 && error.status !== 429)
+ ) {
+ return;
+ }
+ await sleep(1_000 * 2 ** attempt, owner.signal);
+ }
+ }
+ })().catch(() => undefined);
+ };
+ const mapUtility = (result: { enqueued?: number; item_ids?: number[] }) => ({
+ acknowledge,
+ enqueued: result.enqueued ?? 0,
+ itemIds: result.item_ids ?? [],
+ });
+ for (let attempt = 0; ; attempt += 1) {
+ assertAccountScopeCurrent(owner);
+ try {
+ const result = await apiFetchJson<{ enqueued?: number; item_ids?: number[] }>(
+ '/api/v1/queue/default/enqueue_batch',
+ { body, method: 'POST', signal: requestSignal() }
+ );
+ assertAccountScopeCurrent(owner);
+ return mapUtility(result);
+ } catch (cause) {
+ assertAccountScopeCurrent(owner);
+ // Conflicts, validation and receipt quotas are definitive rejections, never a reason to mint another key.
+ if (cause instanceof ApiError && cause.status < 500 && cause.status !== 408) {
+ throw cause;
+ }
+ try {
+ const query = new URLSearchParams({ idempotency_key: idempotencyKey });
+ const receipt = mapEnqueueResult(
+ await apiFetchJson<unknown>(`/api/v1/queue/default/enqueue_batch/receipt?${query}`, {
+ signal: requestSignal(),
+ }),
+ true
+ );
+ assertAccountScopeCurrent(owner);
+ return { acknowledge, enqueued: receipt.enqueued, itemIds: receipt.itemIds };
+ } catch {
+ assertAccountScopeCurrent(owner);
+ if (attempt >= 2) {
+ throw new Error(
+ 'Utility admission could not be confirmed. Backend work may still be running; trying again creates a new operation.',
+ { cause }
+ );
+ }
+ await sleep(1_000 * 2 ** attempt, owner.signal);
+ // Even a 404 can race the original commit. Replay the frozen payload with its original key.
+ }
+ }
+ }
};
const getResultImageNames = (queueItem: QueueServerItemDTO, options?: QueueResultImageOptions): string[] => {
@@ -230,6 +303,7 @@ const getResultImage = async (
imageName: string,
queuedAt: string,
sourceQueueItemId: string,
+ sourceBackendItemId: number,
signal: AbortSignal
): Promise<QueueResultImage | null> => {
try {
@@ -243,6 +317,7 @@ const getResultImage = async (
imageUrl: absolutizeApiUrl(image.image_url),
isIntermediate: image.is_intermediate,
queuedAt,
+ sourceBackendItemId,
sourceQueueItemId,
thumbnailUrl: absolutizeApiUrl(image.thumbnail_url),
width: image.width,
@@ -268,7 +343,7 @@ export const getResultImages = async (
const images = await mapWithConcurrency(
getResultImageNames(item, options),
8,
- (imageName) => getResultImage(imageName, queuedAt, sourceQueueItemId, owner.signal),
+ (imageName) => getResultImage(imageName, queuedAt, sourceQueueItemId, itemId, owner.signal),
{ signal: owner.signal }
);
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index b2d09addd4..3ecd62372f 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -9,9 +9,11 @@ import type {
import type { BackendConnectionStatus } from '@platform/transport/types';
import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';
+import { getQueueStagedResults } from '@app/queueStagedResults';
import { collectSubmissionInputMediaNames } from '@features/queue/core/graphInputMedia';
import { activeProgressTargetStore } from '@features/queue/data/activeProgressTargetStore';
import { buildQueueItemOrigin } from '@features/queue/data/events';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { createInitialWorkbenchState, type WorkbenchAction, workbenchReducer } from '@workbench/workbenchState.testing';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -20,6 +22,7 @@ import {
createQueueItemBackendSubmission,
createQueueRuntime,
type QueueHistoryCommands,
+ type QueueHistoryPort,
type QueueRunJournalPort,
type QueueRunLock,
type QueueRunLockPort,
@@ -84,7 +87,7 @@ const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBack
pauseProcessor: vi.fn(),
readCurrent: vi.fn(),
readItemIds: vi.fn(),
- readItemsById: vi.fn(),
+ readItemsById: vi.fn().mockResolvedValue([]),
readNext: vi.fn(),
readStatus: vi.fn(),
resumeProcessor: vi.fn(),
@@ -187,6 +190,7 @@ const createWorkbenchQueueHistory = () => {
),
});
return {
+ dispatch,
/** The backend item a successful enqueue of the run creates. */
acceptedItem: {
batchId: 'backend-batch',
@@ -198,6 +202,7 @@ const createWorkbenchQueueHistory = () => {
state.projects.find((project) => project.id === projectId)?.queue.items.find((item) => item.id === queueItem.id),
history: {
commands,
+ listStagedResults: () => getQueueStagedResults(state.projects),
getSnapshot: () => ({ connectionStatus, isHydrated: true, projects: state.projects }),
subscribe: (listener: () => void) => {
listeners.add(listener);
@@ -476,7 +481,7 @@ describe('queue runtime', () => {
pauseProcessor: vi.fn(),
readCurrent: vi.fn(),
readItemIds: vi.fn(),
- readItemsById: vi.fn(),
+ readItemsById: vi.fn().mockResolvedValue([]),
readNext: vi.fn(),
readStatus: vi.fn(),
resumeProcessor: vi.fn(),
@@ -512,6 +517,7 @@ describe('queue runtime', () => {
ensureTemplatesLoaded: vi.fn(),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -563,6 +569,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate }),
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -604,6 +611,7 @@ describe('queue runtime', () => {
ensureProjectPersisted,
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -638,6 +646,7 @@ describe('queue runtime', () => {
ensureProjectPersisted: vi.fn().mockResolvedValue('refused'),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -671,6 +680,7 @@ describe('queue runtime', () => {
ensureProjectPersisted: vi.fn().mockResolvedValue(outcome),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -708,6 +718,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -738,6 +749,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -786,6 +798,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -841,6 +854,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -888,6 +902,7 @@ describe('queue runtime', () => {
queueItem.localRecoveryState = state;
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -929,6 +944,7 @@ describe('queue runtime', () => {
queueItem.localRecoveryState = state;
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'disconnected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -967,6 +983,7 @@ describe('queue runtime', () => {
queueItem.localRecoveryState = state;
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1025,6 +1042,7 @@ describe('queue runtime', () => {
queueItem.localRecoveryState = state;
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1057,6 +1075,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -1110,6 +1129,7 @@ describe('queue runtime', () => {
backend,
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1178,6 +1198,7 @@ describe('queue runtime', () => {
}
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1230,6 +1251,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ getItem, getResultImages }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1277,6 +1299,7 @@ describe('queue runtime', () => {
backend: createTestBackend(),
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1324,6 +1347,7 @@ describe('queue runtime', () => {
}),
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1370,6 +1394,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ cancelQueueItems }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1430,6 +1455,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ cancelQueueItems: vi.fn().mockResolvedValue(undefined) }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1492,6 +1518,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1545,6 +1572,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1599,6 +1627,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1663,6 +1692,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1771,6 +1801,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ cancelQueueItems, cancelQueueItemsByBatchIds, enqueueGenerate }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -1821,6 +1852,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate, listItems }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2449,6 +2481,7 @@ describe('queue runtime', () => {
}),
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus, isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -2501,6 +2534,7 @@ describe('queue runtime', () => {
backend,
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'disconnected', isHydrated: true, projects }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2541,6 +2575,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -2591,6 +2626,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ enqueueGenerate, listItems }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2657,6 +2693,7 @@ describe('queue runtime', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2693,6 +2730,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ listItems }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2727,6 +2765,7 @@ describe('queue runtime', () => {
backend,
history: {
commands: createTestCommands({ restoreFromJournal }),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -2779,6 +2818,7 @@ describe('queue runtime', () => {
backend: createTestBackend({ listItems }),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -2835,6 +2875,7 @@ describe('queue runtime', () => {
backend,
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
@@ -2891,6 +2932,7 @@ describe('queue runtime', () => {
backend,
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -2943,6 +2985,7 @@ describe('queue runtime', () => {
backend,
history: {
commands: createTestCommands(),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -3000,6 +3043,7 @@ describe('queue runtime', () => {
listeners.forEach((listener) => listener());
},
}),
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -3159,6 +3203,7 @@ describe('queue runtime video board routing', () => {
ensureTemplatesLoaded: vi.fn(),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: vi.fn(() => vi.fn()),
},
@@ -3630,7 +3675,12 @@ describe('queue runtime retries', () => {
const createRetryHarness = (
queueItem: QueueItem,
backendOverrides: Partial<QueueBackendPort> = {},
- services: { journal?: QueueRunJournalPort; locks?: QueueRunLockPort; viewerUserId?: string | null } = {}
+ services: {
+ journal?: QueueRunJournalPort;
+ locks?: QueueRunLockPort;
+ viewerUserId?: string | null;
+ listStagedResults?: QueueHistoryPort['listStagedResults'];
+ } = {}
) => {
const project = { id: 'project-1', queue: { items: [queueItem] } };
const projects = [project];
@@ -3650,8 +3700,26 @@ describe('queue runtime retries', () => {
}),
...backendOverrides,
});
+ const staged: Array<{ backendItemId: number; projectId: string; queueItemId: string }> = [];
+ const stageImages = (payload: {
+ images: QueueResultImage[];
+ backendItemId?: number;
+ projectId: string;
+ queueItemId: string;
+ }) => {
+ for (const image of payload.images) {
+ const backendItemId = image.sourceBackendItemId ?? payload.backendItemId;
+ if (backendItemId !== undefined) {
+ staged.push({ backendItemId, projectId: payload.projectId, queueItemId: payload.queueItemId });
+ }
+ }
+ notify();
+ };
const commands = createTestCommands({
- routeResults: vi.fn(() => {
+ routePartialResults: vi.fn(stageImages),
+ stageRetriedCanvasResults: vi.fn(stageImages),
+ routeResults: vi.fn((payload) => {
+ stageImages(payload);
queueItem.status = 'completed';
notify();
}),
@@ -3662,6 +3730,7 @@ describe('queue runtime retries', () => {
backend,
history: {
commands,
+ listStagedResults: services.listStagedResults ?? (() => staged),
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),
subscribe: (listener) => {
listeners.add(listener);
@@ -3829,6 +3898,7 @@ describe('queue runtime retries', () => {
history: {
commands,
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: state.projects }),
+ listStagedResults: () => getQueueStagedResults(state.projects),
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
@@ -4042,7 +4112,8 @@ describe('queue runtime retries', () => {
});
return { claimItemDelivery, claims };
};
- const rerunImages = (itemId: number) => Promise.resolve([{ imageName: `rerun-${itemId}.png` } as QueueResultImage]);
+ const rerunImages = (itemId: number) =>
+ Promise.resolve([{ imageName: `rerun-${itemId}.png`, sourceBackendItemId: itemId } as QueueResultImage]);
const openCanvasTab = (
server: ReturnType<typeof createDeliveryServer>,
getResultImages: QueueBackendPort['getResultImages'] = vi.fn(rerunImages),
@@ -4097,6 +4168,744 @@ describe('queue runtime retries', () => {
setTimeout(resolve);
});
+ it.each(['empty', 'filtered', 'delivered elsewhere'] as const)(
+ 'retains backend provenance through full Workbench routing when the first adopted item is %s',
+ async (firstResult) => {
+ const { getResultImages } = await import('./data/submissionApi');
+ const imageNames = firstResult === 'empty' ? ['first.png'] : ['first.png', 'second.png'];
+ let state = createInitialWorkbenchState();
+ const projectId = state.activeProjectId;
+ const { canvas } = state.projects.find((project) => project.id === projectId)!;
+ const queueItem: WorkbenchQueueItem = {
+ ...createPendingQueueItem(),
+ backendItemIds: [41, 42],
+ snapshot: {
+ ...createPendingQueueItem().snapshot,
+ filterIntermediateResults: firstResult === 'filtered',
+ canvas: {
+ document: { bbox: canvas.document.bbox, height: canvas.document.height, width: canvas.document.width },
+ documentRevision: canvas.documentRevision,
+ },
+ },
+ status: 'failed',
+ };
+ state = { ...state, projects: state.projects.map((project) => ({ ...project, queue: { items: [queueItem] } })) };
+ const listeners = new Set<() => void>();
+ const dispatch = (action: WorkbenchAction): void => {
+ state = workbenchReducer(state, action);
+ listeners.forEach((listener) => listener());
+ };
+ const server = createDeliveryServer();
+ if (firstResult === 'delivered elsewhere') {
+ server.claims.set(99, { claimant: 'other-browser', claimedAt: Date.now(), isDelivered: true });
+ }
+ const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
+ const url = String(input);
+ const data = url.includes('/queue/default/i/')
+ ? {
+ item_id: Number(url.split('/').at(-1)),
+ status: 'completed',
+ session: {
+ results: url.endsWith('/99')
+ ? firstResult === 'filtered'
+ ? { canvas_output: { image: { image_name: 'filtered.png' } } }
+ : {}
+ : { canvas_output: { collection: imageNames.map((image_name) => ({ image_name })) } },
+ },
+ }
+ : {
+ image_name: url.split('/').at(-1),
+ image_url: '/result.png',
+ thumbnail_url: '/result.png',
+ width: 64,
+ height: 64,
+ is_intermediate: url.endsWith('/filtered.png'),
+ };
+ return Promise.resolve(new Response(JSON.stringify(data)));
+ });
+ // A slow partial-route lease check must not force the full route to infer ids by image position.
+ let completePartialClaim!: (claim: { kind: 'claimed' }) => void;
+ const partialClaim = new Promise<{ kind: 'claimed' }>((resolve) => {
+ completePartialClaim = resolve;
+ });
+ let claimChecks = 0;
+ const handlers = new Map<string, (payload: never) => void>();
+ const backend = createTestBackend({
+ claimItemDelivery: (id, action, claimant) => {
+ if (id === 100 && action === 'claim' && ++claimChecks === 2) {
+ return partialClaim;
+ }
+ return server.claimItemDelivery(id, action, claimant);
+ },
+ getItem: (id) =>
+ Promise.resolve({
+ id,
+ batchId: 'batch',
+ origin: buildQueueItemOrigin(queueItem.id, projectId),
+ status: 'completed',
+ }),
+ getResultImages,
+ on: (event, handler) => {
+ handlers.set(event, handler as (payload: never) => void);
+ return () => handlers.delete(event);
+ },
+ });
+ const runtime = createQueueRuntime({
+ ...runtimeServices,
+ backend,
+ history: {
+ commands: createTestCommands({
+ reopenForRetry: (payload) => dispatch({ ...payload, type: 'reopenQueueItemForRetry' }),
+ routePartialResults: (payload) => dispatch({ ...payload, type: 'routeQueueItemPartialResults' }),
+ routeResults: (payload) => dispatch({ ...payload, type: 'routeQueueItemResults' }),
+ setStatus: (payload) => dispatch({ ...payload, type: 'setQueueItemStatus' }),
+ }),
+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: state.projects }),
+ listStagedResults: () => getQueueStagedResults(state.projects),
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ });
+ try {
+ runtime.start();
+ handlers.get('queue_items_retried')?.(
+ retriedEvent([
+ { item_id: 99, source_item_id: 41 },
+ { item_id: 100, source_item_id: 42 },
+ ]) as never
+ );
+ await vi.waitFor(() => expect(server.claims.get(100)?.isDelivered).toBe(true));
+ const candidates = state.projects.find((project) => project.id === projectId)!.canvas.stagingArea.pendingImages;
+ expect(candidates.map(({ imageName, sourceBackendItemId }) => ({ imageName, sourceBackendItemId }))).toEqual(
+ imageNames.map((imageName) => ({ imageName, sourceBackendItemId: 100 }))
+ );
+ expect(
+ vi.mocked(server.claimItemDelivery).mock.calls.some(([id, action]) => id === 100 && action === 'release')
+ ).toBe(false);
+ completePartialClaim({ kind: 'claimed' });
+ expect(vi.mocked(server.claimItemDelivery).mock.calls).toContainEqual([100, 'confirm', expect.any(String)]);
+ if (firstResult !== 'delivered elsewhere') {
+ await vi.waitFor(() => expect(server.claims.has(99)).toBe(false));
+ expect(vi.mocked(server.claimItemDelivery).mock.calls).toContainEqual([99, 'release', expect.any(String)]);
+ }
+ const stale = openCanvasTab(server);
+ stale.runtime.start();
+ emitReruns(stale, [100]);
+ stale.emit(
+ 'queue_item_status_changed',
+ completedEvent(100, buildQueueItemOrigin('gone', stale.project.id), 'canvas')
+ );
+ await settleEvents();
+ expect(stagedItemIds(stale)).toEqual([]);
+ await stale.runtime.dispose();
+ } finally {
+ completePartialClaim({ kind: 'claimed' });
+ await runtime.dispose();
+ fetch.mockRestore();
+ }
+ }
+ );
+
+ it.each([false, true])(
+ 'bounds staging projection work for a completed retry batch when routing throws after mutation: %s',
+ async (throwsAfterMutation) => {
+ const server = createDeliveryServer(120_000);
+ const backendItemIds = Array.from({ length: 16 }, (_, index) => 100 + index);
+ const foreignBackendItemId = backendItemIds.at(-2)!;
+ const unstagedBackendItemId = backendItemIds.at(-1)!;
+ let state = createInitialWorkbenchState();
+ const projectId = state.activeProjectId;
+ const { canvas } = state.projects.find((project) => project.id === projectId)!;
+ const queueItem: WorkbenchQueueItem = {
+ ...createPendingQueueItem(),
+ backendItemIds: backendItemIds.map((id) => id - 100),
+ snapshot: {
+ ...createPendingQueueItem().snapshot,
+ canvas: {
+ document: { bbox: canvas.document.bbox, height: canvas.document.height, width: canvas.document.width },
+ documentRevision: canvas.documentRevision,
+ },
+ },
+ status: 'failed',
+ };
+ state = { ...state, projects: state.projects.map((project) => ({ ...project, queue: { items: [queueItem] } })) };
+ state = workbenchReducer(state, {
+ type: 'stageRetriedCanvasResults',
+ backendItemId: foreignBackendItemId,
+ projectId,
+ queueItemId: 'other-run',
+ images: [
+ { imageName: 'other-run.png', sourceQueueItemId: 'other-run', width: 64, height: 64 } as QueueResultImage,
+ ],
+ });
+ const listeners = new Set<() => void>();
+ const dispatch = (action: WorkbenchAction): void => {
+ state = workbenchReducer(state, action);
+ listeners.forEach((listener) => listener());
+ };
+ let isRouting = false;
+ let projectedEntries = 0;
+ const handlers = new Map<string, (payload: never) => void>();
+ const runtime = createQueueRuntime({
+ ...runtimeServices,
+ backend: createTestBackend({
+ claimItemDelivery: server.claimItemDelivery,
+ getItem: (id) =>
+ Promise.resolve({
+ id,
+ batchId: 'batch',
+ origin: buildQueueItemOrigin(queueItem.id, projectId),
+ status: 'completed',
+ }),
+ getResultImages: (id) =>
+ Promise.resolve([
+ {
+ imageName: `rerun-${id}.png`,
+ sourceBackendItemId: id,
+ sourceQueueItemId: queueItem.id,
+ width: 64,
+ height: 64,
+ } as QueueResultImage,
+ ]),
+ on: (event, handler) => {
+ handlers.set(event, handler as (payload: never) => void);
+ return () => handlers.delete(event);
+ },
+ }),
+ history: {
+ commands: createTestCommands({
+ reopenForRetry: (payload) => dispatch({ ...payload, type: 'reopenQueueItemForRetry' }),
+ // Exercise full-batch confirmation rather than confirming each item's partial route first.
+ routePartialResults: () => undefined,
+ routeResults: (payload) => {
+ isRouting = true;
+ dispatch({
+ ...payload,
+ images: payload.images.filter(
+ (image) =>
+ image.sourceBackendItemId !== unstagedBackendItemId &&
+ image.sourceBackendItemId !== foreignBackendItemId
+ ),
+ type: 'routeQueueItemResults',
+ });
+ if (throwsAfterMutation) {
+ throw new Error('after staging');
+ }
+ },
+ setStatus: (payload) => dispatch({ ...payload, type: 'setQueueItemStatus' }),
+ }),
+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: state.projects }),
+ listStagedResults: () => {
+ const results = getQueueStagedResults(state.projects);
+ if (isRouting) {
+ projectedEntries += results.length;
+ }
+ return results;
+ },
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ });
+ try {
+ runtime.start();
+ handlers.get('queue_items_retried')?.(
+ retriedEvent(backendItemIds.map((id) => ({ item_id: id, source_item_id: id - 100 }))) as never
+ );
+ const stagedBackendItemIds = backendItemIds.slice(0, -2);
+ await vi.waitFor(() => expect(isRouting).toBe(true));
+ await vi.waitFor(() => {
+ expect(stagedBackendItemIds.filter((id) => !server.claims.get(id)?.isDelivered)).toEqual([]);
+ expect(server.claims.has(unstagedBackendItemId)).toBe(false);
+ });
+ expect(server.claims.get(foreignBackendItemId)?.isDelivered).not.toBe(true);
+ expect(getQueueStagedResults(state.projects)).toEqual([
+ { backendItemId: foreignBackendItemId, projectId, queueItemId: 'other-run' },
+ ...stagedBackendItemIds.map((backendItemId) => ({ backendItemId, projectId, queueItemId: queueItem.id })),
+ ]);
+ // Recovery notifications, confirmation and unstaged release each project at most once per pass.
+ expect(projectedEntries).toBeLessThanOrEqual(6 * backendItemIds.length);
+ } finally {
+ await runtime.dispose();
+ }
+ }
+ );
+
+ it('retries a lost confirmation response without staging again, including after the run ends', async () => {
+ vi.useFakeTimers();
+ const server = createDeliveryServer(120_000);
+ const original = server.claimItemDelivery;
+ let confirmations = 0;
+ server.claimItemDelivery = vi.fn<QueueBackendPort['claimItemDelivery']>(async (id, action, claimant) => {
+ if (action === 'confirm' && ++confirmations === 1) {
+ await original(id, action, claimant);
+ throw new TypeError('successful response lost');
+ }
+ return original(id, action, claimant);
+ });
+ const adopting = openAdoptingTab(server);
+ adopting.runtime.start();
+ adopting.emit('queue_items_retried', retriedEvent([{ item_id: 99, source_item_id: 41 }]));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(stagedImageNames(adopting)).toContain('rerun-99.png');
+ expect(server.claims.get(99)?.isDelivered).toBe(true);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'confirm')).toHaveLength(2);
+ const later = openCanvasTab(server);
+ later.runtime.start();
+ emitReruns(later, [99]);
+ later.emit(
+ 'queue_item_status_changed',
+ completedEvent(99, buildQueueItemOrigin('gone', later.project.id), 'canvas')
+ );
+ await vi.advanceTimersByTimeAsync(100);
+ expect(stagedItemIds(later)).toEqual([]);
+ await adopting.runtime.dispose();
+ await later.runtime.dispose();
+ vi.useRealTimers();
+ });
+
+ it.each(['partial', 'completed'] as const)(
+ 'excludes live ordinary %s staging from recovery through history clearing, then recovers an unknown rerun',
+ async (routing) => {
+ vi.useFakeTimers();
+ const workbench = createWorkbenchQueueHistory();
+ const projectId = workbench.history.getSnapshot().projects[0]!.id;
+ const queueItemId = workbench.getRun()!.id;
+ const commands = workbench.history.commands;
+ if (routing === 'partial') {
+ vi.mocked(commands.routePartialResults).mockImplementation((payload) =>
+ workbench.dispatch({ ...payload, type: 'routeQueueItemPartialResults' })
+ );
+ } else {
+ vi.mocked(commands.routeResults).mockImplementation((payload) =>
+ workbench.dispatch({ ...payload, type: 'routeQueueItemResults' })
+ );
+ }
+ const backend = createTestBackend({
+ enqueueGenerate: vi.fn().mockResolvedValue({
+ batchId: 'backend-batch',
+ enqueued: routing === 'partial' ? 2 : 1,
+ itemIds: routing === 'partial' ? [88, 89] : [88],
+ requested: routing === 'partial' ? 2 : 1,
+ }),
+ getItem: vi.fn<QueueBackendPort['getItem']>((id) =>
+ Promise.resolve({ ...workbench.acceptedItem, id, status: id === 88 ? 'completed' : 'pending' })
+ ),
+ getResultImages: vi.fn().mockResolvedValue([
+ {
+ imageName: 'ordinary.png',
+ sourceBackendItemId: 88,
+ sourceQueueItemId: queueItemId,
+ width: 64,
+ height: 64,
+ } as QueueResultImage,
+ ]),
+ readItemsById: vi.fn().mockRejectedValue(new TypeError('metadata unavailable')),
+ claimItemDelivery: vi.fn().mockResolvedValue({ kind: 'delivered' }),
+ });
+ const runtime = createQueueRuntime({ ...runtimeServices, backend, history: workbench.history });
+ try {
+ runtime.start();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(workbench.history.listStagedResults()).toEqual([{ backendItemId: 88, projectId, queueItemId }]);
+ if (routing === 'partial') {
+ expect(workbench.getRun()?.status).toBe('running');
+ commands.setStatus({ projectId, queueItemId, status: 'failed' });
+ } else {
+ expect(workbench.getRun()?.status).toBe('completed');
+ }
+ workbench.dispatch({ type: 'clearCompletedQueueItems' });
+ expect(workbench.getRun()).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(workbench.history.listStagedResults()).toEqual([{ backendItemId: 88, projectId, queueItemId }]);
+ expect(backend.readItemsById).not.toHaveBeenCalled();
+ expect(backend.claimItemDelivery).not.toHaveBeenCalled();
+ expect(commands.recordError).not.toHaveBeenCalled();
+
+ // A candidate arriving from project recovery has no live routing classification or queue history.
+ vi.mocked(backend.readItemsById).mockResolvedValue([
+ {
+ id: 99,
+ retriedFromItemId: 41,
+ destination: 'canvas',
+ origin: buildQueueItemOrigin('restored-run', projectId),
+ } as Awaited<ReturnType<QueueBackendPort['readItemsById']>>[number],
+ ]);
+ workbench.dispatch({
+ type: 'stageRetriedCanvasResults',
+ backendItemId: 99,
+ projectId,
+ queueItemId: 'restored-run',
+ images: [
+ { imageName: 'restored.png', sourceQueueItemId: 'restored-run', width: 64, height: 64 } as QueueResultImage,
+ ],
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(backend.readItemsById).toHaveBeenCalledExactlyOnceWith([99], expect.any(AbortSignal));
+ expect(backend.claimItemDelivery).toHaveBeenCalledExactlyOnceWith(
+ 99,
+ 'confirm',
+ `run:${JSON.stringify([projectId, 'restored-run'])}`
+ );
+ expect(commands.recordError).not.toHaveBeenCalled();
+ } finally {
+ await runtime.dispose();
+ }
+ }
+ );
+
+ it('validates a restored active run without local retry history before confirming its staged rerun', async () => {
+ vi.useFakeTimers();
+ const workbench = createWorkbenchQueueHistory();
+ const projectId = workbench.history.getSnapshot().projects[0]!.id;
+ const queueItemId = workbench.getRun()!.id;
+ const commands = workbench.history.commands;
+ commands.markBackendSubmitted({ backendItemIds: [88], backendBatchId: 'backend-batch', projectId, queueItemId });
+ vi.mocked(commands.routeResults).mockImplementation((payload) =>
+ workbench.dispatch({ ...payload, type: 'routeQueueItemResults' })
+ );
+ const backend = createTestBackend({
+ getItem: vi.fn().mockResolvedValue({ ...workbench.acceptedItem, status: 'completed' }),
+ getResultImages: vi.fn().mockResolvedValue([
+ {
+ imageName: 'restored.png',
+ sourceBackendItemId: 88,
+ sourceQueueItemId: queueItemId,
+ width: 64,
+ height: 64,
+ } as QueueResultImage,
+ ]),
+ readItemsById: vi.fn().mockResolvedValue([
+ {
+ id: 88,
+ retriedFromItemId: 41,
+ destination: 'canvas',
+ origin: buildQueueItemOrigin(queueItemId, projectId),
+ },
+ ]),
+ claimItemDelivery: vi.fn().mockResolvedValue({ kind: 'delivered' }),
+ });
+ const runtime = createQueueRuntime({ ...runtimeServices, backend, history: workbench.history });
+ try {
+ runtime.start();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(workbench.getRun()).toMatchObject({ status: 'completed' });
+ expect(backend.enqueueGenerate).not.toHaveBeenCalled();
+ expect(backend.readItemsById).toHaveBeenCalledExactlyOnceWith([88], expect.any(AbortSignal));
+ expect(backend.claimItemDelivery).toHaveBeenCalledExactlyOnceWith(
+ 88,
+ 'confirm',
+ `run:${JSON.stringify([projectId, queueItemId])}`
+ );
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
+ it('confirms an already staged candidate recovered from the project without staging it again', async () => {
+ const server = createDeliveryServer();
+ const tab = createRetryHarness(
+ { ...createPendingQueueItem(), backendItemIds: [99], retriedBackendItemIds: [41], status: 'completed' },
+ {
+ claimItemDelivery: server.claimItemDelivery,
+ readItemsById: vi.fn().mockResolvedValue([
+ {
+ id: 99,
+ retriedFromItemId: 41,
+ destination: 'canvas',
+ origin: buildQueueItemOrigin('recovered-run', 'project-1'),
+ },
+ ]),
+ },
+ { listStagedResults: () => [{ backendItemId: 99, projectId: 'project-1', queueItemId: 'recovered-run' }] }
+ );
+ tab.runtime.start();
+ await vi.waitFor(() => expect(server.claims.get(99)?.isDelivered).toBe(true));
+ expect(stagedItemIds(tab)).toEqual([]);
+ await tab.runtime.dispose();
+ });
+
+ it('keeps an unadopted staged delivery pending after confirmation failure and stops retries on disposal', async () => {
+ vi.useFakeTimers();
+ const server = createDeliveryServer(120_000);
+ const original = server.claimItemDelivery;
+ server.claimItemDelivery = vi.fn<QueueBackendPort['claimItemDelivery']>((id, action, claimant) =>
+ action === 'confirm' ? Promise.reject(new TypeError('offline')) : original(id, action, claimant)
+ );
+ const tab = openCanvasTab(server);
+ tab.runtime.start();
+ emitReruns(tab, [99]);
+ tab.emit('queue_item_status_changed', completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(stagedItemIds(tab)).toEqual([99]);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(stagedItemIds(tab)).toEqual([99]);
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'release')).toHaveLength(0);
+ await tab.runtime.dispose();
+ const requests = vi.mocked(server.claimItemDelivery).mock.calls.length;
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(server.claimItemDelivery).toHaveBeenCalledTimes(requests);
+ vi.useRealTimers();
+ });
+
+ it.each([403, 422, 503] as const)(
+ 'bounds unsuccessful confirmation retries (%s) without releasing staged work',
+ async (failure) => {
+ vi.useFakeTimers();
+ const server = createDeliveryServer(120_000);
+ const original = server.claimItemDelivery;
+ server.claimItemDelivery = vi.fn<QueueBackendPort['claimItemDelivery']>((id, action, claimant) => {
+ if (action === 'confirm') {
+ return Promise.reject(new ApiError('confirmation failed', failure));
+ }
+ return original(id, action, claimant);
+ });
+ const tab = openCanvasTab(server);
+ tab.runtime.start();
+ emitReruns(tab, [99]);
+ tab.emit('queue_item_status_changed', completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.advanceTimersByTimeAsync(180_000);
+ const confirmations = vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'confirm');
+ expect(confirmations).toHaveLength(failure === 403 || failure === 422 ? 1 : 5);
+ const requests = vi.mocked(server.claimItemDelivery).mock.calls.length;
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(server.claimItemDelivery).toHaveBeenCalledTimes(requests);
+ expect(stagedItemIds(tab)).toEqual([99]);
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'release')).toHaveLength(
+ 0
+ );
+ await tab.runtime.dispose();
+ vi.useRealTimers();
+ }
+ );
+
+ it.each(['close', 'dispose', 'account change'] as const)(
+ 'returns a late unadopted grant after %s, with account fencing',
+ async (ending) => {
+ const server = createDeliveryServer(120_000);
+ const original = server.claimItemDelivery;
+ let grant!: () => void;
+ server.claimItemDelivery = vi.fn<QueueBackendPort['claimItemDelivery']>((id, action, claimant) =>
+ action === 'claim'
+ ? new Promise((resolve) => {
+ grant = () => {
+ void original(id, action, claimant).then(resolve);
+ };
+ })
+ : original(id, action, claimant)
+ );
+ const tab = openCanvasTab(server);
+ tab.runtime.start();
+ emitReruns(tab, [99]);
+ tab.emit('queue_item_status_changed', completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.waitFor(() => expect(grant).toBeDefined());
+ let disposal: Promise<void> | undefined;
+ if (ending === 'close') {
+ tab.closeProject();
+ }
+ if (ending === 'dispose') {
+ disposal = tab.runtime.dispose();
+ }
+ if (ending === 'account change') {
+ accountLifecycle.activate('replacement-grant-account');
+ }
+ grant();
+ await settleEvents();
+ await disposal;
+ expect(stagedItemIds(tab)).toEqual([]);
+ const releases = vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'release');
+ if (ending === 'account change') {
+ expect(releases).toHaveLength(0);
+ } else {
+ expect(releases).toHaveLength(1);
+ expect(server.claims.has(99)).toBe(false);
+ }
+ await tab.runtime.dispose();
+ }
+ );
+
+ it.each(['adopted', 'unadopted'] as const)(
+ 'releases owned unstaged %s claims during disposal while reads are in flight',
+ async (kind) => {
+ const server = createDeliveryServer(120_000);
+ const finishers: Array<(images: QueueResultImage[]) => void> = [];
+ const tab = kind === 'adopted' ? openAdoptingTab(server) : openCanvasTab(server);
+ vi.mocked(tab.backend.getResultImages).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishers.push(resolve);
+ })
+ );
+ tab.runtime.start();
+ if (kind === 'adopted') {
+ tab.emit('queue_items_retried', retriedEvent([{ item_id: 99, source_item_id: 41 }]));
+ } else {
+ emitReruns(tab, [99]);
+ tab.emit(
+ 'queue_item_status_changed',
+ completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas')
+ );
+ }
+ await vi.waitFor(() => expect(finishers.length).toBeGreaterThan(0));
+ const disposal = tab.runtime.dispose();
+ await vi.waitFor(() => expect(server.claims.has(99)).toBe(false));
+ vi.mocked(tab.backend.getResultImages).mockResolvedValue([]);
+ finishers
+ .splice(0)
+ .forEach((finish) => finish([{ imageName: 'late.png', sourceBackendItemId: 99 } as QueueResultImage]));
+ await disposal;
+ expect(stagedImageNames(tab)).toEqual([]);
+ }
+ );
+
+ it.each(['routeResults', 'routePartialResults'] as const)('releases unstaged work when %s throws', async (route) => {
+ const server = createDeliveryServer(120_000);
+ const tab = openAdoptingTab(server);
+ vi.mocked(tab.commands.routePartialResults).mockImplementation(() => undefined);
+ vi.mocked(tab.commands.routeResults).mockImplementation(() => undefined);
+ vi.mocked(tab.commands[route]).mockImplementation(() => {
+ throw new Error('routing failed');
+ });
+ tab.runtime.start();
+ tab.emit('queue_items_retried', retriedEvent([{ item_id: 99, source_item_id: 41 }]));
+ await vi.waitFor(() => expect(tab.commands[route]).toHaveBeenCalled());
+ await vi.waitFor(() => expect(server.claims.has(99)).toBe(false));
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.some(([, action]) => action === 'confirm')).toBe(false);
+ if (route === 'routeResults') {
+ expect(tab.commands.setStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'failed', error: 'routing failed' })
+ );
+ } else {
+ expect(tab.commands.recordError).toHaveBeenCalledWith(expect.objectContaining({ message: 'routing failed' }));
+ }
+ await tab.runtime.dispose();
+ });
+
+ it.each(['routeResults', 'routePartialResults'] as const)(
+ 'keeps and confirms actual staging when %s throws after mutation',
+ async (route) => {
+ const server = createDeliveryServer(120_000);
+ const tab = openAdoptingTab(server);
+ const stage = vi.mocked(tab.commands[route]).getMockImplementation()!;
+ let releasesBeforeStaging = 0;
+ const other = route === 'routeResults' ? 'routePartialResults' : 'routeResults';
+ vi.mocked(tab.commands[other]).mockImplementation(() => undefined);
+ vi.mocked(tab.commands[route]).mockImplementation((payload) => {
+ releasesBeforeStaging = vi
+ .mocked(server.claimItemDelivery)
+ .mock.calls.filter(([, action]) => action === 'release').length;
+ stage(payload as Parameters<typeof stage>[0]);
+ throw new Error('after staging');
+ });
+ tab.runtime.start();
+ tab.emit('queue_items_retried', retriedEvent([{ item_id: 99, source_item_id: 41 }]));
+ await vi.waitFor(() => expect(server.claims.get(99)?.isDelivered).toBe(true));
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'release')).toHaveLength(
+ releasesBeforeStaging
+ );
+ await tab.runtime.dispose();
+ }
+ );
+
+ it('confirms actual unadopted staging even if the stage callback throws after the mutation', async () => {
+ const server = createDeliveryServer(120_000);
+ const tab = openCanvasTab(server);
+ const stage = vi.mocked(tab.commands.stageRetriedCanvasResults).getMockImplementation()!;
+ vi.mocked(tab.commands.stageRetriedCanvasResults).mockImplementation((payload) => {
+ stage(payload);
+ throw new Error('after staging');
+ });
+ tab.runtime.start();
+ emitReruns(tab, [99]);
+ tab.emit('queue_item_status_changed', completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.waitFor(() => expect(server.claims.get(99)?.isDelivered).toBe(true));
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.some(([, action]) => action === 'release')).toBe(false);
+ await tab.runtime.dispose();
+ });
+
+ it('never reclaims or releases previously staged work when cancellation interrupts a failing confirmation', async () => {
+ vi.useFakeTimers();
+ const server = createDeliveryServer(120_000);
+ const original = server.claimItemDelivery;
+ server.claimItemDelivery = vi.fn((id, action, claimant) =>
+ action === 'confirm' ? Promise.reject(new TypeError('offline')) : original(id, action, claimant)
+ );
+ const tab = openAdoptingTab(server);
+ // Partial routing leaves the run alive, as another item of its batch would.
+ vi.mocked(tab.commands.routeResults).mockImplementation(() => undefined);
+ tab.runtime.start();
+ tab.emit('queue_items_retried', retriedEvent([{ item_id: 99, source_item_id: 41 }]));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(stagedImageNames(tab)).toContain('rerun-99.png');
+ const claims = vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'claim').length;
+ tab.notify();
+ tab.run.status = 'cancelled';
+ tab.notify();
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'claim')).toHaveLength(
+ claims
+ );
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'confirm')).toHaveLength(5);
+ expect(vi.mocked(server.claimItemDelivery).mock.calls.filter(([, action]) => action === 'release')).toHaveLength(0);
+ await tab.runtime.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.useRealTimers();
+ });
+
+ it('removes settled retry-wait listeners and aborts the pending wait on disposal', async () => {
+ vi.useFakeTimers();
+ const added = vi.spyOn(AbortSignal.prototype, 'addEventListener');
+ const removed = vi.spyOn(AbortSignal.prototype, 'removeEventListener');
+ const server = createDeliveryServer();
+ const original = server.claimItemDelivery;
+ let waits = 0;
+ server.claimItemDelivery = vi.fn<QueueBackendPort['claimItemDelivery']>((id, action, claimant) => {
+ if (action === 'claim' && waits++ < 25) {
+ return Promise.resolve({ kind: 'held', retryInMs: 1 } as const);
+ }
+ return original(id, action, claimant);
+ });
+ const tab = openCanvasTab(server);
+ tab.runtime.start();
+ const initialRegistrations = added.mock.calls.length;
+ emitReruns(tab, [99]);
+ tab.emit('queue_item_status_changed', completedEvent(99, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(stagedItemIds(tab)).toEqual([99]);
+ const waitRegistrations = () =>
+ added.mock.calls.flatMap(([event, listener, options], index) =>
+ index >= initialRegistrations && event === 'abort' && typeof options === 'object' && options.once
+ ? [{ signal: added.mock.contexts[index], listener }]
+ : []
+ );
+ const unremovedWaits = () =>
+ waitRegistrations().filter(
+ ({ signal, listener }) =>
+ !(signal as AbortSignal).aborted &&
+ !removed.mock.calls.some(
+ ([event, removedListener], index) =>
+ event === 'abort' && removedListener === listener && removed.mock.contexts[index] === signal
+ )
+ );
+ expect(waitRegistrations().length).toBeGreaterThanOrEqual(25);
+ expect(unremovedWaits()).toHaveLength(0);
+ vi.mocked(server.claimItemDelivery).mockResolvedValue({ kind: 'held', retryInMs: 10_000 });
+ emitReruns(tab, [100]);
+ tab.emit('queue_item_status_changed', completedEvent(100, buildQueueItemOrigin('gone', tab.project.id), 'canvas'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(unremovedWaits()).toHaveLength(1);
+ await tab.runtime.dispose();
+ expect(unremovedWaits()).toHaveLength(0);
+ expect(vi.getTimerCount()).toBe(0);
+ added.mockRestore();
+ removed.mockRestore();
+ vi.useRealTimers();
+ });
+
it('stages a Canvas rerun once across tabs and browsers, however late another sees it and after the first closed', async () => {
const server = createDeliveryServer();
const first = openCanvasTab(server);
@@ -4146,13 +4955,14 @@ describe('queue runtime retries', () => {
it('stages a Canvas rerun after the tab that claimed it closed before staging, once the claim expires', async () => {
const server = createDeliveryServer();
- // This tab closes while it reads the results, so it neither stages nor gives the claim back.
+ // A lost page cannot run cleanup; this abandoned claimant leaves its lease to expire.
+ let finishAbandoned!: (images: QueueResultImage[]) => void;
const closing = openCanvasTab(
server,
vi.fn(
() =>
- new Promise<QueueResultImage[]>(() => {
- // Never settles: the tab is gone.
+ new Promise<QueueResultImage[]>((resolve) => {
+ finishAbandoned = resolve;
})
)
);
@@ -4171,6 +4981,9 @@ describe('queue runtime retries', () => {
await vi.waitFor(() => expect(stagedItemIds(open)).toEqual([99]));
+ const disposal = closing.runtime.dispose();
+ finishAbandoned([{ imageName: 'late.png' } as QueueResultImage]);
+ await disposal;
await open.runtime.dispose();
});
@@ -4744,6 +5557,7 @@ describe('run outcomes', () => {
}),
history: {
commands,
+ listStagedResults: () => [],
getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
subscribe: (listener) => {
listeners.add(listener);
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 81208bb910..cdf9b32dad 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -47,11 +47,12 @@ import {
type ReconcileInput,
type ReconcileOutcome,
} from '@features/queue/runtime/coordinator';
+import { createDeliveryConfirmations } from '@features/queue/runtime/deliveryClaims';
import { createUuid } from '@platform/browser/randomUuid';
import { mapWithConcurrency } from '@platform/core/concurrency';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';
-import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { ApiError, getApiErrorMessage, sleep } from '@platform/transport/http';
export interface QueueResultDestinationPort {
addImagesToGalleryBoard(boardId: string, imageNames: string[]): Promise<void>;
@@ -382,6 +383,8 @@ export interface QueueHistoryPort {
isHydrated: boolean;
projects: QueueHistoryProject[];
};
+ /** Existing Canvas candidates, including those restored by project recovery; no new persistence schema. */
+ listStagedResults(): Array<{ backendItemId: number; projectId: string; queueItemId: string }>;
subscribe(listener: () => void): () => void;
}
@@ -409,6 +412,8 @@ const RERUN_CLAIM_TTL_MS = 120_000;
const RERUN_CLAIM_RENEW_MS = 40_000;
interface RunAttempt {
+ /** Only fresh admissions observed here are known ordinary; restored runs still need metadata validation. */
+ ordinaryBackendItemIds?: ReadonlySet<number>;
generation: number;
key: string;
projectId: string;
@@ -622,6 +627,7 @@ export const createQueueRuntime = ({
const beginAttempt = (projectId: string, queueItemId: string): RunAttempt => {
const key = getRunKey(projectId, queueItemId);
const attempt = {
+ ordinaryBackendItemIds: activeAttempts.get(key)?.ordinaryBackendItemIds,
generation: ++nextAttemptGeneration,
key,
projectId,
@@ -1262,8 +1268,32 @@ export const createQueueRuntime = ({
return;
}
+ if (images.length > 0) {
+ markAdoptedRerunsStaged(
+ projectId,
+ queueItem,
+ images.flatMap((image) => (image.sourceBackendItemId === undefined ? [] : [image.sourceBackendItemId]))
+ );
+ }
+ try {
+ deliveryConfirmations.routeOrdinaryResults(
+ backendItemIds.filter((id) => attempt.ordinaryBackendItemIds?.has(id)),
+ () => commands.routeResults({ images, projectId, queueItemId: queueItem.id, videos })
+ );
+ } catch (error) {
+ let stagedBackendItemIds: Set<number> | undefined;
+ for (const backendItemId of backendItemIds) {
+ const claim = adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId));
+ if (claim) {
+ stagedBackendItemIds ??= getStagedBackendItemIds(projectId, queueItem.id);
+ claim.isStaged = stagedBackendItemIds.has(backendItemId);
+ }
+ }
+ confirmAdoptedReruns(projectId, queueItem, backendItemIds);
+ releaseAdoptedReruns(projectId, queueItem.id);
+ throw error;
+ }
confirmAdoptedReruns(projectId, queueItem, backendItemIds);
- commands.routeResults({ images, projectId, queueItemId: queueItem.id, videos });
if (queueItem.snapshot.destination === 'gallery') {
commands.refreshBackendData();
}
@@ -1349,7 +1379,7 @@ export const createQueueRuntime = ({
}
// A renewal may have found the claim lost while the results loaded; another claimant stages the rerun then.
- const visibleImages = isAdoptedRerunDecidedHere(projectId, queueItem, backendItemId)
+ const visibleImages = (await isAdoptedRerunStagedHere(projectId, queueItem, backendItemId))
? await deliverVisibleImages(queueItem, images)
: [];
// Never throws — a board-attach hiccup must not block routePartialResults below.
@@ -1365,14 +1395,38 @@ export const createQueueRuntime = ({
queueItem.id,
visibleImages.map((image) => image.imageName)
);
+ if (visibleImages.length > 0) {
+ markAdoptedRerunsStaged(projectId, queueItem, [backendItemId]);
+ }
+ try {
+ deliveryConfirmations.routeOrdinaryResults(
+ attempt.ordinaryBackendItemIds?.has(backendItemId) ? [backendItemId] : [],
+ () =>
+ commands.routePartialResults({
+ backendItemId,
+ images: visibleImages,
+ projectId,
+ queueItemId: queueItem.id,
+ videos,
+ })
+ );
+ } catch (error) {
+ const claim = adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId));
+ if (claim) {
+ claim.isStaged = history
+ .listStagedResults()
+ .some(
+ (result) =>
+ result.backendItemId === backendItemId &&
+ result.projectId === projectId &&
+ result.queueItemId === queueItem.id
+ );
+ }
+ confirmAdoptedReruns(projectId, queueItem, [backendItemId]);
+ releaseAdoptedReruns(projectId, queueItem.id);
+ throw error;
+ }
confirmAdoptedReruns(projectId, queueItem, [backendItemId]);
- commands.routePartialResults({
- backendItemId,
- images: visibleImages,
- projectId,
- queueItemId: queueItem.id,
- videos,
- });
if (queueItem.snapshot.destination === 'gallery') {
commands.refreshBackendData();
}
@@ -1453,7 +1507,11 @@ export const createQueueRuntime = ({
if (target?.queueItem && !(await isAdoptedRerunStagedHere(target.project.id, target.queueItem, itemId))) {
return [];
}
- return runResultRead(() => backend.getResultImages(itemId, localQueueItemId, ...rest));
+ const images = await runResultRead(() => backend.getResultImages(itemId, localQueueItemId, ...rest));
+ if (target?.queueItem && !(await isAdoptedRerunStagedHere(target.project.id, target.queueItem, itemId))) {
+ return [];
+ }
+ return images;
},
};
const coordinator = createQueueCoordinator(
@@ -1508,6 +1566,7 @@ export const createQueueRuntime = ({
/** Backend ids of reruns no run in this tab adopted. */
const unadoptedReruns = new Set<number>();
+ const ownedUnadoptedClaims = new Map<number, string>();
const rememberUnadoptedRerun = (itemId: number): void => {
unadoptedReruns.add(itemId);
for (const oldest of unadoptedReruns) {
@@ -1521,17 +1580,7 @@ export const createQueueRuntime = ({
/** Ends every wait on another tab's run, or on a rerun another claimant holds, once this runtime stops. */
const rerunWaits = new AbortController();
const waitForRerunRetry = (delayMs: number): Promise<void> =>
- new Promise((resolve) => {
- const timer = setTimeout(resolve, delayMs);
- rerunWaits.signal.addEventListener(
- 'abort',
- () => {
- clearTimeout(timer);
- resolve();
- },
- { once: true }
- );
- });
+ sleep(delayMs, rerunWaits.signal).catch(() => undefined);
/** This tab, as the claimant of the reruns it stages outside any run. */
const tabClaimant = `tab:${createUuid()}`;
/** A run, as the claimant of the reruns it was reopened around; the run restored by a reload claims as it did. */
@@ -1543,8 +1592,16 @@ export const createQueueRuntime = ({
* request that fails is asked again for as long as a claim could last. A server without claims (a 404) lets every
* claimant stage it, as before claims existed.
*/
- const claimRerunDelivery = async (itemId: number, claimant: string, canDeliver: () => boolean): Promise<boolean> => {
+ const claimRerunDelivery = async (
+ itemId: number,
+ claimant: string,
+ canDeliver: () => boolean,
+ onClaim: () => void
+ ): Promise<boolean> => {
for (let failures = 0; ;) {
+ if (!isActive()) {
+ return false;
+ }
let claim: QueueItemDeliveryClaim;
try {
claim = await backend.claimItemDelivery(itemId, 'claim', claimant);
@@ -1559,7 +1616,14 @@ export const createQueueRuntime = ({
claim = { kind: 'held', retryInMs: RERUN_CLAIM_POLL_MS };
}
if (claim.kind !== 'held') {
- return claim.kind === 'claimed';
+ if (claim.kind === 'claimed' && !canDeliver()) {
+ settleRerunClaim(itemId, 'release', claimant);
+ return false;
+ }
+ if (claim.kind === 'claimed') {
+ onClaim();
+ }
+ return canDeliver() && claim.kind === 'claimed';
}
// Soon enough to see the holder confirm, and spread out so claimants turned away together do not ask together.
await waitForRerunRetry(Math.min(claim.retryInMs, RERUN_CLAIM_POLL_MS) * (1 + Math.random() / 2));
@@ -1569,15 +1633,51 @@ export const createQueueRuntime = ({
}
};
/** Whether this claimant still holds an item it claimed, renewing the claim; a server that cannot answer keeps it. */
- const isRerunClaimHeld = async (itemId: number, claimant: string): Promise<boolean> => {
+ const isRerunClaimHeld = async (
+ itemId: number,
+ claimant: string,
+ canDeliver: () => boolean,
+ onClaim: () => void
+ ): Promise<boolean> => {
+ if (!isActive()) {
+ return false;
+ }
try {
- return (await backend.claimItemDelivery(itemId, 'claim', claimant)).kind === 'claimed';
+ const result = await backend.claimItemDelivery(itemId, 'claim', claimant);
+ if (result.kind === 'claimed' && !canDeliver()) {
+ settleRerunClaim(itemId, 'release', claimant);
+ return false;
+ }
+ if (result.kind === 'claimed') {
+ onClaim();
+ }
+ return result.kind === 'claimed' && canDeliver();
} catch {
- return true;
+ return canDeliver();
}
};
- const settleRerunClaim = (itemId: number, action: 'confirm' | 'release', claimant: string): void => {
- void backend.claimItemDelivery(itemId, action, claimant).catch(() => undefined);
+ const deliveryConfirmations = createDeliveryConfirmations({
+ backend,
+ isActive,
+ signal: owner.signal,
+ reportError: (message) => commands.recordError({ area: 'queue-results', message, namespace: 'queue' }),
+ });
+ const settleRerunClaim = (
+ itemId: number,
+ action: 'confirm' | 'release',
+ claimant: string,
+ ownsClaim = false
+ ): void => {
+ if (action === 'confirm') {
+ deliveryConfirmations.confirm(itemId, claimant, ownsClaim);
+ } else if (
+ isAccountScopeCurrent(owner) &&
+ !deliveryConfirmations.isStaged(itemId) &&
+ !history.listStagedResults().some((result) => result.backendItemId === itemId)
+ ) {
+ // Same-account teardown may release unstaged work; an account change must never send with new credentials.
+ void backend.claimItemDelivery(itemId, action, claimant).catch(() => undefined);
+ }
};
/**
@@ -1587,7 +1687,8 @@ export const createQueueRuntime = ({
interface AdoptedRerunClaim {
decision: Promise<boolean>;
isClaimed: boolean;
- isConfirmed: boolean;
+ isStaged: boolean;
+ ownsClaim: boolean;
}
const adoptedRerunClaims = new Map<string, AdoptedRerunClaim>();
const getAdoptedRerunKey = (projectId: string, queueItemId: string, backendItemId: number): string =>
@@ -1607,13 +1708,17 @@ export const createQueueRuntime = ({
decision: claimRerunDelivery(
backendItemId,
getRunClaimant(projectId, queueItemId),
- () => isActive() && adoptedRerunClaims.get(key) === claim
+ () => isActive() && adoptedRerunClaims.get(key) === claim,
+ () => {
+ claim.ownsClaim = true;
+ }
).then((isClaimed) => {
claim.isClaimed = isClaimed;
return isClaimed;
}),
isClaimed: false,
- isConfirmed: false,
+ isStaged: deliveryConfirmations.isStaged(backendItemId),
+ ownsClaim: false,
};
adoptedRerunClaims.set(key, claim);
return claim;
@@ -1621,22 +1726,33 @@ export const createQueueRuntime = ({
/** Claim the Canvas reruns of a run this tab holds that it has yet to stage. */
const claimAdoptedReruns = (projectId: string, queueItem: QueueItem): void => {
for (const backendItemId of queueItem.backendItemIds ?? []) {
- if (isAdoptedRerun(queueItem, backendItemId) && !queueItem.completedBackendItemIds?.includes(backendItemId)) {
+ if (
+ isAdoptedRerun(queueItem, backendItemId) &&
+ !deliveryConfirmations.isStaged(backendItemId) &&
+ !queueItem.completedBackendItemIds?.includes(backendItemId)
+ ) {
claimAdoptedRerun(projectId, queueItem.id, backendItemId);
}
}
};
/** Keep the claims of runs still going from lapsing; a claim lost meanwhile leaves its rerun out of the run. */
const renewAdoptedRerunClaims = (): void => {
+ if (!isActive()) {
+ return;
+ }
+ deliveryConfirmations.renewOwned();
for (const [key, claim] of adoptedRerunClaims) {
- if (!claim.isClaimed || claim.isConfirmed) {
+ if (!claim.isClaimed || !claim.ownsClaim || claim.isStaged) {
continue;
}
const [projectId, queueItemId, backendItemId] = JSON.parse(key) as [string, string, number];
void backend
.claimItemDelivery(backendItemId, 'claim', getRunClaimant(projectId, queueItemId))
.then((renewal) => {
- if (renewal.kind !== 'claimed' && adoptedRerunClaims.get(key) === claim && !claim.isConfirmed) {
+ if (renewal.kind === 'claimed' && adoptedRerunClaims.get(key) !== claim && !claim.isStaged) {
+ settleRerunClaim(backendItemId, 'release', getRunClaimant(projectId, queueItemId));
+ }
+ if (renewal.kind !== 'claimed' && adoptedRerunClaims.get(key) === claim && !claim.isStaged) {
claim.isClaimed = false;
}
})
@@ -1652,11 +1768,28 @@ export const createQueueRuntime = ({
queueItem: QueueItem,
backendItemId: number
): Promise<boolean> => {
+ if (!isActive()) {
+ return false;
+ }
if (!isAdoptedRerun(queueItem, backendItemId)) {
return true;
}
+ if (deliveryConfirmations.isStaged(backendItemId)) {
+ return false;
+ }
const claim = claimAdoptedRerun(projectId, queueItem.id, backendItemId);
await claim.decision;
+ if (claim.isClaimed && !claim.isStaged) {
+ claim.isClaimed = await isRerunClaimHeld(
+ backendItemId,
+ getRunClaimant(projectId, queueItem.id),
+ () =>
+ isActive() && adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId)) === claim,
+ () => {
+ claim.ownsClaim = true;
+ }
+ );
+ }
return claim.isClaimed;
};
/**
@@ -1665,19 +1798,46 @@ export const createQueueRuntime = ({
*/
const isAdoptedRerunDecidedHere = (projectId: string, queueItem: QueueItem, backendItemId: number): boolean =>
!isAdoptedRerun(queueItem, backendItemId) ||
- adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId))?.isClaimed === true;
+ (!deliveryConfirmations.isStaged(backendItemId) &&
+ adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId))?.isClaimed === true);
/**
- * Confirm the reruns a run is about to stage. Called just before their results are routed, since routing them can
- * finish the run, and a finished run gives back the claims it did not confirm.
+ * Protect claims during synchronous routing, which may finish the run and release its unstaged claims.
+ * Actual candidates decide confirmation; a routing failure releases only work it did not stage.
*/
- const confirmAdoptedReruns = (projectId: string, queueItem: QueueItem, backendItemIds: number[]): void => {
+ const markAdoptedRerunsStaged = (projectId: string, queueItem: QueueItem, backendItemIds: number[]): void => {
for (const backendItemId of backendItemIds) {
const claim = adoptedRerunClaims.get(getAdoptedRerunKey(projectId, queueItem.id, backendItemId));
- if (claim?.isClaimed && !claim.isConfirmed) {
- claim.isConfirmed = true;
- settleRerunClaim(backendItemId, 'confirm', getRunClaimant(projectId, queueItem.id));
+ if (claim?.isClaimed && !claim.isStaged) {
+ claim.isStaged = true;
+ }
+ }
+ };
+ const getStagedBackendItemIds = (projectId: string, queueItemId: string): Set<number> => {
+ const backendItemIds = new Set<number>();
+ for (const result of history.listStagedResults()) {
+ if (result.projectId === projectId && result.queueItemId === queueItemId) {
+ backendItemIds.add(result.backendItemId);
}
}
+ return backendItemIds;
+ };
+ const confirmAdoptedReruns = (projectId: string, queueItem: QueueItem, backendItemIds: number[]): void => {
+ let stagedBackendItemIds: Set<number> | undefined;
+ for (const backendItemId of backendItemIds) {
+ const key = getAdoptedRerunKey(projectId, queueItem.id, backendItemId);
+ const claim = adoptedRerunClaims.get(key);
+ if (!claim?.isStaged) {
+ continue;
+ }
+ stagedBackendItemIds ??= getStagedBackendItemIds(projectId, queueItem.id);
+ if (!stagedBackendItemIds.has(backendItemId)) {
+ claim.isStaged = false;
+ releaseAdoptedReruns(projectId, queueItem.id);
+ continue;
+ }
+ settleRerunClaim(backendItemId, 'confirm', getRunClaimant(projectId, queueItem.id), claim.ownsClaim);
+ adoptedRerunClaims.delete(key);
+ }
};
/**
* A run this tab lets go of, whether it ended or its project closed, gives back the claims it did not confirm, so
@@ -1689,8 +1849,8 @@ export const createQueueRuntime = ({
if (keyProjectId !== projectId || keyQueueItemId !== queueItemId) {
continue;
}
- adoptedRerunClaims.delete(key);
- if (!claim.isConfirmed) {
+ if (!claim.isStaged) {
+ adoptedRerunClaims.delete(key);
void claim.decision.then((isClaimed) => {
if (isClaimed) {
settleRerunClaim(backendItemId, 'release', getRunClaimant(projectId, queueItemId));
@@ -1879,20 +2039,55 @@ export const createQueueRuntime = ({
if (await isRunTrackedElsewhere(projectId, queueItemId)) {
await locks?.waitForRunRelease(projectId, queueItemId, rerunWaits.signal);
}
- if (!canStage() || !(await claimRerunDelivery(event.item_id, tabClaimant, canStage))) {
+ let ownsClaim = false;
+ if (
+ !canStage() ||
+ !(await claimRerunDelivery(event.item_id, tabClaimant, canStage, () => {
+ ownsClaim = true;
+ }))
+ ) {
+ return;
+ }
+ if (!canStage()) {
+ settleRerunClaim(event.item_id, 'release', tabClaimant);
return;
}
- // Confirmed only once staged, so a tab that cannot stage it, or closes first, leaves the rerun to the next.
+ ownedUnadoptedClaims.set(event.item_id, projectId);
+ // The candidate read model remains authoritative even if a routing callback stages and then throws.
let isStaged = false;
try {
const images = await readUnadoptedRerunImages(event, queueItemId, run);
// A read slower than the claim lasts may have let another claimant stage it meanwhile.
- if (images.length > 0 && canStage() && (await isRerunClaimHeld(event.item_id, tabClaimant)) && canStage()) {
+ if (
+ images.length > 0 &&
+ canStage() &&
+ (await isRerunClaimHeld(event.item_id, tabClaimant, canStage, () => {
+ ownsClaim = true;
+ })) &&
+ canStage()
+ ) {
commands.stageRetriedCanvasResults({ backendItemId: event.item_id, images, projectId, queueItemId });
- isStaged = true;
+ isStaged = history
+ .listStagedResults()
+ .some(
+ (result) =>
+ result.backendItemId === event.item_id &&
+ result.projectId === projectId &&
+ result.queueItemId === queueItemId
+ );
}
} finally {
- settleRerunClaim(event.item_id, isStaged ? 'confirm' : 'release', tabClaimant);
+ isStaged ||= history
+ .listStagedResults()
+ .some(
+ (result) =>
+ result.backendItemId === event.item_id &&
+ result.projectId === projectId &&
+ result.queueItemId === queueItemId
+ );
+ if (ownedUnadoptedClaims.delete(event.item_id)) {
+ settleRerunClaim(event.item_id, isStaged ? 'confirm' : 'release', tabClaimant, ownsClaim);
+ }
}
};
void stage().catch(recordError);
@@ -2004,6 +2199,9 @@ export const createQueueRuntime = ({
});
}
+ if (currentQueueItem.snapshot.destination === 'canvas') {
+ attempt.ordinaryBackendItemIds = new Set(itemIds);
+ }
commands.markBackendSubmitted({
backendBatchId: batchId,
backendItemIds: itemIds,
@@ -2080,9 +2278,16 @@ export const createQueueRuntime = ({
if (!hasInitialized || !isActive()) {
return;
}
- const activeKeys = new Set<string>();
const projects = history.getSnapshot().projects;
+ deliveryConfirmations.recover(history.listStagedResults());
+ const activeKeys = new Set<string>();
const openProjectIds = new Set(projects.map((project) => project.id));
+ for (const [itemId, projectId] of ownedUnadoptedClaims) {
+ if (!openProjectIds.has(projectId)) {
+ settleRerunClaim(itemId, 'release', tabClaimant);
+ ownedUnadoptedClaims.delete(itemId);
+ }
+ }
for (const project of projects) {
for (const item of project.queue.items) {
const key = getRunKey(project.id, item.id);
@@ -2712,6 +2917,21 @@ export const createQueueRuntime = ({
const dispose = async (): Promise<void> => {
isDisposed = true;
rerunWaits.abort();
+ for (const key of adoptedRerunClaims.keys()) {
+ const [projectId, queueItemId] = JSON.parse(key) as [string, string];
+ releaseAdoptedReruns(projectId, queueItemId);
+ }
+ adoptedRerunClaims.clear();
+ for (const itemId of ownedUnadoptedClaims.keys()) {
+ settleRerunClaim(itemId, 'release', tabClaimant);
+ }
+ ownedUnadoptedClaims.clear();
+ unadoptedReruns.clear();
+ deliveryConfirmations.dispose();
+ if (renewTimer !== undefined) {
+ clearInterval(renewTimer);
+ renewTimer = undefined;
+ }
if (retryTimer !== undefined) {
clearTimeout(retryTimer);
retryTimer = undefined;
@@ -2747,15 +2967,6 @@ export const createQueueRuntime = ({
)
);
}
- if (renewTimer !== undefined) {
- clearInterval(renewTimer);
- renewTimer = undefined;
- }
- // A run restored by the next hold claims again as the same claimant; meanwhile another tab may stage the rerun.
- for (const key of adoptedRerunClaims.keys()) {
- const [projectId, queueItemId] = JSON.parse(key) as [string, string];
- releaseAdoptedReruns(projectId, queueItemId);
- }
startedRunKeys.clear();
preparingRunKeys.clear();
pendingJournalSettles.clear();
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.test.ts
new file mode 100644
index 0000000000..1d945d3715
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.test.ts
@@ -0,0 +1,325 @@
+import type { QueueBackendPort, QueueItemReadModel } from '@features/queue/core/types';
+
+import { buildQueueItemOrigin } from '@features/queue/data/events';
+import { ApiError } from '@platform/transport/http';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createDeliveryConfirmations, type StagedQueueResult } from './deliveryClaims';
+
+const candidate = (id: number): StagedQueueResult => ({ backendItemId: id, projectId: 'project', queueItemId: 'run' });
+const item = (id: number, retry: number | null = 1): QueueItemReadModel =>
+ ({
+ id,
+ retriedFromItemId: retry,
+ destination: 'canvas',
+ origin: buildQueueItemOrigin('run', 'project'),
+ }) as QueueItemReadModel;
+const harness = (overrides: Partial<QueueBackendPort> = {}) => {
+ const backend = {
+ claimItemDelivery: vi.fn<QueueBackendPort['claimItemDelivery']>().mockResolvedValue({ kind: 'delivered' }),
+ readItemsById: vi
+ .fn<QueueBackendPort['readItemsById']>()
+ .mockImplementation((ids) => Promise.resolve(ids.map((id) => item(id)))),
+ ...overrides,
+ };
+ const reportError = vi.fn();
+ const owner = new AbortController();
+ const confirmations = createDeliveryConfirmations({
+ backend,
+ isActive: () => !owner.signal.aborted,
+ signal: owner.signal,
+ reportError,
+ });
+ return { backend, confirmations, reportError, owner };
+};
+
+afterEach(() => vi.useRealTimers());
+
+describe('delivery confirmations', () => {
+ it('reads recovered candidates serially in bounded batches and caps confirmation writes at eight', async () => {
+ let activeReads = 0;
+ let maxReads = 0;
+ let activeWrites = 0;
+ let maxWrites = 0;
+ const releases: Array<() => void> = [];
+ const { backend, confirmations } = harness({
+ readItemsById: vi.fn<QueueBackendPort['readItemsById']>(async (ids) => {
+ activeReads += 1;
+ maxReads = Math.max(maxReads, activeReads);
+ await Promise.resolve();
+ activeReads -= 1;
+ return ids.map((id) => item(id, id % 2 ? 1 : null));
+ }),
+ claimItemDelivery: vi.fn<QueueBackendPort['claimItemDelivery']>(() => {
+ activeWrites += 1;
+ maxWrites = Math.max(maxWrites, activeWrites);
+ return new Promise((resolve) => {
+ releases.push(() => {
+ activeWrites -= 1;
+ resolve({ kind: 'delivered' });
+ });
+ });
+ }),
+ });
+ const candidates = Array.from({ length: 200 }, (_, index) => candidate(index + 1));
+ confirmations.recover(candidates);
+ confirmations.recover(candidates);
+ await vi.waitFor(() => expect(backend.readItemsById).toHaveBeenCalledTimes(4));
+ expect(vi.mocked(backend.readItemsById).mock.calls.map(([ids]) => ids.length)).toEqual([64, 64, 64, 8]);
+ expect(maxReads).toBe(1);
+ expect(backend.claimItemDelivery).toHaveBeenCalledTimes(8);
+ for (let i = 0; i < 13; i += 1) {
+ for (const release of releases.splice(0)) {
+ release();
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+ await vi.waitFor(() => expect(backend.claimItemDelivery).toHaveBeenCalledTimes(100));
+ expect(maxWrites).toBe(8);
+ expect(
+ vi.mocked(backend.claimItemDelivery).mock.calls.every(([id, action]) => id % 2 === 1 && action === 'confirm')
+ ).toBe(true);
+ confirmations.recover(candidates);
+ await Promise.resolve();
+ expect(backend.readItemsById).toHaveBeenCalledTimes(4);
+ confirmations.dispose();
+ releases.splice(0).forEach((release) => release());
+ });
+
+ it('does not confirm ordinary, missing, foreign-project, foreign-run or non-Canvas rows after reload/history clearing', async () => {
+ const { backend, confirmations } = harness({
+ readItemsById: vi
+ .fn()
+ .mockResolvedValue([
+ item(1, null),
+ { ...item(3), origin: buildQueueItemOrigin('run', 'other-project') },
+ { ...item(4), origin: buildQueueItemOrigin('other-run', 'project') },
+ { ...item(5), destination: 'gallery' },
+ item(6),
+ ]),
+ });
+ const candidates = [1, 2, 3, 4, 5, 6].map(candidate);
+ confirmations.recover(candidates);
+ await vi.waitFor(() => expect(backend.claimItemDelivery).toHaveBeenCalledTimes(1));
+ expect(backend.claimItemDelivery).toHaveBeenCalledWith(6, 'confirm', 'run:["project","run"]');
+ confirmations.recover(candidates);
+ expect(backend.readItemsById).toHaveBeenCalledTimes(1);
+ confirmations.dispose();
+ });
+
+ it.each([false, true])(
+ 'keeps only surviving ordinary candidates when routing throws (staged: %s)',
+ async (staged) => {
+ const { backend, confirmations } = harness();
+ expect(() =>
+ confirmations.routeOrdinaryResults([99], () => {
+ if (staged) {
+ confirmations.recover([candidate(99)]);
+ }
+ throw new Error('routing failed');
+ })
+ ).toThrow('routing failed');
+ if (staged) {
+ confirmations.recover([candidate(99)]);
+ await Promise.resolve();
+ expect(backend.readItemsById).not.toHaveBeenCalled();
+ // Removing the candidate ends its classification, so a later restored candidate must be validated again.
+ confirmations.recover([]);
+ }
+ confirmations.recover([candidate(99)]);
+ await vi.waitFor(() =>
+ expect(backend.claimItemDelivery).toHaveBeenCalledWith(99, 'confirm', 'run:["project","run"]')
+ );
+ expect(backend.readItemsById).toHaveBeenCalledExactlyOnceWith([99], expect.any(AbortSignal));
+ confirmations.dispose();
+ }
+ );
+
+ it('shares one five-attempt budget across run/tab claimants and synchronous candidate notifications', async () => {
+ vi.useFakeTimers();
+ const { backend, confirmations, reportError } = harness({
+ claimItemDelivery: vi.fn().mockRejectedValue(new TypeError('offline')),
+ });
+ confirmations.confirm(99, 'tab:one');
+ confirmations.recover([candidate(99)]);
+ confirmations.confirm(99, 'run:two');
+ await vi.advanceTimersByTimeAsync(30_000);
+ confirmations.recover([candidate(99)]);
+ confirmations.confirm(99, 'tab:one');
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(backend.claimItemDelivery).toHaveBeenCalledTimes(5);
+ expect(reportError).toHaveBeenCalledOnce();
+ expect(reportError).toHaveBeenCalledWith(expect.stringContaining('are staged'));
+ expect(backend.readItemsById).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ confirmations.dispose();
+ });
+
+ it('bounds failed recovery reads and reports exhausted recovery without arbitrary claim renewals', async () => {
+ vi.useFakeTimers();
+ const { backend, confirmations, reportError } = harness({
+ readItemsById: vi.fn().mockRejectedValue(new TypeError('offline')),
+ });
+ const candidates = Array.from({ length: 1_000 }, (_, index) => candidate(index + 1));
+ confirmations.recover(candidates);
+ await vi.advanceTimersByTimeAsync(180_000);
+ confirmations.recover(candidates);
+ expect(backend.readItemsById).toHaveBeenCalledTimes(3);
+ expect(backend.claimItemDelivery).not.toHaveBeenCalled();
+ expect(reportError).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ confirmations.dispose();
+ });
+
+ it('clears retry timers and queued confirmations when its account ends', async () => {
+ vi.useFakeTimers();
+ const { backend, confirmations, owner, reportError } = harness({
+ claimItemDelivery: vi.fn().mockRejectedValue(new TypeError('offline')),
+ });
+ for (let id = 1; id <= 20; id += 1) {
+ confirmations.confirm(id, 'tab:owner');
+ }
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vi.getTimerCount()).toBe(20);
+ owner.abort();
+ expect(vi.getTimerCount()).toBe(0);
+ const requests = vi.mocked(backend.claimItemDelivery).mock.calls.length;
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(backend.claimItemDelivery).toHaveBeenCalledTimes(requests);
+ expect(reportError).not.toHaveBeenCalled();
+ expect(confirmations.isStaged(1)).toBe(false);
+ });
+
+ it('drains candidates arriving as the previous recovery pass is finishing', async () => {
+ const { backend, confirmations } = harness();
+ confirmations.recover([]);
+ confirmations.recover([candidate(99)]);
+ await vi.waitFor(() =>
+ expect(backend.claimItemDelivery).toHaveBeenCalledWith(99, 'confirm', 'run:["project","run"]')
+ );
+ confirmations.dispose();
+ });
+
+ it('renews a granted live lease behind a recovery backlog without claiming recovered candidates', async () => {
+ vi.useFakeTimers();
+ let claimedAt = Date.now();
+ let holder = 'tab:actual';
+ const backend = {
+ readItemsById: vi
+ .fn<QueueBackendPort['readItemsById']>()
+ .mockImplementation((ids) => Promise.resolve(ids.map((id) => item(id)))),
+ claimItemDelivery: vi.fn<QueueBackendPort['claimItemDelivery']>((_id, action, claimant) => {
+ if (action === 'confirm') {
+ return new Promise(() => {
+ /* Keep confirmation transport deferred while the lease-renewal queue drains. */
+ });
+ }
+ if (holder !== claimant && Date.now() - claimedAt < 120_000) {
+ return Promise.resolve({ kind: 'held', retryInMs: 120_000 - (Date.now() - claimedAt) });
+ }
+ holder = claimant;
+ claimedAt = Date.now();
+ return Promise.resolve({ kind: 'claimed' });
+ }),
+ };
+ const { confirmations } = harness(backend);
+ confirmations.recover(Array.from({ length: 30 }, (_, index) => candidate(index + 1)));
+ await vi.advanceTimersByTimeAsync(0);
+ confirmations.confirm(999, 'run:recovery');
+ confirmations.confirm(999, 'tab:actual', true);
+ confirmations.confirm(999, 'tab:fail-open');
+ const timer = setInterval(confirmations.renewOwned, 40_000);
+ await vi.advanceTimersByTimeAsync(160_000);
+ const renewals = backend.claimItemDelivery.mock.calls.filter(([, action]) => action === 'claim');
+ expect(renewals).toEqual(Array.from({ length: 4 }, () => [999, 'claim', 'tab:actual']));
+ expect(backend.claimItemDelivery.mock.calls.filter(([, action]) => action === 'confirm')).toHaveLength(8);
+ await expect(backend.claimItemDelivery(999, 'claim', 'another-browser')).resolves.toMatchObject({ kind: 'held' });
+ confirmations.dispose();
+ clearInterval(timer);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('keeps an upgraded live holder when the previous holder renewal responds late', async () => {
+ let finishOldRenewal!: () => void;
+ const { backend, confirmations } = harness({
+ claimItemDelivery: vi.fn<QueueBackendPort['claimItemDelivery']>((_id, action, claimant) => {
+ if (action === 'confirm') {
+ return new Promise(() => {
+ /* Confirmation remains unresolved while delivery ownership changes. */
+ });
+ }
+ if (claimant === 'tab:old') {
+ return new Promise((resolve) => {
+ finishOldRenewal = () => resolve({ kind: 'held', retryInMs: 120_000 });
+ });
+ }
+ return Promise.resolve({ kind: 'claimed' });
+ }),
+ });
+ confirmations.confirm(99, 'tab:old', true);
+ confirmations.renewOwned();
+ confirmations.confirm(99, 'tab:new', true);
+ finishOldRenewal();
+ // Let the old response and its in-flight cleanup settle before the next renewal tick.
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ confirmations.renewOwned();
+ expect(backend.claimItemDelivery).toHaveBeenCalledWith(99, 'claim', 'tab:new');
+ confirmations.dispose();
+ });
+
+ it('bounds and coalesces owned lease renewal requests', async () => {
+ let active = 0;
+ let peak = 0;
+ const finishers: Array<() => void> = [];
+ const { backend, confirmations } = harness({
+ claimItemDelivery: vi.fn<QueueBackendPort['claimItemDelivery']>((_id, action) => {
+ if (action === 'confirm') {
+ return new Promise(() => {
+ /* Keep confirmation transport deferred while the lease-renewal queue drains. */
+ });
+ }
+ active += 1;
+ peak = Math.max(peak, active);
+ return new Promise((resolve) => {
+ finishers.push(() => {
+ active -= 1;
+ resolve({ kind: 'claimed' });
+ });
+ });
+ }),
+ });
+ for (let id = 1; id <= 20; id += 1) {
+ confirmations.confirm(id, 'tab:owner', true);
+ }
+ confirmations.renewOwned();
+ confirmations.renewOwned();
+ expect(active).toBe(8);
+ for (let i = 0; i < 3; i += 1) {
+ finishers.splice(0).forEach((finish) => finish());
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+ await vi.waitFor(() =>
+ expect(vi.mocked(backend.claimItemDelivery).mock.calls.filter(([, action]) => action === 'claim')).toHaveLength(
+ 20
+ )
+ );
+ expect(peak).toBe(8);
+ confirmations.dispose();
+ });
+
+ it('keeps the unsupported-endpoint fallback quiet', async () => {
+ const { backend, confirmations, reportError } = harness({
+ claimItemDelivery: vi.fn().mockRejectedValue(new ApiError('unsupported', 404)),
+ });
+ confirmations.confirm(99, 'tab:one');
+ await vi.waitFor(() => expect(backend.claimItemDelivery).toHaveBeenCalledOnce());
+ expect(reportError).not.toHaveBeenCalled();
+ confirmations.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.transport.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.transport.test.ts
new file mode 100644
index 0000000000..c98bd17c3f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.transport.test.ts
@@ -0,0 +1,62 @@
+import { queueBackend } from '@features/queue/data/httpRealtimeQueueBackend';
+import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { createDeliveryConfirmations } from './deliveryClaims';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it('replays a hung production confirmation with the exact delivery endpoint/body and keeps server delivery', async () => {
+ const owner = captureAccountScope();
+ const timeout = AbortSignal.timeout.bind(AbortSignal);
+ vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => timeout(Math.min(ms, 5)));
+ let requests = 0;
+ let delivered = false;
+ let timeoutReason: unknown;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;
+ if (
+ !String(input).endsWith('/api/v1/queue/default/i/99/delivery') ||
+ init?.method !== 'POST' ||
+ JSON.stringify(body) !== JSON.stringify({ action: 'confirm', claimant: 'tab:owner' })
+ ) {
+ return Promise.resolve(Response.json({ detail: 'Invalid delivery request' }, { status: 422 }));
+ }
+ delivered = true;
+ if (++requests === 1) {
+ return new Promise((_resolve, reject) => {
+ init!.signal!.addEventListener(
+ 'abort',
+ () => {
+ timeoutReason = init!.signal!.reason;
+ reject(timeoutReason);
+ },
+ { once: true }
+ );
+ });
+ }
+ return Promise.resolve(Response.json({ status: 'delivered' }));
+ })
+ );
+ const reportError = vi.fn();
+ const confirmations = createDeliveryConfirmations({
+ backend: queueBackend,
+ isActive: () => true,
+ signal: owner.signal,
+ reportError,
+ });
+ try {
+ confirmations.confirm(99, 'tab:owner');
+ await vi.waitFor(() => expect(requests).toBe(2), { timeout: 2_000 });
+ expect(timeoutReason).toMatchObject({ name: 'TimeoutError' });
+ expect(delivered).toBe(true);
+ expect(reportError).not.toHaveBeenCalled();
+ } finally {
+ confirmations.dispose();
+ }
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.ts b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.ts
new file mode 100644
index 0000000000..7e2948ff87
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/deliveryClaims.ts
@@ -0,0 +1,297 @@
+import type { QueueBackendPort } from '@features/queue/core/types';
+
+import { parseQueueItemOrigin, parseQueueItemOriginProjectId } from '@features/queue/data/events';
+import { ApiError, sleep } from '@platform/transport/http';
+
+export type StagedQueueResult = { backendItemId: number; projectId: string; queueItemId: string };
+
+/** Owns bounded, claimant-independent confirmation and authoritative candidate recovery for one account runtime. */
+export const createDeliveryConfirmations = ({
+ backend,
+ isActive,
+ signal,
+ reportError,
+}: {
+ backend: Pick<QueueBackendPort, 'claimItemDelivery' | 'readItemsById'>;
+ isActive: () => boolean;
+ signal: AbortSignal;
+ reportError: (message: string) => void;
+}) => {
+ const confirmations = new Map<
+ number,
+ {
+ attempts: number;
+ claimant: string;
+ settled: boolean;
+ leaseClaimant?: string;
+ timer?: ReturnType<typeof setTimeout>;
+ }
+ >();
+ const ready = new Set<number>();
+ const renewalQueue = new Set<number>();
+ const renewing = new Set<number>();
+ let activeRenewals = 0;
+ let candidates = new Map<number, StagedQueueResult>();
+ const checkedCandidates = new Set<number>();
+ const recovery = new AbortController();
+ let activeRequests = 0;
+ let recovering = false;
+ let recoverAgain = false;
+ let recoveryFailed = false;
+ let disposed = false;
+ const active = () => !disposed && isActive();
+
+ const drain = (): void => {
+ if (!active()) {
+ return;
+ }
+ for (const itemId of ready) {
+ const pending = confirmations.get(itemId)!;
+ if (activeRequests >= 8) {
+ break;
+ }
+ ready.delete(itemId);
+ pending.attempts += 1;
+ activeRequests += 1;
+ void backend
+ .claimItemDelivery(itemId, 'confirm', pending.claimant)
+ .then((result) => {
+ if (result.kind !== 'delivered') {
+ throw new Error('Invalid delivery confirmation response');
+ }
+ pending.settled = true;
+ })
+ .catch((error: unknown) => {
+ if (!active()) {
+ return;
+ }
+ const definitive =
+ error instanceof ApiError && error.status < 500 && error.status !== 408 && error.status !== 429;
+ if (definitive || pending.attempts >= 5) {
+ pending.settled = true;
+ if (error instanceof ApiError && error.status === 404) {
+ return;
+ }
+ reportError(
+ 'Canvas results are staged, but server delivery could not be confirmed. Another browser may deliver them again.'
+ );
+ return;
+ }
+ pending.timer = setTimeout(
+ () => {
+ pending.timer = undefined;
+ ready.add(itemId);
+ drain();
+ },
+ 1_000 * 2 ** (pending.attempts - 1)
+ );
+ })
+ .finally(() => {
+ activeRequests -= 1;
+ drain();
+ });
+ }
+ };
+
+ const confirm = (itemId: number, claimant: string, ownsClaim = false): void => {
+ if (!active()) {
+ return;
+ }
+ const existing = confirmations.get(itemId);
+ if (existing) {
+ if (ownsClaim && !existing.settled) {
+ existing.leaseClaimant = claimant;
+ }
+ return;
+ }
+ confirmations.set(itemId, {
+ attempts: 0,
+ claimant,
+ settled: false,
+ ...(ownsClaim ? { leaseClaimant: claimant } : {}),
+ });
+ ready.add(itemId);
+ drain();
+ };
+
+ const drainRenewals = (): void => {
+ if (!active()) {
+ return;
+ }
+ for (const itemId of renewalQueue) {
+ if (activeRenewals >= 8) {
+ break;
+ }
+ renewalQueue.delete(itemId);
+ const pending = confirmations.get(itemId);
+ if (!pending?.leaseClaimant || pending.settled) {
+ continue;
+ }
+ const leaseClaimant = pending.leaseClaimant;
+ activeRenewals += 1;
+ renewing.add(itemId);
+ void backend
+ .claimItemDelivery(itemId, 'claim', leaseClaimant)
+ .then((result) => {
+ if (
+ confirmations.get(itemId) === pending &&
+ pending.leaseClaimant === leaseClaimant &&
+ result.kind !== 'claimed'
+ ) {
+ pending.leaseClaimant = undefined;
+ }
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ renewing.delete(itemId);
+ activeRenewals -= 1;
+ drainRenewals();
+ });
+ }
+ };
+ const renewOwned = (): void => {
+ if (!active()) {
+ return;
+ }
+ for (const [id, pending] of confirmations) {
+ if (pending.leaseClaimant && !pending.settled && !renewing.has(id)) {
+ renewalQueue.add(id);
+ }
+ }
+ drainRenewals();
+ };
+
+ const routeOrdinaryResults = (itemIds: number[], route: () => void): void => {
+ // Mark before synchronous staging notifications; retain only candidates the route actually leaves behind.
+ for (const id of itemIds) {
+ checkedCandidates.add(id);
+ }
+ try {
+ route();
+ } finally {
+ for (const id of itemIds) {
+ if (!candidates.has(id)) {
+ checkedCandidates.delete(id);
+ }
+ }
+ }
+ };
+
+ const recover = (staged: StagedQueueResult[]): void => {
+ if (!active()) {
+ return;
+ }
+ candidates = new Map(staged.map((candidate) => [candidate.backendItemId, candidate]));
+ for (const id of checkedCandidates) {
+ if (!candidates.has(id)) {
+ checkedCandidates.delete(id);
+ }
+ }
+ // Retain exhausted budgets while the candidate exists; synchronous staging notifications cannot restart them.
+ for (const [id, pending] of confirmations) {
+ if (!candidates.has(id) && pending.settled) {
+ confirmations.delete(id);
+ }
+ }
+ if (recovering) {
+ recoverAgain = true;
+ return;
+ }
+ if (recoveryFailed) {
+ return;
+ }
+ recovering = true;
+ void (async () => {
+ while (active()) {
+ const batch = [...candidates.values()]
+ .filter(
+ (candidate) =>
+ !checkedCandidates.has(candidate.backendItemId) && !confirmations.has(candidate.backendItemId)
+ )
+ .slice(0, 64);
+ if (batch.length === 0) {
+ return;
+ }
+ for (const candidate of batch) {
+ checkedCandidates.add(candidate.backendItemId);
+ }
+ for (let attempt = 0; attempt < 3 && active(); attempt += 1) {
+ try {
+ const items = await backend.readItemsById(
+ batch.map((candidate) => candidate.backendItemId),
+ AbortSignal.any([signal, recovery.signal, AbortSignal.timeout(10_000)])
+ );
+ if (!active()) {
+ return;
+ }
+ for (const item of items) {
+ const candidate = candidates.get(item.id);
+ // Queue history is transient; backend retry ancestry survives reload and completed-history clearing.
+ if (
+ candidate &&
+ item.retriedFromItemId !== null &&
+ item.retriedFromItemId !== undefined &&
+ item.destination === 'canvas' &&
+ parseQueueItemOrigin(item.origin) === candidate.queueItemId &&
+ parseQueueItemOriginProjectId(item.origin) === candidate.projectId
+ ) {
+ confirm(item.id, `run:${JSON.stringify([candidate.projectId, candidate.queueItemId])}`);
+ }
+ }
+ break;
+ } catch {
+ if (!active()) {
+ return;
+ }
+ if (attempt === 2) {
+ recoveryFailed = true;
+ reportError(
+ 'Staged Canvas results could not be checked for delivery recovery. Reload the editor to retry.'
+ );
+ return;
+ } else {
+ await sleep(1_000 * 2 ** attempt, AbortSignal.any([signal, recovery.signal]));
+ }
+ }
+ }
+ }
+ })()
+ .catch(() => undefined)
+ .finally(() => {
+ recovering = false;
+ if (recoverAgain) {
+ recoverAgain = false;
+ recover([...candidates.values()]);
+ }
+ });
+ };
+
+ const dispose = (): void => {
+ disposed = true;
+ recoverAgain = false;
+ signal.removeEventListener('abort', dispose);
+ recovery.abort();
+ for (const pending of confirmations.values()) {
+ clearTimeout(pending.timer);
+ }
+ confirmations.clear();
+ ready.clear();
+ renewalQueue.clear();
+ renewing.clear();
+ candidates.clear();
+ checkedCandidates.clear();
+ };
+ signal.addEventListener('abort', dispose, { once: true });
+ if (signal.aborted) {
+ dispose();
+ }
+
+ return {
+ confirm,
+ renewOwned,
+ routeOrdinaryResults,
+ isStaged: (itemId: number) => confirmations.has(itemId) || candidates.has(itemId),
+ recover,
+ dispose,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts
index c27d1ac09f..444f9044bd 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts
@@ -9,13 +9,13 @@ import {
isUtilityQueueItemOrigin,
parseQueueItemOrigin,
} from '@features/queue/contracts';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { UtilityEnqueue, UtilityItemStatusReader } from './utilityGraph';
import {
- DEFAULT_UTILITY_QUEUE_TIMEOUT_MS,
DEFAULT_UTILITY_RECONCILE_INTERVAL_MS,
runUtilityGraph,
submitUtilityGraph,
@@ -190,6 +190,8 @@ const createReconcileScheduler = () => {
};
afterEach(() => {
+ accountLifecycle.invalidate();
+ vi.unstubAllGlobals();
vi.useRealTimers();
});
@@ -285,7 +287,7 @@ describe('runUtilityGraph — await + settle', () => {
origin: ORIGIN,
width: 64,
});
- expect(reconcileCompletedOutput).toHaveBeenCalledExactlyOnceWith([1], 'control_filter');
+ expect(reconcileCompletedOutput).toHaveBeenCalledExactlyOnceWith([1], 'control_filter', expect.any(AbortSignal));
expect(fake.handlerCount('invocation_complete')).toBe(0);
expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
});
@@ -888,7 +890,7 @@ describe('runUtilityGraph — timeout + cancellation', () => {
hub: fake.hub,
timeoutMs: 0,
});
- await vi.advanceTimersByTimeAsync(DEFAULT_UTILITY_QUEUE_TIMEOUT_MS * 2);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
// Still pending — settle it so the promise doesn't leak.
fake.emit('invocation_complete', completeEvent());
fake.emit('queue_item_status_changed', statusEvent('completed'));
@@ -1160,7 +1162,7 @@ describe('runUtilityGraph — missed settlement', () => {
await Promise.resolve();
removed.emit('queue_cleared', { queue_id: 'default', timestamp: 1, user_id: null });
await expect(removedRun).rejects.toMatchObject({ reason: 'removed' });
- expect(readRemoved).toHaveBeenCalledExactlyOnceWith(3, undefined);
+ expect(readRemoved).toHaveBeenCalledExactlyOnceWith(3, expect.any(AbortSignal));
expect(removed.handlerCount('queue_items_canceled')).toBe(0);
const canceled = createFakeHub();
@@ -1258,7 +1260,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
const submission = await submitUtilityGraph({ createId: () => UTIL_ID, enqueue, graph, hub: fake.hub });
- expect(enqueue).toHaveBeenCalledExactlyOnceWith({ graph, origin: ORIGIN });
+ expect(enqueue).toHaveBeenCalledExactlyOnceWith({ graph, origin: ORIGIN, idempotencyKey: ORIGIN });
expect(submission).toMatchObject({ itemIds: [7], origin: ORIGIN });
// Only status changes are watched; no output image is expected.
expect(fake.handlerCount('invocation_complete')).toBe(0);
@@ -1358,7 +1360,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
await submitUtilityGraph({ createId: () => UTIL_ID, enqueue, graph, hub: fake.hub, prepend: true });
- expect(enqueue).toHaveBeenCalledExactlyOnceWith({ graph, origin: ORIGIN, prepend: true });
+ expect(enqueue).toHaveBeenCalledExactlyOnceWith({ graph, origin: ORIGIN, prepend: true, idempotencyKey: ORIGIN });
});
it('aborting ends the watch: the listener detaches, the timer clears, and the item is not canceled', async () => {
@@ -1487,7 +1489,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
fake.connection('disconnected');
fake.connection('connected');
- await vi.waitFor(() => expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, undefined));
+ await vi.waitFor(() => expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, expect.any(AbortSignal)));
expect(fake.handlerCount('queue_item_status_changed')).toBe(1);
readItemStatus.mockResolvedValueOnce({ status: 'completed' });
@@ -1517,7 +1519,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
// A clear that only removed other items leaves this one watched.
fake.emit('queue_cleared', clearedEvent);
- await vi.waitFor(() => expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, undefined));
+ await vi.waitFor(() => expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, expect.any(AbortSignal)));
expect(fake.handlerCount('queue_item_status_changed')).toBe(1);
// A pending item a clear deleted answers 404: there will never be a terminal event for it.
@@ -1555,7 +1557,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
fake.emit('queue_items_canceled', bulkCanceledEvent([4, 9]));
await expect(outcome).resolves.toBe('canceled');
- expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, undefined);
+ expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(9, expect.any(AbortSignal));
expect(fake.handlerCount('queue_items_canceled')).toBe(0);
// A bulk delete removes the row: the read answers 404.
@@ -1592,7 +1594,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
const submission = await pending;
await expect(submission.settled).rejects.toMatchObject({ reason: 'canceled' });
- expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(12, undefined);
+ expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(12, expect.any(AbortSignal));
});
it('defers a clear that arrives before the enqueue response until the item id is known', async () => {
@@ -1617,7 +1619,7 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
const submission = await pending;
await expect(submission.settled).rejects.toMatchObject({ reason: 'removed' });
- expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(12, undefined);
+ expect(readItemStatus).toHaveBeenCalledExactlyOnceWith(12, expect.any(AbortSignal));
});
it('reads the item at the reconcile interval: a finished item settles, an open one re-arms the read', async () => {
@@ -1676,3 +1678,301 @@ describe('submitUtilityGraph — fire, then watch settlement', () => {
expect(vi.getTimerCount()).toBe(0);
});
});
+
+describe('utility recovery lifetimes', () => {
+ const graph = { edges: [], id: 'utility-recovery', nodes: {} };
+
+ it.each(['submit', 'run'] as const)(
+ 'surfaces persistent status-read failure for %s without exhausting on event bursts',
+ async (api) => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const readItemStatus = vi.fn<UtilityItemStatusReader>().mockRejectedValue(new TypeError('backend down'));
+ const operation =
+ api === 'submit'
+ ? (await submitUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue, readItemStatus })).settled
+ : runUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue, readItemStatus });
+ const assertion = expect(operation).rejects.toMatchObject({
+ reason: 'reconcile',
+ message: expect.stringContaining('Backend work may still be running'),
+ });
+ for (let i = 0; i < 10; i += 1) {
+ fake.emit('queue_cleared', {});
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(1);
+ await vi.advanceTimersByTimeAsync(30_000);
+ await assertion;
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ );
+
+ it('surfaces repeated hung production status requests after their TimeoutError signals', async () => {
+ const realDelay = globalThis.setTimeout;
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const timeout = AbortSignal.timeout.bind(AbortSignal);
+ vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => timeout(Math.min(ms, 5)));
+ const failures: unknown[] = [];
+ const fetch = vi.fn(
+ (_input: RequestInfo | URL, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init!.signal!.addEventListener(
+ 'abort',
+ () => {
+ failures.push(init!.signal!.reason);
+ reject(init!.signal!.reason);
+ },
+ { once: true }
+ );
+ })
+ );
+ vi.stubGlobal('fetch', fetch);
+ const submission = await submitUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue });
+ const assertion = expect(submission.settled).rejects.toMatchObject({
+ reason: 'reconcile',
+ message: expect.stringContaining('Backend work may still be running'),
+ });
+ for (let i = 0; i < 3; i += 1) {
+ await vi.advanceTimersByTimeAsync(15_000);
+ await new Promise<void>((resolve) => {
+ realDelay(resolve, 20);
+ });
+ }
+ await assertion;
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(failures).toEqual(Array.from({ length: 3 }, () => expect.objectContaining({ name: 'TimeoutError' })));
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('resets consecutive read failures on healthy waiting states for jobs lasting hours', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const readItemStatus = vi.fn<UtilityItemStatusReader>();
+ let reads = 0;
+ readItemStatus.mockImplementation(() =>
+ ++reads % 3 === 0 ? Promise.resolve({ status: 'waiting' }) : Promise.reject(new TypeError('intermittent outage'))
+ );
+ const submission = await submitUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue, readItemStatus });
+ const settled = vi.fn();
+ void submission.settled.then(settled, settled);
+ await vi.advanceTimersByTimeAsync(4 * 60 * 60 * 1_000);
+ expect(settled).not.toHaveBeenCalled();
+ readItemStatus.mockResolvedValue({ status: 'completed' });
+ await vi.advanceTimersByTimeAsync(15_000);
+ await expect(submission.settled).resolves.toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('keeps a workflow waiting for a child active through production status reads and recovers its completion', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ let status = 'waiting';
+ const fetch = vi.fn(() => Promise.resolve(new Response(JSON.stringify({ item_id: 1, status }))));
+ vi.stubGlobal('fetch', fetch);
+ const submission = await submitUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue });
+ const onSettled = vi.fn();
+ void submission.settled.then(onSettled);
+
+ await vi.advanceTimersByTimeAsync(DEFAULT_UTILITY_RECONCILE_INTERVAL_MS * 2);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(onSettled).not.toHaveBeenCalled();
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(1);
+
+ status = 'completed';
+ await vi.advanceTimersByTimeAsync(DEFAULT_UTILITY_RECONCILE_INTERVAL_MS);
+ await expect(submission.settled).resolves.toBeUndefined();
+ expect(onSettled).toHaveBeenCalledOnce();
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('recovers a missing terminal event within one status interval and cleans up', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const readItemStatus = vi.fn<UtilityItemStatusReader>().mockResolvedValue({ status: 'completed' });
+ const reconcileCompletedOutput = vi.fn().mockResolvedValue({ imageName: 'recovered.png', width: 64, height: 64 });
+ const result = runUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: okEnqueue,
+ createId: () => UTIL_ID,
+ readItemStatus,
+ reconcileCompletedOutput,
+ });
+ await vi.advanceTimersByTimeAsync(DEFAULT_UTILITY_RECONCILE_INTERVAL_MS - 1);
+ expect(readItemStatus).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(result).resolves.toMatchObject({ imageName: 'recovered.png' });
+ expect(readItemStatus).toHaveBeenCalledTimes(1);
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('coalesces periodic and reconnect reads while a legitimate long queue wait stays open', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const controller = new AbortController();
+ const pending = createDeferred<{ status: 'pending' }>();
+ const readItemStatus = vi
+ .fn<UtilityItemStatusReader>()
+ .mockReturnValueOnce(pending.promise)
+ .mockResolvedValue({ status: 'pending' });
+ const submission = await submitUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: okEnqueue,
+ signal: controller.signal,
+ readItemStatus,
+ });
+ await vi.advanceTimersByTimeAsync(DEFAULT_UTILITY_RECONCILE_INTERVAL_MS);
+ fake.connection('disconnected');
+ fake.connection('connected');
+ expect(readItemStatus).toHaveBeenCalledTimes(1);
+ pending.resolve({ status: 'pending' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(readItemStatus).toHaveBeenCalledTimes(2);
+ readItemStatus.mockClear();
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(1);
+ expect(readItemStatus.mock.calls.length).toBeLessThanOrEqual(240);
+ controller.abort();
+ await expect(submission.settled).rejects.toMatchObject({ reason: 'aborted' });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reconciles an event received during a stale status read without concurrent reads', async () => {
+ const fake = createFakeHub();
+ const stale = createDeferred<{ status: 'pending' }>();
+ const readItemStatus = vi
+ .fn<UtilityItemStatusReader>()
+ .mockReturnValueOnce(stale.promise)
+ .mockResolvedValue({ status: 'completed' });
+ const submission = await submitUtilityGraph({ graph, hub: fake.hub, enqueue: okEnqueue, readItemStatus });
+ fake.connection('disconnected');
+ fake.connection('connected');
+ fake.emit('queue_cleared', { queue_id: 'default', timestamp: 1, user_id: null });
+ fake.connection('disconnected');
+ fake.connection('connected');
+ expect(readItemStatus).toHaveBeenCalledTimes(1);
+ stale.resolve({ status: 'pending' });
+ await expect(submission.settled).resolves.toBeUndefined();
+ expect(readItemStatus).toHaveBeenCalledTimes(2);
+ });
+
+ it('aborts outstanding status reads when a watch stops and ignores their late terminal result', async () => {
+ const fake = createFakeHub();
+ const controller = new AbortController();
+ const status = createDeferred<{ status: 'completed' }>();
+ const readItemStatus = vi.fn<UtilityItemStatusReader>().mockReturnValue(status.promise);
+ const submission = await submitUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: okEnqueue,
+ readItemStatus,
+ signal: controller.signal,
+ });
+ fake.connection('disconnected');
+ fake.connection('connected');
+ const requestSignal = readItemStatus.mock.calls[0]?.[1];
+ expect(requestSignal?.aborted).toBe(false);
+ controller.abort();
+ await expect(submission.settled).rejects.toMatchObject({ reason: 'aborted' });
+ expect(requestSignal?.aborted).toBe(true);
+ status.resolve({ status: 'completed' });
+ await nextMacrotask();
+ expect(readItemStatus).toHaveBeenCalledTimes(1);
+ expect(fake.connectionHandlerCount()).toBe(0);
+ });
+
+ it('aborts an outstanding output read when its account expires without retrying', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const output = createDeferred<null>();
+ const reconcileCompletedOutput = vi.fn().mockReturnValue(output.promise);
+ const result = runUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: okEnqueue,
+ createId: () => UTIL_ID,
+ reconcileCompletedOutput,
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ fake.emit('queue_item_status_changed', statusEvent('completed'));
+ await vi.advanceTimersByTimeAsync(0);
+ const requestSignal = reconcileCompletedOutput.mock.calls[0]?.[2] as AbortSignal;
+ expect(requestSignal.aborted).toBe(false);
+ accountLifecycle.activate('next-account');
+ await expect(result).rejects.toMatchObject({ reason: 'aborted' });
+ expect(requestSignal.aborted).toBe(true);
+ output.resolve(null);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(reconcileCompletedOutput).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reads authoritative completion before an explicit deadline can report timeout', async () => {
+ vi.useFakeTimers();
+ const fake = createFakeHub();
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ const result = runUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: okEnqueue,
+ timeoutMs: 1_000,
+ cancel,
+ readItemStatus: vi.fn().mockResolvedValue({ status: 'completed' }),
+ reconcileCompletedOutput: vi.fn().mockResolvedValue({ imageName: 'finished.png', width: 32, height: 32 }),
+ });
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expect(result).resolves.toMatchObject({ imageName: 'finished.png' });
+ expect(cancel).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('retains ids before acknowledging even when abort races acceptance', async () => {
+ const fake = createFakeHub();
+ const controller = new AbortController();
+ const admission = createDeferred<{ enqueued: number; itemIds: number[]; acknowledge: () => void }>();
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ const acknowledge = vi.fn();
+ const result = runUtilityGraph({
+ graph,
+ hub: fake.hub,
+ enqueue: () => admission.promise,
+ cancel,
+ signal: controller.signal,
+ });
+ controller.abort();
+ await expect(result).rejects.toMatchObject({ reason: 'aborted' });
+ admission.resolve({ enqueued: 1, itemIds: [71], acknowledge });
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith([71]));
+ expect(acknowledge).toHaveBeenCalledTimes(1);
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ });
+
+ it('does not start a deferred admission under a replacement account', async () => {
+ const fake = createFakeHub();
+ const enqueue = vi.fn(okEnqueue);
+ const result = runUtilityGraph({ graph, hub: fake.hub, enqueue });
+ accountLifecycle.activate('replacement-before-admission');
+ await expect(result).rejects.toMatchObject({ reason: 'aborted' });
+ await nextMacrotask();
+ expect(enqueue).not.toHaveBeenCalled();
+ });
+
+ it('never cancels old-account ids through the replacement account after a late admission', async () => {
+ const fake = createFakeHub();
+ const admission = createDeferred<{ enqueued: number; itemIds: number[] }>();
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ const result = runUtilityGraph({ graph, hub: fake.hub, enqueue: () => admission.promise, cancel });
+ await Promise.resolve();
+ accountLifecycle.activate('replacement');
+ await expect(result).rejects.toMatchObject({ reason: 'aborted' });
+ admission.resolve({ enqueued: 1, itemIds: [72] });
+ await nextMacrotask();
+ expect(cancel).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts
index 94fdab2080..65d7f1bb82 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts
@@ -15,10 +15,11 @@ import { buildUtilityQueueItemOrigin } from '@features/queue/data/events';
import { cancelQueueItems, getQueueItem } from '@features/queue/data/serverApi';
import { enqueueUtility } from '@features/queue/data/submissionApi';
import { createUuid } from '@platform/browser/randomUuid';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ApiError, getApiErrorMessage } from '@platform/transport/http';
-/** The default time a utility graph may run before it is abandoned. */
-export const DEFAULT_UTILITY_QUEUE_TIMEOUT_MS = 120_000;
+/** No universal deadline: model downloads, queue waits and calibration can legitimately take hours. */
+export const DEFAULT_UTILITY_QUEUE_TIMEOUT_MS = 0;
/** Bounded retries for transient completed-item reconciliation failures. */
export const DEFAULT_UTILITY_RECONCILE_RETRY_POLICY = { delayMs: 100, maxAttempts: 3 } as const;
@@ -47,8 +48,9 @@ export class UtilityQueueError extends Error {
export type UtilityEnqueue = (request: {
graph: QueueBackendGraph;
origin: string;
+ idempotencyKey: string;
prepend?: boolean;
-}) => Promise<{ itemIds: number[]; enqueued: number }>;
+}) => Promise<{ itemIds: number[]; enqueued: number; acknowledge?: () => void }>;
/** The cancellation seam: best-effort cancels accepted backend item ids. */
export type UtilityCancel = (itemIds: number[]) => Promise<void>;
@@ -77,7 +79,8 @@ const inspectUtilityEnqueueResult = (result: unknown) => {
/** Deterministically reads a completed queue item's target output. */
export type UtilityCompletedOutputReconciler = (
itemIds: number[],
- outputNodeId?: string
+ outputNodeId?: string,
+ signal?: AbortSignal
) => Promise<UtilityImageOutput | null>;
export interface UtilityReconcileRetryPolicy {
@@ -91,7 +94,7 @@ export type UtilityReconcileRetryScheduler = (callback: () => void, delayMs: num
export type UtilityReconcileErrorClassifier = (cause: unknown) => 'retry' | 'fail';
export const classifyUtilityReconcileError: UtilityReconcileErrorClassifier = (cause) => {
- if (cause instanceof TypeError) {
+ if (cause instanceof TypeError || (cause instanceof DOMException && cause.name === 'TimeoutError')) {
return 'retry';
}
if (cause instanceof ApiError) {
@@ -171,9 +174,23 @@ const extractImageOutput = (result: InvocationCompleteEvent['result'] | undefine
return { height: output.height, imageName: output.image.image_name, width: output.width };
};
-export const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler = async (itemIds, outputNodeId) => {
+export const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler = async (
+ itemIds,
+ outputNodeId,
+ signal
+) => {
+ const owner = captureAccountScope();
for (const itemId of itemIds) {
- const item = await getQueueItem(itemId);
+ if (!isAccountScopeCurrent(owner)) {
+ throw new Error('Utility account scope expired.');
+ }
+ const item = await getQueueItem(
+ itemId,
+ AbortSignal.any([owner.signal, AbortSignal.timeout(10_000), ...(signal ? [signal] : [])])
+ );
+ if (!isAccountScopeCurrent(owner)) {
+ throw new Error('Utility account scope expired.');
+ }
if (
!item ||
typeof item !== 'object' ||
@@ -209,11 +226,10 @@ export const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler =
};
/**
- * How long a submitted utility graph goes unheard from before its item is read again; the first run may download
- * models. An item still open at the read re-arms it, so the watch never gives up: it ends only on a terminal status,
- * the item's removal, or an abort.
+ * Active watches read every 15 seconds, coalescing overlapping reads. An open item re-arms the timer;
+ * the watch ends on a terminal status, removal, persistent read failure, or an abort.
*/
-export const DEFAULT_UTILITY_RECONCILE_INTERVAL_MS = 30 * 60_000;
+export const DEFAULT_UTILITY_RECONCILE_INTERVAL_MS = 15_000;
/**
* The outcome a terminal queue status means for a utility item: `null` for completion, the error for failure or
@@ -245,7 +261,17 @@ export type UtilityItemStatusReader = (
) => Promise<{ status: QueueItemStatusChangedEvent['status']; errorMessage?: unknown; errorType?: unknown }>;
const readUtilityItemStatus: UtilityItemStatusReader = async (itemId, signal) => {
- const item = await getQueueItem(itemId, signal);
+ const owner = captureAccountScope();
+ const requestSignal = AbortSignal.any([owner.signal, AbortSignal.timeout(10_000), ...(signal ? [signal] : [])]);
+ const item = await getQueueItem(itemId, requestSignal);
+ if (
+ !item ||
+ typeof item !== 'object' ||
+ item.item_id !== itemId ||
+ !['pending', 'in_progress', 'waiting', 'completed', 'failed', 'canceled'].includes(item.status)
+ ) {
+ throw new UtilityQueueError('reconcile', `Queue item ${itemId} returned malformed status data.`);
+ }
return { errorMessage: item.error_message, errorType: item.error_type, status: item.status };
};
@@ -273,21 +299,27 @@ const watchUtilityItems = ({
onOutcome,
origin,
readItemStatus,
- signal,
}: {
hub: UtilityHub;
onOutcome: (error: UtilityQueueError | null) => void;
origin: string;
readItemStatus: UtilityItemStatusReader;
- signal?: AbortSignal;
}): UtilityItemWatch => {
let detached = false;
let itemIds: number[] = [];
let readRequestedBeforeAccept = false;
+ let pendingRead: Promise<void> | undefined;
+ let readAgain = false;
+ const reads = new AbortController();
+ const readFailures = new Map<number, { count: number; firstAt: number }>();
+ let timer: ReturnType<typeof setTimeout> | undefined;
const detachers: Array<() => void> = [];
const detach = (): void => {
detached = true;
+ reads.abort();
+ readFailures.clear();
+ clearTimeout(timer);
for (const detachListener of detachers.splice(0)) {
try {
detachListener();
@@ -297,29 +329,77 @@ const watchUtilityItems = ({
}
};
- const read = async (): Promise<void> => {
+ const readItems = async (): Promise<void> => {
for (const itemId of itemIds) {
if (detached) {
return;
}
try {
- const item = await readItemStatus(itemId, signal);
+ const item = await readItemStatus(itemId, reads.signal);
+ readFailures.delete(itemId);
const outcome = detached ? undefined : toTerminalUtilityOutcome(item.status, item.errorMessage, item.errorType);
if (outcome !== undefined) {
onOutcome(outcome);
return;
}
} catch (cause) {
+ if (!detached && cause instanceof UtilityQueueError) {
+ onOutcome(cause);
+ return;
+ }
if (!detached && cause instanceof ApiError && cause.status === 404) {
// A queue clear or bulk delete removes a pending item without a terminal event.
onOutcome(new UtilityQueueError('removed', 'The utility graph item was removed from the queue.', cause));
return;
}
- // Unreadable now; the socket or a later read can still settle it.
+ if (!detached) {
+ const previous = readFailures.get(itemId);
+ const failures = { count: (previous?.count ?? 0) + 1, firstAt: previous?.firstAt ?? Date.now() };
+ readFailures.set(itemId, failures);
+ // Event bursts cannot exhaust the health budget before two polling intervals have elapsed.
+ if (failures.count >= 3 && Date.now() - failures.firstAt >= 2 * DEFAULT_UTILITY_RECONCILE_INTERVAL_MS) {
+ onOutcome(
+ new UtilityQueueError(
+ 'reconcile',
+ 'Utility status could not be read repeatedly. Backend work may still be running.',
+ cause
+ )
+ );
+ return;
+ }
+ }
}
}
};
+ const read = (): Promise<void> => {
+ readAgain = true;
+ if (!pendingRead) {
+ pendingRead = (async () => {
+ try {
+ do {
+ readAgain = false;
+ await readItems();
+ if (detached) {
+ return;
+ }
+ } while (readAgain);
+ } finally {
+ pendingRead = undefined;
+ }
+ })();
+ }
+ return pendingRead;
+ };
+ const armTimer = (): void => {
+ if (detached) {
+ return;
+ }
+ timer = setTimeout(() => {
+ void read().then(armTimer);
+ }, DEFAULT_UTILITY_RECONCILE_INTERVAL_MS);
+ };
+
const requestRead = (): void => {
if (itemIds.length === 0) {
// The event raced the enqueue; read the item once its id is known.
@@ -370,6 +450,7 @@ const watchUtilityItems = ({
return {
accept: (acceptedItemIds) => {
itemIds = acceptedItemIds;
+ armTimer();
if (readRequestedBeforeAccept) {
readRequestedBeforeAccept = false;
void read();
@@ -426,6 +507,7 @@ export interface UtilityGraphSubmission {
*/
export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Promise<UtilityGraphSubmission> => {
const { graph, hub, prepend, signal } = options;
+ const owner = captureAccountScope();
const enqueue = options.enqueue ?? enqueueUtility;
const cancel = options.cancel ?? cancelQueueItems;
const readItemStatus = options.readItemStatus ?? readUtilityItemStatus;
@@ -447,7 +529,6 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
// never hands it over at all; callers still observe the rejection through their own handlers.
settled.catch(() => {});
let isSettled = false;
- let timer: ReturnType<typeof setTimeout> | null = null;
const detachers: Array<() => void> = [];
const finish = (error: UtilityQueueError | null): void => {
@@ -455,10 +536,6 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
return;
}
isSettled = true;
- if (timer !== null) {
- clearTimeout(timer);
- timer = null;
- }
for (const detach of detachers) {
try {
detach();
@@ -484,7 +561,9 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
// Attach before enqueue so a very fast completion is not missed.
let watch!: UtilityItemWatch;
try {
- watch = watchUtilityItems({ hub, onOutcome: finish, origin, readItemStatus, signal });
+ owner.signal.addEventListener('abort', onAbort);
+ detachers.push(() => owner.signal.removeEventListener('abort', onAbort));
+ watch = watchUtilityItems({ hub, onOutcome: finish, origin, readItemStatus });
detachers.push(watch.detach);
if (signal) {
if (signal.aborted) {
@@ -501,20 +580,9 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
fail(new UtilityQueueError('setup', `Failed to attach utility graph listeners: ${detail}`, cause));
}
- /** An item still open at the periodic read re-arms it. */
- const armReconcileTimer = (): void => {
- if (isSettled) {
- return;
- }
- timer = setTimeout(() => {
- timer = null;
- void watch.read().then(armReconcileTimer);
- }, DEFAULT_UTILITY_RECONCILE_INTERVAL_MS);
- };
-
let result: Awaited<ReturnType<UtilityEnqueue>>;
try {
- result = await enqueue({ graph, origin, prepend });
+ result = await enqueue({ graph, origin, prepend, idempotencyKey: origin });
} catch (cause) {
fail(new UtilityQueueError('enqueue', getApiErrorMessage(cause, 'Failed to enqueue utility graph.'), cause));
}
@@ -523,13 +591,16 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
if (!inspected.result) {
if (inspected.itemIds.length > 0) {
// Whatever the backend did accept must not run unwatched; cancellation is best-effort.
- void cancel(inspected.itemIds).catch(() => {});
+ void Promise.resolve()
+ .then(() => (isAccountScopeCurrent(owner) ? cancel(inspected.itemIds) : undefined))
+ .catch(() => {});
+ result!.acknowledge?.();
}
fail(new UtilityQueueError('enqueue', 'The backend returned an inconsistent utility enqueue response.'));
}
const { itemIds } = inspected.result!;
watch.accept(itemIds);
- armReconcileTimer();
+ result!.acknowledge?.();
return { itemIds, origin, settled };
};
@@ -540,6 +611,7 @@ export const submitUtilityGraph = async (options: SubmitUtilityGraphOptions): Pr
*/
export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<UtilityGraphResult> => {
const { graph, hub, outputNodeId, signal } = options;
+ const owner = captureAccountScope();
const enqueue = options.enqueue ?? enqueueUtility;
const cancel = options.cancel ?? cancelQueueItems;
const readItemStatus = options.readItemStatus ?? readUtilityItemStatus;
@@ -565,6 +637,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
return new Promise<UtilityGraphResult>((resolve, reject) => {
let settled = false;
+ const outputReads = new AbortController();
+ const outputSignal = AbortSignal.any([owner.signal, outputReads.signal]);
let capturedOutput: { height: number; imageName: string; width: number } | null = null;
let cancellationRequested = false;
let cancellationStarted = false;
@@ -579,6 +653,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
const cancelAcceptedItems = (): void => {
if (
+ !isAccountScopeCurrent(owner) ||
!cancellationRequested ||
cancellationStarted ||
enqueueResult === null ||
@@ -591,7 +666,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
cancellationStarted = true;
const itemIds = [...enqueueResult.itemIds];
void Promise.resolve()
- .then(() => cancel(itemIds))
+ .then(() => (isAccountScopeCurrent(owner) ? cancel(itemIds) : undefined))
.catch(() => {
// Cancellation is best-effort and must never mask the original settle reason.
});
@@ -603,6 +678,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
};
const cleanup = (): void => {
+ outputReads.abort();
if (timer !== null) {
clearTimeout(timer);
timer = null;
@@ -687,7 +763,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
}
};
void Promise.resolve()
- .then(() => reconcileCompletedOutput(reconciliationItemIds, outputNodeId))
+ .then(() => (settled ? null : reconcileCompletedOutput(reconciliationItemIds, outputNodeId, outputSignal)))
.then((output) => {
reconciliationInFlight = false;
if (settled) {
@@ -769,6 +845,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
})
);
+ owner.signal.addEventListener('abort', onAbort);
+ detachers.push(() => owner.signal.removeEventListener('abort', onAbort));
watch = watchUtilityItems({
hub,
onOutcome: (error) => {
@@ -781,7 +859,6 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
},
origin,
readItemStatus,
- signal,
});
detachers.push(watch.detach);
} catch (cause) {
@@ -809,15 +886,25 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
if (settled) {
return;
}
- requestBackendCancellation();
- settleReject(new UtilityQueueError('timeout', `The utility graph timed out after ${timeoutMs}ms.`));
+ void watch?.read().then(() => {
+ if (settled || completionReceived) {
+ return;
+ }
+ requestBackendCancellation();
+ settleReject(new UtilityQueueError('timeout', `The utility graph timed out after ${timeoutMs}ms.`));
+ });
}, timeoutMs);
}
// Enqueue last. A synchronous listener callback could already have fired by
// the time this resolves; `settled` guards against a late enqueue result.
void Promise.resolve()
- .then(() => enqueue({ graph, origin }))
+ .then(() => {
+ if (!isAccountScopeCurrent(owner)) {
+ throw new UtilityQueueError('aborted', 'The utility graph account scope expired.');
+ }
+ return enqueue({ graph, origin, idempotencyKey: origin });
+ })
.then((result) => {
const inspected = inspectUtilityEnqueueResult(result);
const validResult = inspected.result;
@@ -825,6 +912,9 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
const knownItemIds = inspected.itemIds;
enqueueResult = { enqueued: knownItemIds.length, itemIds: knownItemIds };
requestBackendCancellation();
+ if (knownItemIds.length > 0) {
+ result.acknowledge?.();
+ }
settleReject(
new UtilityQueueError('enqueue', 'The backend returned an inconsistent utility enqueue response.')
);
@@ -833,6 +923,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
enqueueResult = validResult;
watch?.accept(validResult.itemIds);
cancelAcceptedItems();
+ result.acknowledge?.();
if (!settled) {
reconcileCompletion();
}
diff --git a/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts b/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts
new file mode 100644
index 0000000000..a5932a0a0b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { QueueBackendPort, QueueItemReadModel } from './core/types';
+import type { QueueHistoryCommands, QueueHistoryPort } from './runtime';
+
+import { buildQueueItemOrigin } from './data/events';
+import { createQueueRuntime } from './runtime';
+import { runUtilityGraph } from './runtime/utilityGraph';
+
+const disposers: Array<() => Promise<void>> = [];
+afterEach(async () => {
+ await Promise.all(disposers.splice(0).map((dispose) => dispose()));
+});
+
+type Candidate = ReturnType<QueueHistoryPort['listStagedResults']>[number];
+
+/** Separate browser-runtime snapshots share only the server's account-wide delivery state. */
+const openCanvasRuntime = (claimItemDelivery: QueueBackendPort['claimItemDelivery'], candidates: Candidate[] = []) => {
+ const handlers = new Map<string, Set<(event: never) => void>>();
+ const historyListeners = new Set<() => void>();
+ const rerun: QueueItemReadModel = {
+ batchId: 'retry-batch',
+ createdAt: '2026-07-17T00:00:00Z',
+ destination: 'canvas',
+ id: 99,
+ origin: buildQueueItemOrigin('retired-run', 'project'),
+ resultImageNames: ['recovered.png'],
+ retriedFromItemId: 41,
+ sessionId: 'retry-session',
+ status: 'completed',
+ updatedAt: '2026-07-17T00:00:00Z',
+ };
+ const commands: QueueHistoryCommands = {
+ markBackendCancelled: vi.fn(),
+ markBackendSubmitted: vi.fn(),
+ recordError: vi.fn(),
+ recordSubmissionRetry: vi.fn(),
+ refreshBackendData: vi.fn(),
+ refreshBoardDestinations: vi.fn(),
+ reopenForRetry: vi.fn(),
+ restoreFromJournal: vi.fn(),
+ routePartialResults: vi.fn(),
+ routeResults: vi.fn(),
+ setCancellationPending: vi.fn(),
+ setConnectionStatus: vi.fn(),
+ setLocalRecoveryState: vi.fn(),
+ setStatus: vi.fn(),
+ stageRetriedCanvasResults: vi.fn(({ backendItemId, projectId, queueItemId }) => {
+ candidates.push({ backendItemId, projectId, queueItemId });
+ historyListeners.forEach((listener) => listener());
+ }),
+ };
+ const backend: QueueBackendPort = {
+ cancelBatch: vi.fn(),
+ cancelCurrentItem: vi.fn(),
+ cancelItem: vi.fn(),
+ cancelQueueItems: vi.fn(),
+ cancelQueueItemsByBatchIds: vi.fn(),
+ cancelScopedItems: vi.fn(),
+ claimItemDelivery,
+ clearFailedItems: vi.fn(),
+ clearFinishedItems: vi.fn(),
+ clearItems: vi.fn(),
+ emit: vi.fn(),
+ enqueueGenerate: vi.fn(),
+ enqueueWorkflow: vi.fn(),
+ getItem: vi.fn(),
+ getResultImages: () =>
+ Promise.resolve([
+ {
+ imageName: 'recovered.png',
+ width: 64,
+ height: 48,
+ imageUrl: '/recovered.png',
+ thumbnailUrl: '/recovered.png',
+ queuedAt: '2026-07-17T00:00:00Z',
+ sourceQueueItemId: 'retired-run',
+ },
+ ]),
+ getResultVideoNames: () => Promise.resolve([]),
+ getResultVideos: () => Promise.resolve([]),
+ listItems: () => Promise.resolve([]),
+ on: (event, handler) => {
+ const listeners = handlers.get(event) ?? new Set();
+ listeners.add(handler as (event: never) => void);
+ handlers.set(event, listeners);
+ return () => listeners.delete(handler as (event: never) => void);
+ },
+ onConnectionChange: (listener) => {
+ listener('connected');
+ return () => undefined;
+ },
+ pauseProcessor: vi.fn(),
+ readCurrent: vi.fn(),
+ readItemDetail: vi.fn(),
+ readItemIds: vi.fn(),
+ readItemsById: vi.fn((ids) => Promise.resolve(ids.includes(rerun.id) ? [rerun] : [])),
+ readNext: vi.fn(),
+ readStatus: vi.fn(),
+ resumeProcessor: vi.fn(),
+ retryItems: vi.fn(),
+ };
+ const runtime = createQueueRuntime({
+ backend,
+ destinations: { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() },
+ ensureTemplatesLoaded: vi.fn(),
+ history: {
+ commands,
+ getSnapshot: () => ({
+ connectionStatus: 'connected',
+ isHydrated: true,
+ projects: [{ id: 'project', queue: { items: [] } }],
+ }),
+ listStagedResults: () => candidates,
+ subscribe: (listener) => {
+ historyListeners.add(listener);
+ return () => historyListeners.delete(listener);
+ },
+ },
+ modelLoads: { completed: vi.fn(), reset: vi.fn(), started: vi.fn() },
+ nodeExecution: {
+ clearAll: vi.fn(),
+ completed: vi.fn(),
+ failed: vi.fn(),
+ progress: vi.fn(),
+ setOrigin: vi.fn(),
+ settleRunning: vi.fn(),
+ started: vi.fn(),
+ },
+ });
+ disposers.push(runtime.dispose);
+ runtime.start();
+ return {
+ candidates,
+ commands,
+ dispose: runtime.dispose,
+ emitRerun: () => {
+ handlers.get('queue_items_retried')?.forEach((handler) =>
+ handler({
+ queue_id: 'default',
+ retried_item_ids: [41],
+ retried_item_ids_by_user: {},
+ retried_items: [{ item_id: 99, source_item_id: 41 }],
+ timestamp: 0,
+ user_ids: [],
+ } as never)
+ );
+ handlers.get('queue_item_status_changed')?.forEach((handler) =>
+ handler({
+ created_at: '2026-07-17T00:00:00Z',
+ destination: 'canvas',
+ item_id: 99,
+ origin: buildQueueItemOrigin('retired-run', 'project'),
+ status: 'completed',
+ } as never)
+ );
+ },
+ };
+};
+
+describe('browser queue recovery', () => {
+ it('reads authoritative completion before an explicit deadline and detaches native listeners', async () => {
+ const listeners = new Set<unknown>();
+ const cancel = vi.fn();
+ const readItemStatus = vi.fn(() => Promise.resolve({ status: 'completed' as const }));
+ const abort = new AbortController();
+ const result = await runUtilityGraph({
+ cancel,
+ enqueue: () => Promise.resolve({ enqueued: 1, itemIds: [1] }),
+ graph: { edges: [], id: 'utility', nodes: {} },
+ hub: {
+ on: (_event, listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ },
+ readItemStatus,
+ reconcileCompletedOutput: () => Promise.resolve({ height: 48, imageName: 'recovered.png', width: 64 }),
+ signal: abort.signal,
+ timeoutMs: 10,
+ });
+ expect(result).toMatchObject({ imageName: 'recovered.png', height: 48, width: 64 });
+ expect(readItemStatus).toHaveBeenCalledTimes(1);
+ expect(listeners.size).toBe(0);
+ abort.abort();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ expect(cancel).not.toHaveBeenCalled();
+ });
+
+ it('retains staging across a lost confirmation and prevents a stale second runtime from staging again', async () => {
+ let delivered = false;
+ let claimant: string | undefined;
+ let confirmations = 0;
+ const claim: QueueBackendPort['claimItemDelivery'] = (_id, action, requester) => {
+ if (action === 'confirm') {
+ delivered = true;
+ if (++confirmations === 1) {
+ return Promise.reject(new TypeError('server confirmed but its response was lost'));
+ }
+ return Promise.resolve({ kind: 'delivered' });
+ }
+ if (delivered) {
+ return Promise.resolve({ kind: 'delivered' });
+ }
+ if (action === 'release') {
+ claimant = undefined;
+ return Promise.resolve({ kind: 'released' });
+ }
+ if (claimant && claimant !== requester) {
+ return Promise.resolve({ kind: 'held', retryInMs: 10 });
+ }
+ claimant = requester;
+ return Promise.resolve({ kind: 'claimed' });
+ };
+ const first = openCanvasRuntime(claim);
+ first.emitRerun();
+ await vi.waitFor(() =>
+ expect(first.candidates).toEqual([{ backendItemId: 99, projectId: 'project', queueItemId: 'retired-run' }])
+ );
+ await vi.waitFor(() => expect(confirmations).toBe(1));
+ const stale = openCanvasRuntime(claim);
+ stale.emitRerun();
+ await vi.waitFor(() => expect(confirmations).toBe(2), { timeout: 3_000 });
+ expect(stale.candidates).toEqual([]);
+ expect(first.commands.stageRetriedCanvasResults).toHaveBeenCalledTimes(1);
+
+ await first.dispose();
+ const restored = openCanvasRuntime(claim, structuredClone(first.candidates));
+ await vi.waitFor(() => expect(confirmations).toBe(3));
+ expect(restored.candidates).toEqual(first.candidates);
+ expect(restored.commands.stageRetriedCanvasResults).not.toHaveBeenCalled();
+ expect(restored.commands.recordError).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 2d72e65eee..468111efbd 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -260,6 +260,7 @@ const WORKBENCH_RUNTIME_SHARED_MODULES = [
'/features/queue/runtime.ts',
'/features/queue/runtime/cancelRequests.ts',
'/features/queue/runtime/coordinator.ts',
+ '/features/queue/runtime/deliveryClaims.ts',
'/features/queue/runtime/receiptAcknowledgements.ts',
'/features/queue/ui/useDeviceLabel.ts',
'/features/upscale/core/settings.ts',