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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): match wildcard globs without backtracking
joshistoast02600f416f58
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.tsindex 0071b48b42..24c1bc7994 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {getWildcardNameError,hasDynamicPromptSyntax,+ matchesKnownWildcard,sanitizeDynamicPromptsConfig,sanitizeMaxPrompts,} from './dynamicPrompts';@@ -98,3 +99,48 @@ describe('getWildcardNameError', () => {expect(getWildcardNameError('shades', new Set(['colors']))).toBeNull();});});++describe('matchesKnownWildcard', () => {+ const CATALOG = new Set(['colours', 'colours/warm', 'animals/dogs', 'moods']);++ it('looks a plain path up directly', () => {+ expect(matchesKnownWildcard('colours', CATALOG)).toBe(true);+ expect(matchesKnownWildcard('nope', CATALOG)).toBe(false);+ });++ it('resolves globs, including across the `/` separator', () => {+ expect(matchesKnownWildcard('colo*', CATALOG)).toBe(true);+ expect(matchesKnownWildcard('*s', CATALOG)).toBe(true);+ expect(matchesKnownWildcard('animals/*', CATALOG)).toBe(true);+ // `*` is an unanchored run of anything, `/` included — as on the backend.+ expect(matchesKnownWildcard('*/dogs', CATALOG)).toBe(true);+ expect(matchesKnownWildcard('*', CATALOG)).toBe(true);+ expect(matchesKnownWildcard('nope/*', CATALOG)).toBe(false);+ expect(matchesKnownWildcard('colours/*', new Set(['colours']))).toBe(false);+ });++ it('anchors both ends, so the two cannot share characters', () => {+ // `ab*ba` needs four characters; matching `ab` and `ba` onto the same `b`+ // is what a naive prefix/suffix check gets wrong.+ expect(matchesKnownWildcard('ab*ba', new Set(['aba']))).toBe(false);+ expect(matchesKnownWildcard('ab*ba', new Set(['abba']))).toBe(true);+ });++ it('takes the interior runs in order', () => {+ expect(matchesKnownWildcard('a*b*c', new Set(['axbxc']))).toBe(true);+ expect(matchesKnownWildcard('a*b*c', new Set(['axcxb']))).toBe(false);+ // Adjacent stars collapse: `**` means what `*` means.+ expect(matchesKnownWildcard('a**c', new Set(['abc']))).toBe(true);+ });++ // Regression: translating the path to `^a.*.*.*…$` backtracks exponentially,+ // and the path is whatever the user has typed so far. Twelve stars against one+ // name used to take about a minute.+ it('does not backtrack on a path full of stars', () => {+ const names = new Set(Array.from({ length: 50 }, (_, index) => `colours/warm-autumn-palette-${index}`));+ const started = performance.now();++ expect(matchesKnownWildcard(`${'*'.repeat(24)}q`, names)).toBe(false);+ expect(performance.now() - started).toBeLessThan(100);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.tsindex dd344d5edf..553faee0c9 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts@@ -64,7 +64,55 @@ export const WILDCARD_REFERENCE_RE = new RegExp(`__[~@]?(${WILDCARD_PATH_SOURCE}/** The same rule anchored, for validating a name the user is typing. */export const WILDCARD_NAME_RE = new RegExp(`^${WILDCARD_NAME_SOURCE}$`);-const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+/**+ * Whether `name` matches a glob, given the literal runs between its `*`s.+ *+ * Deliberately not a regex. Translating `a*b*c` to `^a.*b.*c$` reads well but+ * makes adjacent stars into `.*.*`, which backtracks exponentially: a dozen of+ * them against one catalog name took a minute to fail. The path comes straight+ * out of whatever the user is typing, so that is a frozen tab, not a slow test.+ *+ * The greedy scan below is the standard `*`-only matcher and is linear in+ * practice: anchor the first run to the start and the last to the end, then take+ * each middle run at its earliest remaining occurrence. Earliest is always safe+ * when the only wildcard is "any run of anything" — consuming less can never+ * turn a match into a miss.+ */+const matchesGlobLiterals = (literals: readonly string[], name: string): boolean => {+ const first = literals[0] ?? '';+ const last = literals[literals.length - 1] ?? '';++ if (literals.length === 1) {+ return name === first;+ }++ // Checked before the middle runs so the two anchors cannot overlap and count+ // the same characters twice: `ab*ba` needs four characters, not three.+ if (name.length < first.length + last.length || !name.startsWith(first) || !name.endsWith(last)) {+ return false;+ }++ const end = name.length - last.length;+ let index = first.length;++ for (let position = 1; position < literals.length - 1; position++) {+ const literal = literals[position];++ if (literal === undefined || literal.length === 0) {+ continue;+ }++ const found = name.indexOf(literal, index);++ if (found < 0 || found + literal.length > end) {+ return false;+ }++ index = found + literal.length;+ }++ return true;+};/*** Whether a referenced path resolves against the catalog.@@ -83,10 +131,10 @@ export const matchesKnownWildcard = (path: string, knownNames: ReadonlySet<strinreturn knownNames.has(path);}- const pattern = new RegExp(`^${path.split('*').map(escapeRegExp).join('.*')}$`);+ const literals = path.split('*');for (const name of knownNames) {- if (pattern.test(name)) {+ if (matchesGlobLiterals(literals, name)) {return true;}}