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.

perf(webv2): invalidate once for a whole wildcard import

joshistoast9bcfe4cb9ca4
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
index 002b581e18..4344b3471b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
@@ -7,6 +7,7 @@ import { HStack, Menu, Portal } from '@chakra-ui/react';
import { getWildcardImportActions, planWildcardImport } from '@features/generation/core/wildcardTransfer';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { WildcardImportDialog } from '@features/generation/ui/promptFields/WildcardImportDialog';
+import { WildcardWriteError } from '@features/generation/ui/useWildcards';
import {
downloadWildcards,
isSupportedWildcardFile,
@@ -56,25 +57,19 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
const applyImport = useCallback(
async (entries: readonly WildcardImportEntry[], resolutions: Record<string, WildcardImportResolution>) => {
const actions = getWildcardImportActions(entries, resolutions, new Set(catalog.wildcards.map((w) => w.name)));
- let done = 0;
setIsBusy(true);
try {
- for (const action of actions) {
- if (action.id === undefined) {
- await catalog.create({ name: action.name, values: action.values });
- } else {
- await catalog.update(action.id, { name: action.name, values: action.values });
- }
- done++;
- }
-
- notifications.info(t('widgets.generate.dynamicPrompts.importedCount', { count: done }));
+ notifications.info(
+ t('widgets.generate.dynamicPrompts.importedCount', { count: await catalog.applyWrites(actions) })
+ );
} catch (caught) {
// Writes go one at a time, so a failure part-way leaves real wildcards
// behind. Saying only that the import failed sent people back for a
// second run that then clashed with everything the first one had made.
+ const done = caught instanceof WildcardWriteError ? caught.done : 0;
+
reportError(
'import-wildcards',
caught,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
index aac004f1d6..fc267d2eb0 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
@@ -20,6 +20,7 @@ let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const catalog: WildcardCatalog = {
+ applyWrites: vi.fn(),
create: vi.fn(),
isLoading: false,
knownNames: new Set(['colors']),
@@ -152,6 +153,7 @@ describe('wildcard name validation', () => {
describe('finding a wildcard', () => {
const manyCatalog: WildcardCatalog = {
+ applyWrites: vi.fn(),
create: vi.fn(),
isLoading: false,
knownNames: new Set(['colors']),
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx
new file mode 100644
index 0000000000..e928c94fef
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx
@@ -0,0 +1,117 @@
+import { useWildcards, WildcardWriteError } from '@features/generation/ui/useWildcards';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const createWildcard = vi.fn(() => Promise.resolve());
+const updateWildcard = vi.fn(() => Promise.resolve());
+const invalidateWildcardDependents = vi.fn(() => Promise.resolve());
+
+vi.mock('@features/generation/data/wildcards', () => ({
+ createWildcard: (...args: unknown[]) => createWildcard(...(args as [])),
+ deleteWildcard: vi.fn(),
+ invalidateWildcardDependents: (...args: unknown[]) => invalidateWildcardDependents(...(args as [])),
+ updateWildcard: (...args: unknown[]) => updateWildcard(...(args as [])),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+let catalog: ReturnType<typeof useWildcards> | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Probe = () => {
+ const value = useWildcards();
+
+ // Assigned in an effect rather than during render: reassigning an outer
+ // binding while rendering is a side effect, and the compiler says so.
+ useEffect(() => {
+ catalog = value;
+ }, [value]);
+
+ return null;
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <Probe />
+ </QueryClientProvider>
+ );
+ });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ catalog = null;
+});
+
+describe('applyWrites', () => {
+ const WRITES = [
+ { name: 'a', values: ['1'] },
+ { id: 'w2', name: 'b', values: ['2'] },
+ { name: 'c', values: ['3'] },
+ ];
+
+ // Every single-write method invalidates the wildcard cache *and* every
+ // dynamic-prompt expansion, and awaits the refetch. Doing that between each
+ // write of a forty-file import meant re-reading a list that grew by one, forty
+ // times over.
+ it('invalidates once for the whole run, not once per write', async () => {
+ await act(async () => {
+ await catalog!.applyWrites(WRITES);
+ });
+
+ expect(createWildcard).toHaveBeenCalledTimes(2);
+ expect(updateWildcard).toHaveBeenCalledTimes(1);
+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports how many landed', async () => {
+ let done = 0;
+
+ await act(async () => {
+ done = await catalog!.applyWrites(WRITES);
+ });
+
+ expect(done).toBe(3);
+ });
+
+ // The ones already written are real, so the caches are stale whether or not
+ // the run finished — and the caller needs the count to say how far it got.
+ it('still invalidates, and carries the count, when a write fails', async () => {
+ createWildcard.mockImplementationOnce(() => Promise.resolve());
+ updateWildcard.mockImplementationOnce(() => Promise.reject(new Error('conflict')));
+
+ let caught: unknown;
+
+ await act(async () => {
+ caught = await catalog!.applyWrites(WRITES).catch((error: unknown) => error);
+ });
+
+ expect(caught).toBeInstanceOf(WildcardWriteError);
+ expect((caught as WildcardWriteError).done).toBe(1);
+ expect((caught as WildcardWriteError).cause).toMatchObject({ message: 'conflict' });
+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not invalidate when the very first write fails', async () => {
+ createWildcard.mockImplementationOnce(() => Promise.reject(new Error('nope')));
+
+ await act(async () => {
+ await catalog!.applyWrites(WRITES).catch(() => undefined);
+ });
+
+ expect(invalidateWildcardDependents).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
index 62d58fa23e..34b8e9c662 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
@@ -11,6 +11,31 @@ import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
+/** One write, as `applyWrites` will perform it. */
+export interface WildcardWrite {
+ name: string;
+ values: string[];
+ /** Present to update that wildcard; absent to create a new one. */
+ id?: string;
+}
+
+/**
+ * A run of writes that stopped part-way, carrying how many had landed.
+ *
+ * The count is the point: the ones already written are real, and a caller that
+ * reports only "it failed" sends the user back for a second run that then
+ * clashes with everything the first one made.
+ */
+export class WildcardWriteError extends Error {
+ constructor(
+ readonly done: number,
+ override readonly cause: unknown
+ ) {
+ super(cause instanceof Error ? cause.message : String(cause));
+ this.name = 'WildcardWriteError';
+ }
+}
+
export interface WildcardCatalog {
wildcards: WildcardRecord[];
/** Names the backend can resolve, for the highlighter's known/unknown split. */
@@ -19,6 +44,16 @@ export interface WildcardCatalog {
create: (wildcard: { name: string; values: string[] }) => Promise<void>;
update: (id: string, changes: { name?: string; values?: string[] }) => Promise<void>;
remove: (id: string) => Promise<void>;
+ /**
+ * A run of writes with a single invalidation at the end.
+ *
+ * Resolves with how many landed, and rethrows whatever stopped it — the caller
+ * needs both to say "stopped after 6 of 40". Ordinary edits go through the
+ * single-write methods above; this exists for import, where doing it one call
+ * at a time meant re-fetching the whole catalog, plus every dynamic-prompt
+ * expansion, between each write and the next.
+ */
+ applyWrites: (writes: readonly WildcardWrite[]) => Promise<number>;
}
/**
@@ -64,5 +99,43 @@ export const useWildcards = (): WildcardCatalog => {
const remove = useCallback((id: string) => runAndInvalidate(() => deleteWildcard(id)), [runAndInvalidate]);
- return { create, isLoading: query.isPending, knownNames, remove, update, wildcards };
+ const applyWrites = useCallback(
+ async (writes: readonly WildcardWrite[]): Promise<number> => {
+ const owner = captureAccountScope();
+ let done = 0;
+ let failure: unknown;
+
+ try {
+ for (const write of writes) {
+ if (write.id === undefined) {
+ await createWildcard({ name: write.name, values: write.values });
+ } else {
+ await updateWildcard(write.id, { name: write.name, values: write.values });
+ }
+
+ done++;
+ }
+ } catch (caught) {
+ failure = caught;
+ }
+
+ // Whatever landed before the failure is real, so the caches are stale
+ // either way — invalidate on the strength of that rather than on the run
+ // having finished. The scope check stays where it is for every other
+ // mutation: a sign-out mid-run must not drop the next account's caches.
+ if (done > 0) {
+ assertAccountScopeCurrent(owner);
+ await invalidateWildcardDependents(queryClient);
+ }
+
+ if (failure) {
+ throw new WildcardWriteError(done, failure);
+ }
+
+ return done;
+ },
+ [queryClient]
+ );
+
+ return { applyWrites, create, isLoading: query.isPending, knownNames, remove, update, wildcards };
};