feat: Add CacheProvider API for external distributed caching#12056
feat: Add CacheProvider API for external distributed caching#12056
Conversation
Introduces a public API for external cache providers, enabling distributed caching across multiple ComfyUI instances (e.g., Kubernetes pods). New files: - comfy_execution/cache_provider.py: CacheProvider ABC, CacheContext/CacheValue dataclasses, thread-safe provider registry, serialization utilities Modified files: - comfy_execution/caching.py: Add provider hooks to BasicCache (_notify_providers_store, _check_providers_lookup), subcache exclusion, prompt ID propagation - execution.py: Add prompt lifecycle hooks (on_prompt_start/on_prompt_end) to PromptExecutor, set _current_prompt_id on caches Key features: - Local-first caching (check local before external for performance) - NaN detection to prevent incorrect external cache hits - Subcache exclusion (ephemeral subgraph results not cached externally) - Thread-safe provider snapshot caching - Graceful error handling (provider errors logged, never break execution) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Pickle serialization is NOT deterministic across Python sessions due to hash randomization affecting frozenset iteration order. This causes distributed caching to fail because different pods compute different hashes for identical cache keys. Fix: Use _canonicalize() + JSON serialization which ensures deterministic ordering regardless of Python's hash randomization. This is critical for cross-pod cache key consistency in Kubernetes deployments. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add comprehensive tests for _canonicalize deterministic ordering - Add tests for serialize_cache_key hash consistency - Add tests for contains_nan utility - Add tests for estimate_value_size - Add tests for provider registry (register, unregister, clear) - Move json import to top-level (fix inline import) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Fixes ruff F821 (undefined name) and F401 (unused import) errors. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Frozensets can only contain hashable types, so use nested frozensets instead of dicts. Added separate test for dict handling via serialize_cache_key. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add Caching class to comfy_api/latest/__init__.py that re-exports
from comfy_execution.cache_provider (source of truth)
- Fix docstring: "Skip large values" instead of "Skip small values"
(small compute-heavy values are good cache targets)
- Maintain backward compatibility: comfy_execution.cache_provider
imports still work
Usage:
from comfy_api.latest import Caching
class MyProvider(Caching.CacheProvider):
def on_lookup(self, context): ...
def on_store(self, context, value): ...
Caching.register_provider(MyProvider())
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Change docstring from "Skip large values" to "Skip if download time > compute time" which better captures the cost/benefit tradeoff for external caching. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Remove prescriptive filtering suggestions - let implementations decide their own caching logic based on their use case. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add ui field to CacheValue dataclass (default None)
- Pass ui when creating CacheValue for external providers
- Use result.ui (or default {}) when returning from external cache lookup
This allows external cache implementations to store/retrieve UI data
if desired, while remaining optional for implementations that skip it.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Clearer name since objects are also cached locally - this specifically checks for external caching eligibility. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
- Make on_lookup/on_store async on CacheProvider ABC - Simplify CacheContext: replace cache_key + cache_key_bytes with cache_key_hash (str hex digest) - Make registry/utility functions internal (_prefix) - Trim comfy_api.latest.Caching exports to core API only - Make cache get/set async throughout caching.py hierarchy - Use asyncio.create_task for fire-and-forget on_store - Add NaN gating before provider calls in Core - Add await to 5 cache call sites in execution.py Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds an asynchronous, pluggable distributed cache provider system and integrates it into caching and execution. Introduces CacheContext, CacheValue, and an abstract CacheProvider with async on_lookup/on_store plus lifecycle hooks; a thread-safe provider registry and utilities for deterministic canonicalization, cache-key hashing, NaN detection, and size estimation. Converts core cache APIs to async, propagates per-prompt IDs to caches, consults external providers on misses and warms local cache on hits, and notifies providers of prompt lifecycle events from the executor. Adds unit tests covering utilities and registry behavior. Changes
Sequence DiagramsequenceDiagram
participant Executor as Executor
participant LocalCache as Local Cache
participant Provider as Cache Provider(s)
rect rgba(100, 150, 200, 0.5)
Note over Executor,Provider: Cache Lookup Flow
Executor->>LocalCache: await get(node_id)
LocalCache->>LocalCache: Check local storage
alt Cache Hit
LocalCache-->>Executor: Return cached value
else Cache Miss
LocalCache->>Provider: await on_lookup(context)
Provider-->>LocalCache: CacheValue or None
alt Provider Hit
LocalCache->>LocalCache: Warm local cache
LocalCache-->>Executor: Return external value
else Provider Miss
LocalCache-->>Executor: Return None
end
end
end
rect rgba(150, 200, 100, 0.5)
Note over Executor,Provider: Cache Store Flow
Executor->>LocalCache: await set(node_id, value)
LocalCache->>LocalCache: Store locally
LocalCache->>Provider: _notify_providers_store(context, value)
Provider->>Provider: await on_store(context, value)
Note over Provider: Fire-and-forget
LocalCache-->>Executor: Complete
end
rect rgba(200, 150, 100, 0.5)
Note over Executor,Provider: Lifecycle Management
Executor->>Provider: on_prompt_start(prompt_id)
Note over Provider: Initialize for prompt
Executor->>Executor: Execute nodes with caching
Executor->>Provider: on_prompt_end(prompt_id)
Note over Provider: Cleanup for prompt
end
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@comfy_execution/cache_provider.py`:
- Around line 178-202: The helper functions are defined with leading underscores
(_get_cache_providers, _has_cache_providers, _clear_cache_providers) while
callers in the PR import non-underscored names, causing import/runtime errors;
add thin public wrappers named get_cache_providers(), has_cache_providers(), and
clear_cache_providers() that simply call and return the existing underscored
implementations (preserving behavior around _providers_snapshot, _providers_lock
and _providers) or alternatively rename all callers to use the existing
underscored names—ensure the public wrappers delegate to _get_cache_providers,
_has_cache_providers, and _clear_cache_providers so existing internal
locking/caching behavior is preserved.
- Around line 260-267: Replace the process-local id()-based fallback in
comfy_execution/cache_provider.py so that when both deterministic serialization
and pickle serialization of cache_key fail the function returns None
(fail-closed) instead of hashing id(cache_key); specifically modify the except
block around pickle.dumps to return None on exception rather than
hashlib.sha256(str(id(cache_key)).encode()).hexdigest(). Then update
comfy_execution/caching.py to check the cache_key_hash variable and skip calling
the provider (do not attempt get/set on the provider) when cache_key_hash is
None so caching is bypassed for non-serializable keys.
In `@comfy_execution/caching.py`:
- Around line 231-235: Remove the unused imported names from the provider-hook
import blocks: in the import that currently imports _has_cache_providers,
_get_cache_providers, CacheContext, CacheValue, _serialize_cache_key,
_contains_nan, _logger remove CacheContext and _serialize_cache_key so only
_has_cache_providers, _get_cache_providers, CacheValue, _contains_nan, and
_logger remain; likewise remove CacheContext from the later import block (the
one around line ~270) so it does not get imported where unused. Keep the other
symbols (_has_cache_providers, _get_cache_providers, CacheValue, _contains_nan,
_logger) intact and rerun CI/lint to confirm F401 is resolved.
- Around line 212-223: The code calls self._check_providers_lookup on every
local cache miss (in _get_immediate), causing unnecessary external lookups for
non-output caches like caches.objects; restrict external provider checks to
output-value keys only by guarding the call with a check against the cache-key
type from cache_key_set (e.g., use a method such as
cache_key_set.is_output_key(node_id) or cache_key_set.is_output(cache_key) if
available) so that _check_providers_lookup(cache_key) is invoked only when the
key represents an output value; apply the same guard to the other affected block
(lines ~268-305) that currently triggers provider lookups on non-output misses.
In `@tests-unit/execution_test/test_cache_provider.py`:
- Around line 135-174: Tests assume serialize_cache_key returns raw SHA256 bytes
but the cache-provider contract returns a hex string; update assertions in
test_returns_bytes and test_dict_in_cache_key (and similar locations) to assert
isinstance(result, str) and len(result) == 64 (SHA256 hex length). Replace any
uses of non-existent CacheContext fields cache_key or cache_key_bytes with
cache_key_hash when constructing CacheContext instances (refer to CacheContext).
Finally, update tests that mock provider methods to follow the provider's async
signatures (use async def test helpers and await the provider methods or return
awaitable mocks) so they match the async method shape used by the provider
interface.
ℹ️ Review info
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (5)
comfy_api/latest/__init__.pycomfy_execution/cache_provider.pycomfy_execution/caching.pyexecution.pytests-unit/execution_test/test_cache_provider.py
- Remove unused CacheContext and _serialize_cache_key imports from caching.py (now handled by _build_context helper) - Update test_cache_provider.py to use _-prefixed internal names - Update tests for new CacheContext.cache_key_hash field (str) - Make MockCacheProvider methods async to match ABC Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Make all docstrings and comments generic for the OSS codebase. Remove references to Kubernetes, Redis, GCS, pods, and other infrastructure-specific terminology. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Strip verbose docstrings and section banners to match existing minimal documentation style used throughout the codebase. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add docstring with usage example to Caching class matching the convention used by sibling APIs (Execution.set_progress, ComfyExtension) - Remove non-deterministic pickle fallback from _serialize_cache_key; return None on JSON failure instead of producing unretrievable hashes - Move cache_provider imports to top of execution.py (no circular dep) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Address review feedback: - Move CacheProvider/CacheContext/CacheValue definitions to comfy_api/latest/_caching.py (source of truth for public API) - comfy_execution/cache_provider.py re-exports types from there - Build _providers_snapshot eagerly on register/unregister instead of lazy memoization in _get_cache_providers Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Address review feedback from guill: - Rename _contains_nan to _contains_self_unequal, use not (x == x) instead of math.isnan to catch any self-unequal value - Remove Unhashable and repr() fallbacks from _canonicalize; raise ValueError for unknown types so _serialize_cache_key returns None and external caching is skipped (fail-closed) - Update tests for renamed function and new fail-closed behavior Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
CacheContext is imported from _caching and re-exported for use by caching.py. Add noqa comment to satisfy the linter. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Subcache nodes (from node expansion) now participate in external provider store/lookup. Previously skipped to avoid duplicates, but the cost of missing partial-expansion cache hits outweighs redundant stores — especially with looping behavior on the horizon. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
comfy_api/latest/__init__.py
Outdated
| register_cache_provider as register_provider, | ||
| unregister_cache_provider as unregister_provider, |
There was a problem hiding this comment.
We should define these as small wrappers here rather than just importing them. As-is, someone could add/remove a param from register_provider and not realize that it'll be breaking the public API.
Define register_provider and unregister_provider as wrapper functions in the Caching class instead of re-importing. This locks the public API signature in comfy_api/ so internal changes can't accidentally break it. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
comfy_api/latest/__init__.py
Outdated
| from ._caching import CacheProvider, CacheContext, CacheValue | ||
|
|
||
| @staticmethod | ||
| def register_provider(provider: "Caching.CacheProvider") -> None: |
There was a problem hiding this comment.
Please follow the pattern of class Execution or class NodeReplacement in this file. To work with both process isolation and our versioning system:
- This class must inherit from
ProxiedSingleton. - The functions should be defined with this as a singleton (i.e. not staticmethods).
- The functions should be defined as async. (People can get an automatically converted non-async version by importing ComfyAPISync.)
comfy_execution/cache_provider.py
Outdated
| return | ||
| _providers.append(provider) | ||
| _providers_snapshot = tuple(_providers) | ||
| _logger.info(f"Registered cache provider: {provider.__class__.__name__}") |
There was a problem hiding this comment.
nit: Should this be a debug-level log line?
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add Caching as a nested class inside ComfyAPI_latest inheriting from ProxiedSingleton with async instance methods, matching the Execution and NodeReplacement patterns. Retains standalone Caching class for direct import convenience. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Follow the Execution/NodeReplacement pattern — the public API methods contain the actual logic operating on cache_provider module state, not wrapper functions delegating to free functions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove duplicate standalone Caching class. Define it once as a nested class in ComfyAPI_latest (matching Execution/NodeReplacement pattern), with a module-level alias for import convenience. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
comfy_api/latest/_caching.py
Outdated
|
|
||
| @dataclass | ||
| class CacheContext: | ||
| prompt_id: str |
There was a problem hiding this comment.
Why do we need the prompt_id in the CacheContext? It seems like we might be able to simplify some things (e.g. storing the prompt id in the caches themselves) if we remove this. It also seems like we wouldn't want to care about the prompt id when determining caching (since the whole point of caching is to cache across different prompt ids).
Remove prompt_id from CacheContext — it's not relevant for cache matching and added unnecessary plumbing (_current_prompt_id on every cache). Lifecycle hooks still receive prompt_id directly. Include type name in canonicalized primitives so that int 7 and str "7" produce distinct hashes. Also canonicalize dict keys properly instead of str() coercion. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Summary
Adds a public
CacheProviderAPI that enables external cache providers to integrate with ComfyUI's caching system. This allows distributed caching across multiple ComfyUI instances (e.g., Kubernetes pods) without monkey-patching internal methods.Key changes:
comfy_execution/cache_provider.pymodule with public API:CacheProviderabstract base class withon_lookup,on_store,should_cachemethodsCacheContextandCacheValuedataclasses for type-safe data passingregister_cache_provider,get_cache_providers, etc.)serialize_cache_key,contains_nan,estimate_value_sizecomfy_execution/caching.pyto call registered providers on cache miss/storeexecution.pyto notify providers on prompt start/endWhy this matters:
Test plan
tests-unit/execution_test/test_cache_provider.py_canonicalizedeterministic orderingserialize_cache_keyhash consistencycontains_nandetectionestimate_value_size🤖 Generated with Claude Code