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(dynamicprompts): report every unresolvable wildcard, not just nested ones

joshistoast9f85e194101b
diff --git a/invokeai/app/util/dynamicprompts.py b/invokeai/app/util/dynamicprompts.py
index 5c92231821..4d71f04d7c 100644
--- a/invokeai/app/util/dynamicprompts.py
+++ b/invokeai/app/util/dynamicprompts.py
@@ -14,43 +14,43 @@ from dynamicprompts.wildcards import WildcardManager
from pyparsing import ParseException
-def _iter_wildcard_names(command: Command, in_variant: bool = False) -> Iterator[str]:
- """Recursively yield the statically-known wildcard names that appear as (part of) a variant value.
-
- Only wildcards reachable from a `VariantCommand` value are yielded: those are the references that
- hang the combinatorial generator (see `find_missing_wildcards`). The same wildcard used as plain
- literal text (e.g. `a __nope__ b`) generates fine, so it is intentionally not reported.
- """
+def _iter_wildcard_names(command: Command) -> Iterator[str]:
+ """Recursively yield the statically-known wildcard names referenced by `command`."""
if isinstance(command, WildcardCommand):
# The wildcard name may itself be a dynamic Command (e.g. `__${var}__`). Only plain string
# names can be validated ahead of time, so the dynamic case is intentionally skipped.
- if in_variant and isinstance(command.wildcard, str):
+ if isinstance(command.wildcard, str):
yield command.wildcard
elif isinstance(command, SequenceCommand):
for token in command.tokens:
- yield from _iter_wildcard_names(token, in_variant)
+ yield from _iter_wildcard_names(token)
elif isinstance(command, VariantCommand):
- # Everything below a variant value is a variant-nested reference, even across sequences.
for value in command.values:
- yield from _iter_wildcard_names(value, in_variant=True)
+ yield from _iter_wildcard_names(value)
elif isinstance(command, WrapCommand):
- yield from _iter_wildcard_names(command.wrapper, in_variant)
- yield from _iter_wildcard_names(command.inner, in_variant)
+ yield from _iter_wildcard_names(command.wrapper)
+ yield from _iter_wildcard_names(command.inner)
# LiteralCommand and variable commands reference no wildcards we can resolve statically.
def find_missing_wildcards(prompt: str, wildcard_manager: WildcardManager | None = None) -> list[str]:
- """Return the unique unknown wildcard names in `prompt` that hang the combinatorial generator.
+ """Return the unique wildcard names in `prompt` that `wildcard_manager` cannot resolve.
+
+ An unresolvable wildcard breaks the combinatorial generator in two different ways, so callers
+ should treat any non-empty result as a hard error rather than generating:
+
+ - *As a variant value* (e.g. `{__nope__|x}`) it loops forever: the not-found fallback
+ (`get_wildcard_not_found_fallback`) yields the wrapped wildcard infinitely, and the
+ combinatorial variant logic dedupes those duplicates away without ever advancing.
+ - *Anywhere else* (e.g. `a {red|green} __nope__ b`) it silently produces `max_prompts` copies of
+ a single prompt and collapses the other variants, so a caller that generated anyway would
+ queue N identical results.
- Referencing an unknown wildcard *as a variant value* (e.g. `{__nope__|x}`) makes dynamicprompts'
- combinatorial generator loop forever: its not-found fallback (`get_wildcard_not_found_fallback`)
- yields the wrapped wildcard infinitely, and the combinatorial variant logic dedupes those
- duplicates away without ever advancing. Detecting these names up front lets callers report a clear
- error instead of hanging. Only the combinatorial generator is affected, and only for wildcards
- nested in a variant — a bare `a __nope__ b` generates fine and is not reported.
+ Only the combinatorial generator is affected; the random generator leaves an unresolvable
+ wildcard as literal text.
- Without a configured `wildcard_manager`, an empty one is used so that every referenced wildcard is
- treated as missing (wildcards are not resolved against any files here).
+ Without a configured `wildcard_manager`, an empty one is used, so every referenced wildcard is
+ reported as missing.
"""
if wildcard_manager is None:
wildcard_manager = WildcardManager()
diff --git a/tests/app/routers/test_utilities.py b/tests/app/routers/test_utilities.py
index 84a6969688..ada5f53322 100644
--- a/tests/app/routers/test_utilities.py
+++ b/tests/app/routers/test_utilities.py
@@ -84,18 +84,23 @@ def test_dynamicprompts_unknown_wildcard_returns_error_without_hanging(client: T
assert body["prompts"] == ["{__random__8chan|fenster|stuff}"]
-def test_dynamicprompts_bare_unknown_wildcard_still_generates(client: TestClient, user1_token: str):
- """A wildcard used as plain literal text (not a variant value) does not hang and must not error."""
+def test_dynamicprompts_bare_unknown_wildcard_returns_error(client: TestClient, user1_token: str):
+ """A wildcard outside a variant does not hang, but it does not generate usefully either.
+
+ The combinatorial generator emits `max_prompts` copies of one prompt and drops every other
+ variant's values, so a caller that generated anyway would queue N identical results. This case
+ was previously allowed through with `error: None`; it must report the unresolvable name instead.
+ """
r = client.post(
"/api/v1/utilities/dynamicprompts",
- json={"prompt": "a photo, __my_style__"},
+ json={"prompt": "a {red|green} photo, __my_style__"},
headers={"Authorization": f"Bearer {user1_token}"},
)
assert r.status_code == status.HTTP_200_OK
body = r.json()
- assert body["error"] is None
- assert body["prompts"] # non-empty
- assert all(p == "a photo, __my_style__" for p in body["prompts"])
+ assert body["error"] is not None
+ assert "my_style" in body["error"]
+ assert body["prompts"] == ["a {red|green} photo, __my_style__"]
def test_dynamicprompts_random_generator_ignores_unknown_wildcard(client: TestClient, user1_token: str):
diff --git a/tests/app/util/test_dynamicprompts.py b/tests/app/util/test_dynamicprompts.py
index 83ff02f3c4..6b27c342df 100644
--- a/tests/app/util/test_dynamicprompts.py
+++ b/tests/app/util/test_dynamicprompts.py
@@ -1,25 +1,44 @@
from __future__ import annotations
import pytest
+from dynamicprompts.generators import CombinatorialPromptGenerator
+from dynamicprompts.wildcards import WildcardManager
from invokeai.app.util.dynamicprompts import find_missing_wildcards
+def wildcard_manager() -> WildcardManager:
+ return WildcardManager(root_map={"": [{"colors": ["red", "green", "blue"]}]})
+
+
def test_find_missing_wildcards_detects_unknown_wildcard_in_variant() -> None:
- # Regression: `__random__` inside a variant is parsed as a wildcard reference. Left unchecked it
- # sends the combinatorial generator into an infinite loop, so it must be reported up front.
+ # `__random__` inside a variant is parsed as a wildcard reference. Left unchecked it sends the
+ # combinatorial generator into an infinite loop, so it must be reported up front.
assert find_missing_wildcards("{__random__8chan|fenster|stuff}") == ["random"]
def test_find_missing_wildcards_detects_unknown_wildcard_nested_in_sequence_in_variant() -> None:
- # The wildcard hangs the generator even when wrapped in other text inside the variant value.
assert find_missing_wildcards("{a __nope__|b}") == ["nope"]
@pytest.mark.parametrize("prompt", ["a __nope__ b", "__nope__", "a photo, __my_style__"])
-def test_find_missing_wildcards_ignores_wildcards_outside_variants(prompt: str) -> None:
- # A wildcard used as plain literal text generates fine (no hang), so it must not be reported.
- assert find_missing_wildcards(prompt) == []
+def test_find_missing_wildcards_detects_unknown_wildcards_outside_variants(prompt: str) -> None:
+ # Regression: these were previously ignored on the theory that only variant-nested wildcards
+ # misbehave. They do not hang, but they silently collapse the prompt (see the generator test
+ # below), so they must be reported too.
+ assert find_missing_wildcards(prompt) != []
+
+
+def test_unresolvable_wildcard_outside_a_variant_silently_collapses_the_prompt() -> None:
+ # The behaviour that makes the case above worth reporting: rather than erroring, the generator
+ # emits `max_prompts` copies of one prompt and drops the other variant's values entirely.
+ prompt = "a {red|green} __nope__ ball"
+ generated = CombinatorialPromptGenerator().generate(prompt, max_prompts=6)
+
+ assert len(generated) == 6
+ assert len(set(generated)) == 1
+ assert find_missing_wildcards(prompt) == ["nope"]
@pytest.mark.parametrize("prompt", ["plain text", "{a|b|c}", "a {2$$x|y|z}"])
@@ -29,3 +48,22 @@ def test_find_missing_wildcards_ignores_prompts_without_wildcards(prompt: str) -
def test_find_missing_wildcards_dedupes_repeated_unknown_wildcards() -> None:
assert find_missing_wildcards("{__nope__|a} {__nope__|b} {__other__|c}") == ["nope", "other"]
+
+
+def test_find_missing_wildcards_reports_nothing_for_resolvable_wildcards(
+ wildcard_manager: WildcardManager,
+) -> None:
+ assert find_missing_wildcards("a __colors__ ball", wildcard_manager) == []
+ assert find_missing_wildcards("{__colors__|x}", wildcard_manager) == []
+ assert find_missing_wildcards("a {__colors__|__nope__} ball", wildcard_manager) == ["nope"]
+
+
+def test_resolvable_wildcard_in_a_variant_generates_instead_of_hanging(
+ wildcard_manager: WildcardManager,
+) -> None:
+ # The hang this module guards against is a symptom of an unresolvable wildcard. Once the manager
+ # can resolve it, the same shape generates normally.
+ generated = CombinatorialPromptGenerator(wildcard_manager).generate("{__colors__|x}", max_prompts=5)
+
+ assert sorted(generated) == ["blue", "green", "red", "x"]