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.

Merge commit from fork

Lincoln Stein88f76b0c41f5
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index d18c6e7846..40ce2ca772 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -76,6 +76,37 @@ def _services_with_invocation_cache_bypassed(services: "InvocationServices") ->
return effect_services
+class _UserScopedInvocationCache:
+ """Cache facade whose keys are scoped to one queueing user; everything else hits the real cache."""
+
+ def __init__(self, cache: Any, user_id: str) -> None:
+ self._cache = cache
+ self._user_id = user_id
+
+ def create_key(self, invocation: "BaseInvocation") -> int:
+ return hash((self._user_id, self._cache.create_key(invocation)))
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._cache, name)
+
+
+def services_for_queue_user(services: "InvocationServices", user_id: Optional[str]) -> "InvocationServices":
+ """Services for one node dispatch on behalf of the queue item's user.
+
+ In multiuser mode nodes authorize and scope work by the queueing user inside invoke(), so a cache
+ hit must never cross accounts. Without a usable user id the cache is bypassed (fail closed).
+ Single-user mode shares the cache across sessions as before.
+ """
+ if not services.configuration.multiuser:
+ return services
+ user_services = copy(services)
+ if isinstance(user_id, str) and user_id:
+ user_services.invocation_cache = _UserScopedInvocationCache(services.invocation_cache, user_id)
+ else:
+ user_services.invocation_cache = _InvocationCacheBypass(services.invocation_cache)
+ return user_services
+
+
class InvalidVersionError(ValueError):
pass
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 647d26a688..1164bbfd4b 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -10,7 +10,7 @@ from typing import Callable, Iterator, Literal, Optional
import torch
from starlette.concurrency import run_in_threadpool
-from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput
+from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, services_for_queue_user
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.events.events_common import (
@@ -486,9 +486,11 @@ class DefaultSessionRunner(SessionRunnerBase):
execution_workflow_authorizer=workflow_authorizer,
execution_workflow_inputs=workflow_inputs,
)
+ # The context hands nodes these services too, so it must carry the same user-scoped cache.
+ node_services = services_for_queue_user(self._services, queue_item.user_id)
context = build_invocation_context(
data=data,
- services=self._services,
+ services=node_services,
is_canceled=self._is_canceled,
)
@@ -508,7 +510,7 @@ class DefaultSessionRunner(SessionRunnerBase):
attention_caller(invocation.get_type()),
data.invocation_resources,
):
- run_result = invocation.invoke_internal_with_effects(context=context, services=self._services)
+ run_result = invocation.invoke_internal_with_effects(context=context, services=node_services)
output = run_result.output
control_collection = None
if self._on_after_run_node_callbacks and isinstance(invocation, (IterateInvocation, CollectInvocation)):
diff --git a/tests/app/invocations/test_external_image_generation.py b/tests/app/invocations/test_external_image_generation.py
index 4247a36687..cc32ed6948 100644
--- a/tests/app/invocations/test_external_image_generation.py
+++ b/tests/app/invocations/test_external_image_generation.py
@@ -109,3 +109,35 @@ def test_external_graph_execution_state_runs_node() -> None:
session.complete(node.id, output)
assert session.results[node.id] == output
+
+
+def test_external_invocation_cache_is_scoped_to_the_queueing_user_in_multiuser() -> None:
+ from invokeai.app.invocations.baseinvocation import services_for_queue_user
+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
+
+ model_config = _build_model()
+ context = _build_context(model_config, Image.new("RGB", (16, 16), color="black"))
+ context._data.queue_item.user_id = "alice"
+ services = SimpleNamespace(
+ configuration=SimpleNamespace(node_cache_size=5, multiuser=True),
+ invocation_cache=MemoryInvocationCache(max_cache_size=5),
+ intermediates=MagicMock(),
+ logger=MagicMock(),
+ )
+
+ def run() -> None:
+ OpenAIImageGenerationInvocation(
+ id="external_node", model=ModelIdentifierField.from_config(model_config), mode="txt2img", prompt="p"
+ ).invoke_internal_with_effects(
+ context,
+ services_for_queue_user(services, context._data.queue_item.user_id), # type: ignore[arg-type]
+ )
+
+ generate = context._services.external_generation.generate
+ run()
+ run() # alice again: a cache hit duplicates her images without calling the provider
+ assert generate.call_count == 1
+
+ context._data.queue_item.user_id = "bob"
+ run()
+ assert generate.call_count == 2
diff --git a/tests/app/invocations/test_text_llm_with_preset.py b/tests/app/invocations/test_text_llm_with_preset.py
index e4083c5e46..6af09808cb 100644
--- a/tests/app/invocations/test_text_llm_with_preset.py
+++ b/tests/app/invocations/test_text_llm_with_preset.py
@@ -252,3 +252,44 @@ def test_the_field_publishes_its_bounds_where_the_editors_read_them() -> None:
assert "anyOf" not in prop
assert (prop["minimum"], prop["maximum"]) == (0, EXPAND_PROMPT_MAX_TOKENS_MAX)
+
+
+def test_preset_node_cache_hit_does_not_bypass_the_access_check_for_another_user() -> None:
+ # Alice may use her private prompt and warms the shared invocation cache; Bob enqueues the
+ # byte-identical node. The cache must not hand him alice's output without the check running.
+ from types import SimpleNamespace
+
+ from invokeai.app.invocations.baseinvocation import services_for_queue_user
+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
+
+ services = SimpleNamespace(
+ configuration=SimpleNamespace(node_cache_size=5, multiuser=True),
+ invocation_cache=MemoryInvocationCache(max_cache_size=5),
+ intermediates=MagicMock(),
+ logger=MagicMock(),
+ )
+ context = _make_context(
+ prompt_record_content="alice's secret instruction",
+ multiuser=True,
+ record_user_id="alice",
+ record_is_public=False,
+ queue_user_id="alice",
+ )
+ context._skip_invocation_cache = False # a MagicMock attribute would be truthy and bypass the cache
+
+ def run() -> str:
+ return (
+ _make_invocation(prompt_id="alice-private")
+ .invoke_internal_with_effects(context, services_for_queue_user(services, context._data.queue_item.user_id))
+ .output.value
+ )
+
+ with patch("invokeai.app.invocations.text_llm._run_text_llm", return_value="alice's expansion") as mock_run:
+ assert run() == "alice's expansion"
+ assert run() == "alice's expansion" # same user, same inputs: served from the cache
+ assert mock_run.call_count == 1
+
+ context._data.queue_item.user_id = "bob"
+ with pytest.raises(ValueError, match="not accessible to this user"):
+ run()
+ assert mock_run.call_count == 1
diff --git a/tests/app/services/session_processor/test_invocation_cache_user_scope.py b/tests/app/services/session_processor/test_invocation_cache_user_scope.py
new file mode 100644
index 0000000000..c50f9aec9a
--- /dev/null
+++ b/tests/app/services/session_processor/test_invocation_cache_user_scope.py
@@ -0,0 +1,38 @@
+"""The session runner scopes the shared invocation cache to each queue item's owner in multiuser mode."""
+
+import pytest
+
+from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
+from tests.app.services.workflow_call_test_utils import _build_queue_item, _build_workflow_runner
+from tests.test_invocation_cache_memory import CACHE_SCOPE_NODE_CLASSES, CacheScopeRecorderInvocation
+
+
+# Node classes cover the default cache path and overrides that reach the cache through the dispatch
+# services argument or through context._services, so run_node must scope both.
[email protected]("node_class", CACHE_SCOPE_NODE_CLASSES)
[email protected]("multiuser,expected_calls", [(True, ["alice", "bob"]), (False, ["alice"])])
+def test_runner_scopes_cache_entries_to_the_queue_owner_only_in_multiuser(
+ monkeypatch: pytest.MonkeyPatch,
+ multiuser: bool,
+ expected_calls: list[str],
+ node_class: type[CacheScopeRecorderInvocation],
+) -> None:
+ runner, events, _ = _build_workflow_runner(monkeypatch)
+ services = runner._services
+ services.configuration.node_cache_size = 5
+ services.configuration.multiuser = multiuser
+ services.invocation_cache = MemoryInvocationCache(max_cache_size=5)
+ CacheScopeRecorderInvocation.calls.clear()
+
+ outputs = []
+ for user_id in ("alice", "bob"):
+ invocation = node_class(id=f"node-{user_id}", prompt="p")
+ queue_item = _build_queue_item(invocation)
+ queue_item.user_id = user_id
+ runner.run_node(invocation=invocation, queue_item=queue_item)
+ outputs.append(events.completed[-1][2].prompt)
+
+ assert events.errors == []
+ assert CacheScopeRecorderInvocation.calls == expected_calls
+ # Single-user mode keeps sharing: bob's run is served alice's cached output.
+ assert outputs == [f"p for {user}" for user in (["alice", "bob"] if multiuser else ["alice", "alice"])]
diff --git a/tests/app/services/session_processor/test_invocation_resources.py b/tests/app/services/session_processor/test_invocation_resources.py
index 1b10a62bba..4bc5f3641e 100644
--- a/tests/app/services/session_processor/test_invocation_resources.py
+++ b/tests/app/services/session_processor/test_invocation_resources.py
@@ -29,7 +29,7 @@ def test_resources_held_during_an_invocation_are_released_when_it_ends(
session.indegree[invocation.id] = 0
services = SimpleNamespace(
- configuration=SimpleNamespace(node_cache_size=0),
+ configuration=SimpleNamespace(node_cache_size=0, multiuser=False),
progress_previews=MemoryProgressPreviews(),
events=Mock(),
logger=Mock(),
diff --git a/tests/app/services/session_processor/test_node_attention_caller.py b/tests/app/services/session_processor/test_node_attention_caller.py
index a0e5aed8e6..9357cf469c 100644
--- a/tests/app/services/session_processor/test_node_attention_caller.py
+++ b/tests/app/services/session_processor/test_node_attention_caller.py
@@ -27,7 +27,7 @@ def _run_one_node(monkeypatch: pytest.MonkeyPatch, invoke) -> Mock:
invocation = session.next()
services = SimpleNamespace(
- configuration=SimpleNamespace(node_cache_size=0, offload_text_encoders_to_idle_gpus=False),
+ configuration=SimpleNamespace(node_cache_size=0, multiuser=False, offload_text_encoders_to_idle_gpus=False),
progress_previews=MemoryProgressPreviews(),
events=Mock(),
logger=Mock(),
diff --git a/tests/app/services/test_for_loop_session_runner.py b/tests/app/services/test_for_loop_session_runner.py
index 8f839777f8..fb88ee27f8 100644
--- a/tests/app/services/test_for_loop_session_runner.py
+++ b/tests/app/services/test_for_loop_session_runner.py
@@ -197,6 +197,7 @@ def _build_queue_item(session: GraphExecutionState) -> SimpleNamespace:
status="in_progress",
session=session,
session_id=session.id,
+ user_id="system",
)
diff --git a/tests/app/services/test_session_processor_callbacks.py b/tests/app/services/test_session_processor_callbacks.py
index 22e90ab6b5..4f9c32a859 100644
--- a/tests/app/services/test_session_processor_callbacks.py
+++ b/tests/app/services/test_session_processor_callbacks.py
@@ -25,7 +25,7 @@ def test_after_run_node_callback_receives_control_node_inputs(monkeypatch: pytes
context_data = []
services = SimpleNamespace(
- configuration=SimpleNamespace(node_cache_size=0),
+ configuration=SimpleNamespace(node_cache_size=0, multiuser=False),
progress_previews=MemoryProgressPreviews(),
events=Mock(),
logger=Mock(),
diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.py
index 9222442ad8..7a356c2fa7 100644
--- a/tests/app/services/workflow_call_test_utils.py
+++ b/tests/app/services/workflow_call_test_utils.py
@@ -936,6 +936,7 @@ def _build_queue_item(invocation: BaseInvocation):
{
"item_id": 1,
"session_id": "test-session",
+ "user_id": "system",
"session": Session(),
},
)()
@@ -1402,6 +1403,7 @@ def test_run_node_does_not_swallow_sigint_in_subprocess() -> None:
{
"item_id": 1,
"session_id": "test-session",
+ "user_id": "system",
"session": Session(),
},
)()
diff --git a/tests/test_invocation_cache_memory.py b/tests/test_invocation_cache_memory.py
index 5dadbe63b0..8563b81ed2 100644
--- a/tests/test_invocation_cache_memory.py
+++ b/tests/test_invocation_cache_memory.py
@@ -1,10 +1,17 @@
# pyright: reportPrivateUsage=false
from contextlib import suppress
+from types import SimpleNamespace
+from typing import ClassVar
+from unittest.mock import MagicMock
-from invokeai.app.invocations.fields import ImageField
+import pytest
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation, services_for_queue_user
+from invokeai.app.invocations.fields import ImageField, InputField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
-from tests.test_nodes import PromptTestInvocation
+from invokeai.app.services.shared.invocation_context import InvocationContext
+from tests.test_nodes import PromptTestInvocation, PromptTestInvocationOutput
def test_invocation_cache_memory_max_cache_size():
@@ -205,3 +212,123 @@ def test_invocation_cache_memory_purges_video_outputs_on_video_deletion():
cache._delete_by_match("clip.mp4")
assert cache.get(1) is None
assert len(cache._cache) == 0
+
+
+@invocation("test_cache_scope_recorder", version="1.0.0", use_cache=True)
+class CacheScopeRecorderInvocation(BaseInvocation):
+ """Records which queueing user each real invoke() ran for."""
+
+ prompt: str = InputField(default="")
+ calls: ClassVar[list] = []
+
+ def invoke(self, context: InvocationContext) -> PromptTestInvocationOutput:
+ user_id = context._data.queue_item.user_id
+ type(self).calls.append(user_id)
+ return PromptTestInvocationOutput(prompt=f"{self.prompt} for {user_id}")
+
+
+@invocation("test_cache_scope_custom_override", version="1.0.0", use_cache=True)
+class CacheScopeCustomOverrideInvocation(CacheScopeRecorderInvocation):
+ """A node pack that owns its cache logic, keying it through services.invocation_cache.create_key."""
+
+ def invoke_internal(self, context: InvocationContext, services) -> PromptTestInvocationOutput:
+ key = services.invocation_cache.create_key(self)
+ cached = services.invocation_cache.get(key)
+ if cached is None:
+ cached = self.invoke(context)
+ services.invocation_cache.save(key, cached)
+ return cached
+
+
+@invocation("test_cache_scope_context_services_override", version="1.0.0", use_cache=True)
+class CacheScopeContextServicesOverrideInvocation(CacheScopeRecorderInvocation):
+ """A node pack that owns its cache logic through context._services, ignoring the services argument."""
+
+ def invoke_internal(self, context: InvocationContext, services) -> PromptTestInvocationOutput:
+ cache = context._services.invocation_cache
+ key = cache.create_key(self)
+ cached = cache.get(key)
+ if cached is None:
+ cached = self.invoke(context)
+ cache.save(key, cached)
+ return cached
+
+
+CACHE_SCOPE_NODE_CLASSES = [
+ CacheScopeRecorderInvocation,
+ CacheScopeCustomOverrideInvocation,
+ CacheScopeContextServicesOverrideInvocation,
+]
+
+
+def _cache_services(*, multiuser: bool) -> SimpleNamespace:
+ return SimpleNamespace(
+ configuration=SimpleNamespace(node_cache_size=5, multiuser=multiuser),
+ invocation_cache=MemoryInvocationCache(max_cache_size=5),
+ intermediates=MagicMock(),
+ logger=MagicMock(),
+ )
+
+
+def _run(
+ services: SimpleNamespace,
+ user_id: str | None,
+ session_id: str = "session",
+ node_class: type[CacheScopeRecorderInvocation] = CacheScopeRecorderInvocation,
+) -> str:
+ """Dispatch one node the way the session processor does, for a queue item owned by `user_id`."""
+ node = node_class(id=f"node-{len(node_class.calls)}", prompt="p")
+ node_services = services_for_queue_user(services, user_id) # type: ignore[arg-type]
+ # Like run_node, the context carries the same per-user services as the dispatch.
+ context = SimpleNamespace(
+ _data=SimpleNamespace(queue_item=SimpleNamespace(user_id=user_id, session_id=session_id)),
+ _services=node_services,
+ _skip_invocation_cache=False,
+ )
+ return node.invoke_internal_with_effects(context, node_services).output.prompt # type: ignore[arg-type]
+
+
[email protected](autouse=True)
+def _reset_recorder_calls():
+ CacheScopeRecorderInvocation.calls.clear()
+
+
[email protected]("node_class", CACHE_SCOPE_NODE_CLASSES)
+def test_multiuser_cache_hits_never_cross_users(node_class: type[CacheScopeRecorderInvocation]):
+ services = _cache_services(multiuser=True)
+
+ assert _run(services, "alice", node_class=node_class) == "p for alice"
+ # Bob's identical node must run invoke() rather than receive alice's output.
+ assert _run(services, "bob", node_class=node_class) == "p for bob"
+ assert CacheScopeRecorderInvocation.calls == ["alice", "bob"]
+
+
[email protected]("node_class", CACHE_SCOPE_NODE_CLASSES)
+def test_multiuser_cache_still_hits_for_the_same_user(node_class: type[CacheScopeRecorderInvocation]):
+ services = _cache_services(multiuser=True)
+
+ assert _run(services, "alice", "s1", node_class) == "p for alice"
+ assert _run(services, "alice", "s2", node_class) == "p for alice"
+ assert CacheScopeRecorderInvocation.calls == ["alice"]
+
+
[email protected]("node_class", CACHE_SCOPE_NODE_CLASSES)
[email protected]("user_id", [None, ""])
+def test_multiuser_cache_is_bypassed_without_a_queueing_user(
+ user_id: str | None, node_class: type[CacheScopeRecorderInvocation]
+):
+ services = _cache_services(multiuser=True)
+
+ _run(services, user_id, node_class=node_class)
+ _run(services, user_id, node_class=node_class)
+ assert CacheScopeRecorderInvocation.calls == [user_id, user_id]
+ assert len(services.invocation_cache._cache) == 0
+
+
+def test_single_user_cache_is_shared_across_sessions():
+ services = _cache_services(multiuser=False)
+
+ assert services_for_queue_user(services, "system") is services # type: ignore[arg-type]
+ assert _run(services, "system", "s1") == "p for system"
+ assert _run(services, "other", "s2") == "p for system"
+ assert CacheScopeRecorderInvocation.calls == ["system"]