Skip to content

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

refactor(webv2): put the optimistic-rollback compare-and-swap in one module

joshistoastb3510a82233a
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index d3e02166a3..126311ccc2 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,10 +2,10 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 832112,
+ "brotliBytes": 832098,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 831924,
+ "gzipBytes": 831918,
"imageRawBytes": 156376,
"initialRawBytes": 1933595,
"largestAssetRawBytes": 746305,
@@ -280,10 +280,10 @@
]
},
"limits": {
- "brotliBytes": 840434,
+ "brotliBytes": 840419,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 840244,
+ "gzipBytes": 840238,
"imageRawBytes": 157940,
"initialRawBytes": 1952931,
"largestAssetRawBytes": 753769,
@@ -298,12 +298,12 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1029111,
+ "brotliBytes": 1029170,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1026451,
+ "gzipBytes": 1026506,
"imageRawBytes": 156376,
- "initialRawBytes": 2524311,
+ "initialRawBytes": 2524449,
"largestAssetRawBytes": 746305,
"otherAssetRawBytes": 0,
"ownedRawBytes": 111374,
@@ -602,6 +602,7 @@
"source:src/platform/react/useZodForm.ts",
"source:src/platform/search/dateTokens.ts",
"source:src/platform/state/accountLifecycle.ts",
+ "source:src/platform/state/compareAndSwapRollback.ts",
"source:src/platform/state/externalStore.ts",
"source:src/platform/state/externalStoreCore.ts",
"source:src/platform/state/projectedExternalStore.ts",
@@ -827,12 +828,12 @@
]
},
"limits": {
- "brotliBytes": 1039403,
+ "brotliBytes": 1039462,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1036716,
+ "gzipBytes": 1036772,
"imageRawBytes": 157940,
- "initialRawBytes": 2549555,
+ "initialRawBytes": 2549694,
"largestAssetRawBytes": 753769,
"otherAssetRawBytes": 0,
"ownedRawBytes": 111374,
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index d060a56001..3c55a00bc6 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,11 +25,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119.10000000149012,
+ "domContentLoadedMedianMs": 116.10000000149012,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 119.10000000149012,
- "longestTaskMaxMs": 73,
+ "loadMedianMs": 116.10000000149012,
+ "longestTaskMaxMs": 70,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -56,7 +56,7 @@
"scriptRequestCount": 32,
"totalRawBytes": 1784521
},
- "routeReadyMedianMs": 260.8999999985099,
+ "routeReadyMedianMs": 250.79999999701977,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -83,11 +83,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 117.89999999850988,
+ "domContentLoadedMedianMs": 115,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 117.89999999850988,
- "longestTaskMaxMs": 72,
+ "loadMedianMs": 115.10000000149012,
+ "longestTaskMaxMs": 91,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -114,7 +114,7 @@
"scriptRequestCount": 32,
"totalRawBytes": 1784521
},
- "routeReadyMedianMs": 279.6000000014901,
+ "routeReadyMedianMs": 266.20000000298023,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -141,13 +141,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119,
+ "domContentLoadedMedianMs": 112.29999999701977,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 119.10000000149012,
- "longestTaskMaxMs": 96,
+ "loadMedianMs": 112.29999999701977,
+ "longestTaskMaxMs": 93,
"owner": "workbench",
- "projectSwitchMedianMs": 36.899999998509884,
+ "projectSwitchMedianMs": 32.20000000298023,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -157,9 +157,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -168,11 +168,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 647.2000000029802,
+ "routeReadyMedianMs": 627.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -199,13 +199,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 115.39999999850988,
+ "domContentLoadedMedianMs": 115.79999999701977,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 115.39999999850988,
- "longestTaskMaxMs": 126,
+ "loadMedianMs": 115.79999999701977,
+ "longestTaskMaxMs": 106,
"owner": "workbench",
- "projectSwitchMedianMs": 51.30000000447035,
+ "projectSwitchMedianMs": 48.899999998509884,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -215,9 +215,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -226,11 +226,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 719.7999999970198,
+ "routeReadyMedianMs": 680.1000000014901,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -257,11 +257,11 @@
"scriptRequestCount": 5,
"totalRawBytes": 286746
},
- "domContentLoadedMedianMs": 111.5,
+ "domContentLoadedMedianMs": 108.89999999850988,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 63.80000000447035,
- "loadMedianMs": 111.5,
- "longestTaskMaxMs": 92,
+ "layoutSwitchMedianMs": 59.5,
+ "loadMedianMs": 108.89999999850988,
+ "longestTaskMaxMs": 93,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -273,9 +273,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 118,
- "scriptRawBytes": 3650869,
+ "scriptRawBytes": 3650023,
"scriptRequestCount": 112,
- "totalRawBytes": 3984419
+ "totalRawBytes": 3983573
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -284,11 +284,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 118,
- "scriptRawBytes": 3687378,
+ "scriptRawBytes": 3686524,
"scriptRequestCount": 112,
- "totalRawBytes": 4024264
+ "totalRawBytes": 4023409
},
- "routeReadyMedianMs": 1081.7999999970198,
+ "routeReadyMedianMs": 1077.2999999970198,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -315,11 +315,11 @@
"scriptRequestCount": 5,
"totalRawBytes": 286746
},
- "domContentLoadedMedianMs": 108.5,
+ "domContentLoadedMedianMs": 115.29999999701977,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 184.39999999850988,
- "loadMedianMs": 108.5,
- "longestTaskMaxMs": 363,
+ "layoutSwitchMedianMs": 185.10000000149012,
+ "loadMedianMs": 115.29999999701977,
+ "longestTaskMaxMs": 380,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -331,9 +331,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 118,
- "scriptRawBytes": 3650869,
+ "scriptRawBytes": 3650023,
"scriptRequestCount": 112,
- "totalRawBytes": 3984419
+ "totalRawBytes": 3983573
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -342,11 +342,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 118,
- "scriptRawBytes": 3687378,
+ "scriptRawBytes": 3686524,
"scriptRequestCount": 112,
- "totalRawBytes": 4024264
+ "totalRawBytes": 4023409
},
- "routeReadyMedianMs": 1226.2000000029802,
+ "routeReadyMedianMs": 1242,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -373,11 +373,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 111,
+ "domContentLoadedMedianMs": 113.10000000149012,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 57.5,
- "loadMedianMs": 111,
- "longestTaskMaxMs": 94,
+ "layoutSwitchMedianMs": 58.100000001490116,
+ "loadMedianMs": 113.10000000149012,
+ "longestTaskMaxMs": 86,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -389,9 +389,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -400,11 +400,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 1051,
+ "routeReadyMedianMs": 1054.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -431,11 +431,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 115.10000000149012,
+ "domContentLoadedMedianMs": 114.40000000596046,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 106.5,
- "loadMedianMs": 115.10000000149012,
- "longestTaskMaxMs": 353,
+ "layoutSwitchMedianMs": 109.5,
+ "loadMedianMs": 114.40000000596046,
+ "longestTaskMaxMs": 379,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -447,9 +447,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -458,11 +458,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 1154.2999999970198,
+ "routeReadyMedianMs": 1160.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -489,11 +489,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 108.60000000149012,
+ "domContentLoadedMedianMs": 114.69999999552965,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 22.700000002980232,
- "loadMedianMs": 108.69999999552965,
- "longestTaskMaxMs": 97,
+ "layoutSwitchMedianMs": 23.799999997019768,
+ "loadMedianMs": 114.69999999552965,
+ "longestTaskMaxMs": 89,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -505,9 +505,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -516,11 +516,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 1301.7999999970198,
+ "routeReadyMedianMs": 1316.7000000029802,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -547,11 +547,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 108.20000000298023,
+ "domContentLoadedMedianMs": 115.39999999850988,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 89.60000000149012,
- "loadMedianMs": 108.20000000298023,
- "longestTaskMaxMs": 150,
+ "layoutSwitchMedianMs": 96.19999999552965,
+ "loadMedianMs": 115.39999999850988,
+ "longestTaskMaxMs": 165,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -563,9 +563,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 135938,
"requestCount": 113,
- "scriptRawBytes": 3366963,
+ "scriptRawBytes": 3366117,
"scriptRequestCount": 107,
- "totalRawBytes": 3700513
+ "totalRawBytes": 3699667
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -574,11 +574,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137298,
"requestCount": 113,
- "scriptRawBytes": 3400633,
+ "scriptRawBytes": 3399779,
"scriptRequestCount": 107,
- "totalRawBytes": 3737519
+ "totalRawBytes": 3736664
},
- "routeReadyMedianMs": 1427.8999999985099,
+ "routeReadyMedianMs": 1468.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1376,6 +1376,7 @@
"source:src/features/workflow/ui/linear/WorkflowJsonTab.tsx",
"source:src/features/workflow/ui/linear/WorkflowLinearPanel.tsx",
"source:src/features/workflow/ui/linear/formBuilderDnd.ts",
+ "source:src/features/workflow/ui/linear/formElementMeta.ts",
"source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts",
"source:src/features/workflow/ui/useProjectGraphCommands.ts",
"source:src/features/workflow/ui/workflowTransfer.ts",
@@ -1397,6 +1398,7 @@
"source:src/platform/react/useZodForm.ts",
"source:src/platform/search/dateTokens.ts",
"source:src/platform/state/accountLifecycle.ts",
+ "source:src/platform/state/compareAndSwapRollback.ts",
"source:src/platform/state/externalStore.ts",
"source:src/platform/state/externalStoreCore.ts",
"source:src/platform/state/projectedExternalStore.ts",
@@ -2324,6 +2326,7 @@
"source:src/features/workflow/ui/linear/WorkflowJsonTab.tsx",
"source:src/features/workflow/ui/linear/WorkflowLinearPanel.tsx",
"source:src/features/workflow/ui/linear/formBuilderDnd.ts",
+ "source:src/features/workflow/ui/linear/formElementMeta.ts",
"source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts",
"source:src/features/workflow/ui/useProjectGraphCommands.ts",
"source:src/features/workflow/ui/workflowTransfer.ts",
@@ -2345,6 +2348,7 @@
"source:src/platform/react/useZodForm.ts",
"source:src/platform/search/dateTokens.ts",
"source:src/platform/state/accountLifecycle.ts",
+ "source:src/platform/state/compareAndSwapRollback.ts",
"source:src/platform/state/externalStore.ts",
"source:src/platform/state/externalStoreCore.ts",
"source:src/platform/state/projectedExternalStore.ts",
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index ecd8e61b08..1603b9b3cb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -11,6 +11,7 @@ import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import { toGalleryItemKey } from '@features/gallery/core/items';
import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { rollBackUnclaimedEntries } from '@platform/state/compareAndSwapRollback';
import { hashKey } from '@tanstack/react-query';
import { ALL_READABLE_BOARDS_ID, isDateBoardId } from './backend';
@@ -184,13 +185,12 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa
}
}
- return () => {
- for (const { after, before, queryKey } of rollbackEntries) {
- if (client.getQueryData(queryKey) === after) {
- client.setQueryData(queryKey, before);
- }
- }
- };
+ return () =>
+ rollBackUnclaimedEntries(
+ rollbackEntries,
+ (entry) => client.getQueryData<InfiniteData<GalleryItemsPage, number>>(entry.queryKey),
+ (entry) => client.setQueryData(entry.queryKey, entry.before)
+ );
};
/**
@@ -318,13 +318,12 @@ export const patchGalleryBoardCaches = (
}
}
- return () => {
- for (const { after, before, queryKey } of rollbackEntries) {
- if (client.getQueryData(queryKey) === after) {
- client.setQueryData(queryKey, before);
- }
- }
- };
+ return () =>
+ rollBackUnclaimedEntries(
+ rollbackEntries,
+ (entry) => client.getQueryData<InfiniteData<GalleryItemsPage, number>>(entry.queryKey),
+ (entry) => client.setQueryData(entry.queryKey, entry.before)
+ );
};
const runGalleryInvalidation = async (
diff --git a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts
new file mode 100644
index 0000000000..e9910dff30
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+
+import { isSlotUnclaimed, rollBackUnclaimedEntries, selectUnclaimedEntries } from './compareAndSwapRollback';
+
+describe('isSlotUnclaimed', () => {
+ it('is true only while the slot still holds what we painted', () => {
+ const painted = { id: 'painted' };
+
+ expect(isSlotUnclaimed(painted, painted)).toBe(true);
+ expect(isSlotUnclaimed({ id: 'painted' }, painted)).toBe(false);
+ expect(isSlotUnclaimed({ id: 'newer' }, painted)).toBe(false);
+ });
+
+ it('rejects an unknown slot by default', () => {
+ // `undefined` may be a value a newer writer set, so reverting over it
+ // would be the data loss the rule exists to prevent.
+ expect(isSlotUnclaimed(undefined, 'painted')).toBe(false);
+ });
+
+ it('accepts an unknown slot only when the caller says unknown means absent', () => {
+ expect(isSlotUnclaimed(undefined, 'painted', { treatUnknownAsUnclaimed: true })).toBe(true);
+ });
+
+ it('still rejects a slot a newer writer claimed, even when unknown is allowed', () => {
+ expect(isSlotUnclaimed('newer', 'painted', { treatUnknownAsUnclaimed: true })).toBe(false);
+ });
+});
+
+describe('selectUnclaimedEntries', () => {
+ const entries = [
+ { after: 'painted-a', before: 'original-a', slot: 'a' },
+ { after: 'painted-b', before: 'original-b', slot: 'b' },
+ ];
+
+ it('drops entries a newer writer has taken over', () => {
+ const current: Record<string, string> = { a: 'painted-a', b: 'someone-else' };
+
+ expect(selectUnclaimedEntries(entries, (entry) => current[entry.slot])).toEqual([entries[0]]);
+ });
+
+ it('keeps every entry when nothing else wrote', () => {
+ const current: Record<string, string> = { a: 'painted-a', b: 'painted-b' };
+
+ expect(selectUnclaimedEntries(entries, (entry) => current[entry.slot])).toEqual(entries);
+ });
+});
+
+describe('rollBackUnclaimedEntries', () => {
+ it('restores only the slots still holding our own write', () => {
+ const slots: Record<string, string> = { a: 'painted-a', b: 'someone-else' };
+
+ rollBackUnclaimedEntries(
+ [
+ { after: 'painted-a', before: 'original-a', slot: 'a' },
+ { after: 'painted-b', before: 'original-b', slot: 'b' },
+ ],
+ (entry) => slots[entry.slot],
+ (entry) => {
+ slots[entry.slot] = entry.before;
+ }
+ );
+
+ expect(slots).toEqual({ a: 'original-a', b: 'someone-else' });
+ });
+
+ it('does nothing when every slot has moved on', () => {
+ const slots: Record<string, string> = { a: 'newer' };
+
+ rollBackUnclaimedEntries(
+ [{ after: 'painted-a', before: 'original-a', slot: 'a' }],
+ (entry) => slots[entry.slot],
+ (entry) => {
+ slots[entry.slot] = entry.before;
+ }
+ );
+
+ expect(slots).toEqual({ a: 'newer' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts
new file mode 100644
index 0000000000..5f3ab3e7f2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts
@@ -0,0 +1,65 @@
+/**
+ * The one rule for undoing an optimistic write: put a slot back only if it
+ * still holds exactly what this mutation painted there.
+ *
+ * An optimistic mutation writes a value, the server rejects it, and the
+ * rollback wants the old value back. Between those two moments anything may
+ * have written to the same slot — a generation completing, a refetch landing,
+ * the person re-selecting, a second mutation on the same item. Restoring
+ * unconditionally would throw that newer work away, and the failure is silent:
+ * the UI shows stale state that no longer corresponds to anything.
+ *
+ * So the restore is a compare-and-swap. `after` is what we painted; if the slot
+ * still reads as `after`, we are the last writer and may safely revert. If it
+ * reads as anything else, someone newer owns it and we leave it alone.
+ *
+ * This lived in three separate places — the gallery query cache, the per-project
+ * widget-value snapshot, and the per-item board/starred rollback — each with its
+ * own copy of the check and a comment pointing at the other two. One wrong copy
+ * is a data-loss bug, so there is one copy.
+ */
+
+/** What a rollback needs to know about a slot: what was there, and what we put there. */
+export interface CompareAndSwapEntry<Value> {
+ /** The value this mutation painted. The slot must still hold it to be revertible. */
+ after: Value;
+ /** The value to restore. */
+ before: Value;
+}
+
+export interface CompareAndSwapOptions {
+ /**
+ * Treat a slot that reads `undefined` as revertible.
+ *
+ * Correct where `undefined` means "no local copy of this exists" rather than
+ * "someone cleared it" — a per-item lookup that simply misses, for instance.
+ * Wrong where `undefined` is a value another writer could have set.
+ */
+ treatUnknownAsUnclaimed?: boolean;
+}
+
+/** Whether `current` still reads as the value this mutation painted. */
+export const isSlotUnclaimed = <Value>(
+ current: Value | undefined,
+ painted: Value,
+ { treatUnknownAsUnclaimed = false }: CompareAndSwapOptions = {}
+): boolean => current === painted || (treatUnknownAsUnclaimed && current === undefined);
+
+/** The subset of `entries` whose slots no newer writer has claimed. */
+export const selectUnclaimedEntries = <Value, Entry extends CompareAndSwapEntry<Value>>(
+ entries: readonly Entry[],
+ readCurrent: (entry: Entry) => Value | undefined,
+ options?: CompareAndSwapOptions
+): Entry[] => entries.filter((entry) => isSlotUnclaimed(readCurrent(entry), entry.after, options));
+
+/** Restore every entry whose slot is still ours, and skip the rest. */
+export const rollBackUnclaimedEntries = <Value, Entry extends CompareAndSwapEntry<Value>>(
+ entries: readonly Entry[],
+ readCurrent: (entry: Entry) => Value | undefined,
+ restore: (entry: Entry) => void,
+ options?: CompareAndSwapOptions
+): void => {
+ for (const entry of selectUnclaimedEntries(entries, readCurrent, options)) {
+ restore(entry);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
index d22f16d43b..1ea9d30929 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
@@ -14,6 +14,7 @@ import {
getGalleryCompareImage,
getSelectedGalleryItemFromValues,
} from '@features/gallery/contracts';
+import { isSlotUnclaimed, selectUnclaimedEntries } from '@platform/state/compareAndSwapRollback';
import { getProjectWidgetValues } from '@workbench/widgetState';
/**
@@ -112,13 +113,16 @@ export interface GalleryWidgetRestorePatch {
}
/**
- * Selects which snapshot entries are still safe to restore: a key restores
- * only if its current value is still reference-equal to what our own
- * mutation left it at — mirroring `patchGalleryItemCaches`'s rollback rule
- * (`if (client.getQueryData(queryKey) === after)`). A key something else
- * wrote to since (a generation completing, a user re-selecting) is left
- * alone rather than clobbered. Entries for the same project+widget are
- * merged into a single patch.
+ * Selects which snapshot entries are still safe to restore, under the shared
+ * compare-and-swap rule (`@platform/state/compareAndSwapRollback`): a key
+ * restores only if its current value is still what our own mutation left it
+ * at. A key something else wrote to since (a generation completing, a user
+ * re-selecting) is left alone rather than clobbered. Entries for the same
+ * project+widget are merged into a single patch.
+ *
+ * A project that has since disappeared has no slot to restore, so its entries
+ * drop out before the compare rather than resolving to a bare `undefined` that
+ * the check could mistake for a match.
*/
export const selectRestorableGalleryWidgetPatches = (
entries: readonly GalleryWidgetKeySnapshotEntry[],
@@ -126,20 +130,12 @@ export const selectRestorableGalleryWidgetPatches = (
): GalleryWidgetRestorePatch[] => {
const projectsById = new Map(projects.map((project) => [project.id, project]));
const patchesByGroup = new Map<string, GalleryWidgetRestorePatch>();
+ const liveEntries = entries.filter((entry) => projectsById.has(entry.projectId));
- for (const entry of entries) {
- const project = projectsById.get(entry.projectId);
-
- if (!project) {
- continue;
- }
-
- const currentValue = getProjectWidgetValues(project, entry.widgetId)[entry.key];
-
- if (currentValue !== entry.after) {
- continue;
- }
-
+ for (const entry of selectUnclaimedEntries(
+ liveEntries,
+ (candidate) => getProjectWidgetValues(projectsById.get(candidate.projectId)!, candidate.widgetId)[candidate.key]
+ )) {
const groupKey = widgetGroupKey(entry.projectId, entry.widgetId);
const patch = patchesByGroup.get(groupKey) ?? { projectId: entry.projectId, values: {}, widgetId: entry.widgetId };
@@ -204,22 +200,18 @@ export const collectGalleryStoreKnownItemFields = (
};
/**
- * Filters `keys` down to those still safe to roll back: a key restores only
- * if its current value (as read by `readCurrent`) is either unknown (nothing
- * locally to protect) or still equal to `paintedValue` — the value *this*
- * optimistic mutation painted it to. A key a second, later mutation already
- * moved on from (e.g. a subsequent drag to a different board, or another
- * star toggle) is excluded, the per-item analogue of
- * `selectRestorableGalleryWidgetPatches`'s reference-equality CAS check and
- * `patchGalleryItemCaches`'s own `if (current === after)` rollback rule.
+ * The per-item form of the shared compare-and-swap rule: a key rolls back only
+ * if its current value is still what *this* mutation painted it to. A key a
+ * second, later mutation already moved on from (a subsequent drag to a
+ * different board, another star toggle) is excluded.
+ *
+ * Unknown counts as unclaimed here, unlike the widget-value case: `readCurrent`
+ * looks the item up in local state that may simply not hold it, so `undefined`
+ * means "nothing here to protect" rather than "someone cleared it".
*/
export const selectItemKeysUnchangedSince = <Value>(
keys: readonly GalleryItemKey[],
paintedValue: Value,
readCurrent: (key: GalleryItemKey) => Value | undefined
): GalleryItemKey[] =>
- keys.filter((key) => {
- const current = readCurrent(key);
-
- return current === undefined || current === paintedValue;
- });
+ keys.filter((key) => isSlotUnclaimed(readCurrent(key), paintedValue, { treatUnknownAsUnclaimed: true }));