Skip to content

Add score-based cache eviction - #15396

Open
iamhaseebn wants to merge 3 commits into
Comfy-Org:masterfrom
iamhaseebn:fix-score-based-cache
Open

Add score-based cache eviction#15396
iamhaseebn wants to merge 3 commits into
Comfy-Org:masterfrom
iamhaseebn:fix-score-based-cache

Conversation

@iamhaseebn

Copy link
Copy Markdown

Summary

This adds an opt-in --cache-score [ACTIVE_GB [INACTIVE_GB]] mode that evicts cached outputs using RAM footprint relative to available memory divided by measured cold execution time. Large outputs that are cheap to recompute are evicted before smaller outputs that are expensive to rebuild.

Execution timing is preserved across normal, async, and generated-subgraph paths. Existing cache modes and the CacheEntry interface remain unchanged.

Testing

  • 1,130 unit tests passed with 10 skips
  • 259 execution tests passed across classic, LRU, score, no-cache, and async configurations
  • Focused parallel timing checks passed
  • Ruff passed on all changed files
  • CLI validation and cache-mode mutual exclusion checks passed

Closes #8367

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

✅ All contributors have signed the CLA. Thank you! This PR is ready to be merged.
Posted by the CLA Assistant Lite bot.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Team

Run ID: 2668c716-36b6-431b-b146-c300860d0894

📥 Commits

Reviewing files that changed from the base of the PR and between cb8729a and b655ea7.

📒 Files selected for processing (5)
  • comfy/cli_args.py
  • comfy_execution/caching.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (7)
Execution engine (graph execution, caching, jobs). Focus on:

⚙️ CodeRabbit configuration file

Files:

  • comfy_execution/caching.py
Core ML/diffusion engine. Focus on:

⚙️ CodeRabbit configuration file

Files:

  • comfy/cli_args.py
IMPORTANT: Only comment on issues directly introduced by this PR's code changes.

⚙️ CodeRabbit configuration file

Files:

  • comfy/cli_args.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • comfy_execution/caching.py
Treat legacy combo, `io.Combo`, and `io.DynamicCombo` values affecting filesystem access as untrusted; revalidate them at load/save boundaries with `folder_paths`, containment checks, or fixed allowlists.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • comfy/cli_args.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • comfy_execution/caching.py
Keep state and capability flags on the object that owns the behavior. Prefer explicit parent-owned attributes over probing child objects with `getattr`; use child checks only when the child owns the delegated behavior.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • comfy/cli_args.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • comfy_execution/caching.py
Keep changes small, direct, and limited to the narrowest necessary code path and smallest number of files.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • comfy/cli_args.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • comfy_execution/caching.py
Keep warning and info messages short and actionable, remove noisy or misleading logging, and make documentation edits concise, factual, and tied to changed behavior.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • comfy/cli_args.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • comfy_execution/caching.py
🪛 ast-grep (0.45.2)
execution.py

[warning] 744-858: Do not use an empty list as a default parameter
Context: async def execute_async(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
set_preview_method(extra_data.get("preview_method"))

    nodes.interrupt_processing(False)
    self.prompt_model_tracker.start()

    if "client_id" in extra_data:
        self.server.client_id = extra_data["client_id"]
    else:
        self.server.client_id = None

    self.status_messages = []
    self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)

    self._notify_prompt_lifecycle("start", prompt_id)
    ram_headroom = int(self.cache_args["ram"] * (1024 ** 3))
    ram_inactive_headroom = int(self.cache_args["ram_inactive"] * (1024 ** 3))
    ram_release_callback = self.caches.outputs.ram_release if self.cache_type in (CacheType.RAM_PRESSURE, CacheType.SCORE) else None
    comfy.memory_management.set_ram_cache_release_state(ram_release_callback, ram_headroom)

    try:
        with torch.inference_mode():
            dynamic_prompt = DynamicPrompt(prompt)
            reset_progress_state(prompt_id, dynamic_prompt)
            add_progress_handler(WebUIProgressHandler(self.server))
            is_changed_cache = IsChangedCache(prompt_id, dynamic_prompt, self.caches.outputs)
            for cache in self.caches.all:
                await cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache)
                cache.clean_unused()

            node_ids = list(prompt.keys())
            cache_results = await asyncio.gather(
                *(self.caches.outputs.get(node_id) for node_id in node_ids)
            )
            cached_nodes = [
                node_id for node_id, result in zip(node_ids, cache_results)
                if result is not None
            ]

            comfy.model_management.cleanup_models_gc()
            self.add_message("execution_cached",
                          { "nodes": cached_nodes, "prompt_id": prompt_id},
                          broadcast=False)
            pending_subgraph_results = {}
            pending_async_nodes = {} # TODO - Unify this with pending_subgraph_results
            execution_start_times = {}
            ui_node_outputs = {}
            executed = set()
            execution_list = ExecutionList(dynamic_prompt, self.caches.outputs, self.prompt_model_tracker.add)
            current_outputs = self.caches.outputs.all_node_ids()
            for node_id in list(execute_outputs):
                execution_list.add_node(node_id)

            while not execution_list.is_empty():
                node_id, error, ex = await execution_list.stage_node_execution()
                if error is not None:
                    self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
                    break

                assert node_id is not None, "Node ID should not be None at this point"
                result, error, ex = await execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results, pending_async_nodes, execution_start_times, ui_node_outputs)
                self.success = result != ExecutionResult.FAILURE
                if result == ExecutionResult.FAILURE:
                    self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
                    break
                elif result == ExecutionResult.PENDING:
                    execution_list.unstage_node_execution()
                else: # result == ExecutionResult.SUCCESS:
                    execution_list.complete_node_execution()

                if self.cache_type in (CacheType.RAM_PRESSURE, CacheType.SCORE):
                    ram_release_callback(ram_inactive_headroom)
                    ram_shortfall = ram_headroom - comfy.system_memory.virtual_memory_available()
                    if ram_shortfall > 0:
                        freed = ram_release_callback(ram_headroom, free_active=True, min_entry_size=RAM_CACHE_LARGE_INTERMEDIATE)
                        ram_shortfall -= freed
                    if comfy.model_management.should_free_pins_for_ram_pressure(ram_shortfall):
                        freed = comfy.model_management.free_pins(ram_shortfall + 512 * (1024 ** 2))
                        if freed < ram_shortfall:
                            if freed > 64 * (1024 ** 2):
                                # AIMDO MEM_DECOMMIT can outrun psutil.available catching up.
                                time.sleep(0.05)
                            ram_release_callback(ram_headroom, free_active=True)
            else:
                # Only execute when the while-loop ends without break
                # Send cached UI for intermediate output nodes that weren't executed
                for node_id in dynamic_prompt.all_node_ids():
                    if node_id in executed:
                        continue
                    if not _is_intermediate_output(dynamic_prompt, node_id):
                        continue
                    cached = await self.caches.outputs.get(node_id)
                    if cached is not None:
                        display_node_id = dynamic_prompt.get_display_node_id(node_id)
                        _send_cached_ui(self.server, node_id, display_node_id, cached, prompt_id, ui_node_outputs)
                self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)

            ui_outputs = {}
            meta_outputs = {}
            for node_id, ui_info in ui_node_outputs.items():
                ui_outputs[node_id] = ui_info["output"]
                meta_outputs[node_id] = ui_info["meta"]
            self.history_result = {
                "outputs": ui_outputs,
                "meta": meta_outputs,
            }
            self.server.last_node_id = None
            if comfy.model_management.DISABLE_SMART_MEMORY:
                comfy.model_management.unload_all_models()
    finally:
        if self.cache_type == CacheType.RAM_PRESSURE:
            detail("RAM cache evictions: prompt=%s active=%s full=%s", prompt_id, self.caches.outputs.active_evictions, self.caches.outputs.full_evictions)
        comfy.memory_management.set_ram_cache_release_state(None, 0)
        self.prompt_model_tracker.end()
        self._notify_prompt_lifecycle("end", prompt_id)

Note: [CWE-710] Improper Adherence to Coding Standards (mutable default argument).

(no-empty-list-as-parameter)

🔇 Additional comments (5)
comfy/cli_args.py (1)

78-78: LGTM!

Also applies to: 154-154, 185-185, 273-273

main.py (1)

44-44: LGTM!

Also applies to: 46-52, 87-87, 96-98, 263-269, 272-274, 599-600, 602-608

comfy_execution/caching.py (1)

590-590: LGTM!

Also applies to: 604-604, 628-628, 641-641

execution.py (1)

20-20: LGTM!

Also applies to: 34-34, 115-115, 127-129, 152-155, 447-447, 553-553, 625-633, 643-643, 762-762, 790-790, 805-805, 815-815

tests-unit/execution_test/caching_test.py (1)

21-21: LGTM!


📝 Walkthrough

Walkthrough

The PR adds the --cache-score option with up to two RAM headroom thresholds. It introduces ScoreCache, which ranks eviction candidates using memory pressure and execution time. Execution records node durations and updates score-cache metadata. Cache setup and RAM-release handling support the new cache mode. Unit and execution tests cover score-based, RAM-pressure, asynchronous, and configured server behavior.

Merge Risk: ⚪ Minimal · up to b655e

The PR adds an opt-in cache eviction mode while preserving existing cache interfaces and modes; no actionable merge-blocking risk remains based on the supplied evidence.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: score-based cache eviction.
Description check ✅ Passed The description directly explains the new --cache-score mode, eviction behavior, execution timing, and testing.
Linked Issues check ✅ Passed The changes implement issue #8367: a score-based cache algorithm using execution time and relative memory size, with a new command-line option alongside existing cache modes.
Out of Scope Changes check ✅ Passed The changes remain within scope. They add score-based caching, CLI validation, execution-time tracking, and related tests without unrelated code changes.
  • Fix all pre-merge checks with AI

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@comfy/cli_args.py`:
- Around line 283-284: Update the --cache-score validation in the CLI argument
parsing flow to reject any threshold that is non-finite or negative, while
preserving the existing maximum-two-values check. Validate both active and
inactive GB values before execution.py converts them, and report invalid input
through parser.error with clear guidance.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5b191b51-cd77-4d67-9d04-dd51bd1fea01

📥 Commits

Reviewing files that changed from the base of the PR and between 531ea7d and 8b291c9.

📒 Files selected for processing (7)
  • comfy/cli_args.py
  • comfy_execution/caching.py
  • execution.py
  • main.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • tests/execution/test_execution.py
📜 Review details
⚠️ CI failures not shown inline (2)

GitHub Actions: CLA Assistant / cla-assistant: Add score-based cache eviction

Conclusion: failure

View job details

##[group]Run contributor-assistant/github-action@ca4a40a7d1004f18d9960b404b97e5f30a505a08
 with:
   path-to-document: https://github.com/Comfy-Org/comfy-cla/blob/main/comfyui_icla.md
   remote-organization-name: comfy-org
   remote-repository-name: comfy-cla
   path-to-signatures: signatures/cla.json
   branch: main
   allowlist: action@github.com,actions-user,ampagent,claude,comfy-pr-bot,GitHub Action,github-actions,github-actions[bot],Glary Bot,Glary-Bot,*[bot]
   custom-notsigned-prcomment: 🎉 Thank you for your contribution, we really appreciate it! 🎉
Like many open source projects, we require contributors to sign our [Contributor License Agreement (CLA)](https://github.com/Comfy-Org/comfy-cla/blob/main/comfyui_icla.md). A CLA makes the ownership of contributions explicit, so contributors and the project share a clear understanding of how the code can be used. By signing, you:
- Confirm that you own your contribution.
- Keep the right to reuse your own code.
- Grant us a copyright license to include and share it within our projects.
CLAs are standard practice across major open source projects including those under the Apache Software Foundation and the Linux Foundation. Ours is based on the Apache Software Foundation's CLA. Most importantly, it would enable us to relicense the project under a more permissive license in the future, giving the project and its community greater flexibility.
✍ **To sign, please post a new comment on this PR with exactly the following text:** ✍
   custom-pr-sign-comment: I have read and agree to the Contributor License Agreement
   custom-allsigned-prcomment: ✅ All contributors have signed the CLA. Thank you! This PR is ready to be merged.
   use-dco-flag: false
   lock-pullrequest-aftermerge: true
   suggest-recheck: true
 env:
   GITHUB_***REDACTED_SECRET_ASSIGNMENT***
   PERSONAL_ACCESS_***REDACTED_SECRET_ASSIGNMENT***
 ##[endgroup]
 CLA Assistant GitHub Action bot has started the process
 (node:2123) [DEP0040] DeprecationWarn...

GitHub Actions: CLA Assistant / 0_cla-assistant.txt: Add score-based cache eviction

Conclusion: failure

View job details

##[group]Run contributor-assistant/github-action@ca4a40a7d1004f18d9960b404b97e5f30a505a08
 with:
   path-to-document: https://github.com/Comfy-Org/comfy-cla/blob/main/comfyui_icla.md
   remote-organization-name: comfy-org
   remote-repository-name: comfy-cla
   path-to-signatures: signatures/cla.json
   branch: main
   allowlist: action@github.com,actions-user,ampagent,claude,comfy-pr-bot,GitHub Action,github-actions,github-actions[bot],Glary Bot,Glary-Bot,*[bot]
   custom-notsigned-prcomment: 🎉 Thank you for your contribution, we really appreciate it! 🎉
Like many open source projects, we require contributors to sign our [Contributor License Agreement (CLA)](https://github.com/Comfy-Org/comfy-cla/blob/main/comfyui_icla.md). A CLA makes the ownership of contributions explicit, so contributors and the project share a clear understanding of how the code can be used. By signing, you:
- Confirm that you own your contribution.
- Keep the right to reuse your own code.
- Grant us a copyright license to include and share it within our projects.
CLAs are standard practice across major open source projects including those under the Apache Software Foundation and the Linux Foundation. Ours is based on the Apache Software Foundation's CLA. Most importantly, it would enable us to relicense the project under a more permissive license in the future, giving the project and its community greater flexibility.
✍ **To sign, please post a new comment on this PR with exactly the following text:** ✍
   custom-pr-sign-comment: I have read and agree to the Contributor License Agreement
   custom-allsigned-prcomment: ✅ All contributors have signed the CLA. Thank you! This PR is ready to be merged.
   use-dco-flag: false
   lock-pullrequest-aftermerge: true
   suggest-recheck: true
 env:
   GITHUB_***REDACTED_SECRET_ASSIGNMENT***
   PERSONAL_ACCESS_***REDACTED_SECRET_ASSIGNMENT***
 ##[endgroup]
 CLA Assistant GitHub Action bot has started the process
 (node:2123) [DEP0040] DeprecationWarn...
🧰 Additional context used
📓 Path-based instructions (7)
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Keep changes small, direct, and limited to the narrowest necessary code path and smallest number of files.
Prefer practical fixes, minimal dependencies, and existing repository patterns; remove obsolete, dead, unreachable, or unused code.
Preserve existing APIs, node names, model-loading behavior, file layout, and workflow compatibility unless replacement is explicitly intended.
Core ComfyUI must not add outbound internet requests, telemetry, tracking, reporting, remote configuration, or background network activity. User-authorized model downloads are limited to the requested artifact and must exclude telemetry and unrelated metadata.

Files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Keep state and capability flags on the object that owns the behavior. Prefer explicit parent-owned attributes over probing child objects with getattr; use child checks only when the child owns the delegated behavior.
Preserve shared method signatures, argument order, return shapes, side effects, and error behavior unless every affected caller and interface is intentionally updated.
Do not add unused compatibility parameters, flags, attributes, constructor options, or model-specific options to shared helpers; keep one-off behavior at the integration boundary.
Normalize third-party return conventions at integration boundaries so core code receives the expected type and shape; avoid undocumented caller-side unwrapping.
Do not add torch.no_grad, torch.inference_mode, or inference-mode wrappers. Do not add model freeze/unfreeze toggles; only disable globally enabled inference mode when a training path requires gradients.
Remove inference-only training behavior such as dropout while preserving checkpoint and state-dict compatibility; use nn.Identity when deleting a module would alter keys or ordering.
Keep imports at module scope except established optional-backend probes or imports required to avoid cycles; avoid unnecessary try/except blocks and use specific exceptions with useful fallbacks.
Do not add workarounds for unsupported library versions, especially PyTorch exception-and-float-cast retries, unless a comment names the exact versions still requiring them.
Let unsupported model formats, invalid quantization metadata, and bad states fail with clear errors instead of silently degrading output.
Match local style, keep comments sparse and useful, and remove comments that merely restate obvious code.
Treat dtype, device placement, VRAM use, and offloading as correctness concerns across CPU, CUDA, ROCm, MPS, DirectML, XPU, NPU, and low-VRAM environments.
Prefer existing ComfyUI and Comfy Kitchen operations, quantization helpers, cast/offload helpe...

Files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
**/*.{py,json}

📄 CodeRabbit inference engine (AGENTS.md)

Treat legacy combo, io.Combo, and io.DynamicCombo values affecting filesystem access as untrusted; revalidate them at load/save boundaries with folder_paths, containment checks, or fixed allowlists.

Files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
**/*.{py,md,txt,json}

📄 CodeRabbit inference engine (AGENTS.md)

Keep warning and info messages short and actionable, remove noisy or misleading logging, and make documentation edits concise, factual, and tied to changed behavior.

Files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
**

⚙️ CodeRabbit configuration file

**: IMPORTANT: Only comment on issues directly introduced by this PR's code changes.
Treat AGENTS.md as mandatory repository policy, not optional style guidance.
Flag PR changes that violate AGENTS.md even when the code is otherwise functional.
In particular, enforce architecture boundaries, dtype/device/memory rules,
interface contracts, import style, no unnecessary try/except blocks, no inline
imports, no outbound internet paths in core ComfyUI, and narrow scoped fixes.
Prefer direct findings over suggestions when a rule is violated. Only ignore
AGENTS.md when it clearly conflicts with a newer explicit maintainer instruction
in the PR.
Do NOT flag pre-existing issues in code that was merely moved, re-indented,
de-indented, or reformatted without logic changes. If code appears in the diff
only due to whitespace or structural reformatting (e.g., removing a with: block),
treat it as unchanged. Contributors should not feel obligated to address
pre-existing issues outside the scope of their contribution.

Files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
comfy/**

⚙️ CodeRabbit configuration file

comfy/**: Core ML/diffusion engine. Focus on:

  • Backward compatibility (breaking changes affect all custom nodes)
  • Memory management and GPU resource handling
  • Performance implications in hot paths
  • Thread safety for concurrent execution

Files:

  • comfy/cli_args.py
comfy_execution/**

⚙️ CodeRabbit configuration file

comfy_execution/**: Execution engine (graph execution, caching, jobs). Focus on:

  • Caching correctness
  • Concurrent execution safety
  • Graph validation edge cases

Files:

  • comfy_execution/caching.py
🧠 Learnings (3)
📚 Learning: 2026-02-21T14:01:41.482Z
Learnt from: pythongosssss
Repo: Comfy-Org/ComfyUI PR: 12555
File: comfy_extras/nodes_glsl.py:719-724
Timestamp: 2026-02-21T14:01:41.482Z
Learning: In PyOpenGL, bare Python scalars can be accepted for 1-element array parameters by NumberHandler. This means you can pass an int/float directly to OpenGL texture deletion (e.g., glDeleteTextures(tex)) without wrapping in a list. Verify function-specific expectations and ensure types match what the OpenGL call expects; use explicit lists only when the API requires an array.

Applied to files:

  • tests/execution/test_execution.py
  • comfy/cli_args.py
  • tests-unit/execution_test/caching_test.py
  • tests/execution/test_async_nodes.py
  • main.py
  • execution.py
  • comfy_execution/caching.py
📚 Learning: 2026-05-13T12:31:45.069Z
Learnt from: rattus128
Repo: Comfy-Org/ComfyUI PR: 13802
File: comfy/pinned_memory.py:19-30
Timestamp: 2026-05-13T12:31:45.069Z
Learning: When reviewing code that uses comfy/pinned_memory.py’s `HostBuffer.extend(size=..., reallocate=...)`: by default (`reallocate` is not True / False), `extend(size=...)` is a *relative increment* that grows the buffer by `size` bytes—so slicing like `[offset:offset+size]` after `hostbuf.extend(size=size)` is correct and the argument should not be rewritten to `offset + size`. Only in the single-segment reallocation mode (`reallocate=True`, e.g., as used by `resize_pin_buffer()` in `comfy/model_management.py`) should `size` be treated as an *absolute target* and the call/arguments should be checked accordingly.

Applied to files:

  • comfy/cli_args.py
📚 Learning: 2026-08-06T22:18:59.719Z
Learnt from: kijai
Repo: Comfy-Org/ComfyUI PR: 15362
File: comfy/ldm/wan/model_animate2.py:186-223
Timestamp: 2026-08-06T22:18:59.719Z
Learning: When reviewing ComfyUI quantization code, treat `comfy.quant_ops.TensorWiseINT8Layout` and `comfy.quant_ops.TensorCoreConvRotW4A4Layout` as re-exports from `comfy_kitchen`. Validate their behavior against the re-exported `comfy_kitchen` implementations rather than assuming they are local fallback classes.

Applied to files:

  • comfy/cli_args.py
🔇 Additional comments (7)
comfy/cli_args.py (1)

141-141: LGTM!

main.py (1)

336-340: LGTM!

Also applies to: 349-350

comfy_execution/caching.py (1)

3-3: LGTM!

Also applies to: 509-510, 553-612, 615-649

execution.py (1)

34-34: LGTM!

Also applies to: 115-115, 127-154, 447-447, 553-553, 625-643, 762-815

tests-unit/execution_test/caching_test.py (1)

8-62: LGTM!

tests/execution/test_async_nodes.py (1)

16-18: LGTM!

Also applies to: 29-29

tests/execution/test_execution.py (1)

188-188: LGTM!

Comment thread comfy/cli_args.py Outdated
@iamhaseebn

Copy link
Copy Markdown
Author

I have read and agree to the Contributor License Agreement

comfy-legal added a commit to Comfy-Org/comfy-cla that referenced this pull request Aug 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@comfy/cli_args.py`:
- Around line 284-288: Update the CacheSet initialization path for
execution.CacheType.SCORE so it uses the configured score-cache implementation
instead of the no-op init_score_cache() path. Read the active and inactive
thresholds from cache_args using the ram and ram_inactive values supplied by
--cache-score, and expose the resulting ram_release value through caches.outputs
for the execution callback.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 0bb0a091-867c-4f4d-921c-9e6107ec3200

📥 Commits

Reviewing files that changed from the base of the PR and between 8b291c9 and cb8729a.

📒 Files selected for processing (2)
  • comfy/cli_args.py
  • tests-unit/comfy_test/cli_args_test.py
📜 Review details
🧰 Additional context used
📓 Path-based instructions (6)
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Keep changes small, direct, and limited to the narrowest necessary code path and smallest number of files.
Prefer practical fixes, minimal dependencies, and existing repository patterns; remove obsolete, dead, unreachable, or unused code.
Preserve existing APIs, node names, model-loading behavior, file layout, and workflow compatibility unless replacement is explicitly intended.
Core ComfyUI must not add outbound internet requests, telemetry, tracking, reporting, remote configuration, or background network activity. User-authorized model downloads are limited to the requested artifact and must exclude telemetry and unrelated metadata.

Files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Keep state and capability flags on the object that owns the behavior. Prefer explicit parent-owned attributes over probing child objects with getattr; use child checks only when the child owns the delegated behavior.
Preserve shared method signatures, argument order, return shapes, side effects, and error behavior unless every affected caller and interface is intentionally updated.
Do not add unused compatibility parameters, flags, attributes, constructor options, or model-specific options to shared helpers; keep one-off behavior at the integration boundary.
Normalize third-party return conventions at integration boundaries so core code receives the expected type and shape; avoid undocumented caller-side unwrapping.
Do not add torch.no_grad, torch.inference_mode, or inference-mode wrappers. Do not add model freeze/unfreeze toggles; only disable globally enabled inference mode when a training path requires gradients.
Remove inference-only training behavior such as dropout while preserving checkpoint and state-dict compatibility; use nn.Identity when deleting a module would alter keys or ordering.
Keep imports at module scope except established optional-backend probes or imports required to avoid cycles; avoid unnecessary try/except blocks and use specific exceptions with useful fallbacks.
Do not add workarounds for unsupported library versions, especially PyTorch exception-and-float-cast retries, unless a comment names the exact versions still requiring them.
Let unsupported model formats, invalid quantization metadata, and bad states fail with clear errors instead of silently degrading output.
Match local style, keep comments sparse and useful, and remove comments that merely restate obvious code.
Treat dtype, device placement, VRAM use, and offloading as correctness concerns across CPU, CUDA, ROCm, MPS, DirectML, XPU, NPU, and low-VRAM environments.
Prefer existing ComfyUI and Comfy Kitchen operations, quantization helpers, cast/offload helpe...

Files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
**/*.{py,json}

📄 CodeRabbit inference engine (AGENTS.md)

Treat legacy combo, io.Combo, and io.DynamicCombo values affecting filesystem access as untrusted; revalidate them at load/save boundaries with folder_paths, containment checks, or fixed allowlists.

Files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
**/*.{py,md,txt,json}

📄 CodeRabbit inference engine (AGENTS.md)

Keep warning and info messages short and actionable, remove noisy or misleading logging, and make documentation edits concise, factual, and tied to changed behavior.

Files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
**

⚙️ CodeRabbit configuration file

**: IMPORTANT: Only comment on issues directly introduced by this PR's code changes.
Treat AGENTS.md as mandatory repository policy, not optional style guidance.
Flag PR changes that violate AGENTS.md even when the code is otherwise functional.
In particular, enforce architecture boundaries, dtype/device/memory rules,
interface contracts, import style, no unnecessary try/except blocks, no inline
imports, no outbound internet paths in core ComfyUI, and narrow scoped fixes.
Prefer direct findings over suggestions when a rule is violated. Only ignore
AGENTS.md when it clearly conflicts with a newer explicit maintainer instruction
in the PR.
Do NOT flag pre-existing issues in code that was merely moved, re-indented,
de-indented, or reformatted without logic changes. If code appears in the diff
only due to whitespace or structural reformatting (e.g., removing a with: block),
treat it as unchanged. Contributors should not feel obligated to address
pre-existing issues outside the scope of their contribution.

Files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
comfy/**

⚙️ CodeRabbit configuration file

comfy/**: Core ML/diffusion engine. Focus on:

  • Backward compatibility (breaking changes affect all custom nodes)
  • Memory management and GPU resource handling
  • Performance implications in hot paths
  • Thread safety for concurrent execution

Files:

  • comfy/cli_args.py
🧠 Learnings (3)
📚 Learning: 2026-02-21T14:01:41.482Z
Learnt from: pythongosssss
Repo: Comfy-Org/ComfyUI PR: 12555
File: comfy_extras/nodes_glsl.py:719-724
Timestamp: 2026-02-21T14:01:41.482Z
Learning: In PyOpenGL, bare Python scalars can be accepted for 1-element array parameters by NumberHandler. This means you can pass an int/float directly to OpenGL texture deletion (e.g., glDeleteTextures(tex)) without wrapping in a list. Verify function-specific expectations and ensure types match what the OpenGL call expects; use explicit lists only when the API requires an array.

Applied to files:

  • tests-unit/comfy_test/cli_args_test.py
  • comfy/cli_args.py
📚 Learning: 2026-05-13T12:31:45.069Z
Learnt from: rattus128
Repo: Comfy-Org/ComfyUI PR: 13802
File: comfy/pinned_memory.py:19-30
Timestamp: 2026-05-13T12:31:45.069Z
Learning: When reviewing code that uses comfy/pinned_memory.py’s `HostBuffer.extend(size=..., reallocate=...)`: by default (`reallocate` is not True / False), `extend(size=...)` is a *relative increment* that grows the buffer by `size` bytes—so slicing like `[offset:offset+size]` after `hostbuf.extend(size=size)` is correct and the argument should not be rewritten to `offset + size`. Only in the single-segment reallocation mode (`reallocate=True`, e.g., as used by `resize_pin_buffer()` in `comfy/model_management.py`) should `size` be treated as an *absolute target* and the call/arguments should be checked accordingly.

Applied to files:

  • comfy/cli_args.py
📚 Learning: 2026-08-06T22:18:59.719Z
Learnt from: kijai
Repo: Comfy-Org/ComfyUI PR: 15362
File: comfy/ldm/wan/model_animate2.py:186-223
Timestamp: 2026-08-06T22:18:59.719Z
Learning: When reviewing ComfyUI quantization code, treat `comfy.quant_ops.TensorWiseINT8Layout` and `comfy.quant_ops.TensorCoreConvRotW4A4Layout` as re-exports from `comfy_kitchen`. Validate their behavior against the re-exported `comfy_kitchen` implementations rather than assuming they are local fallback classes.

Applied to files:

  • comfy/cli_args.py
🪛 ast-grep (0.45.0)
tests-unit/comfy_test/cli_args_test.py

[error] 20-22: Command coming from incoming request
Context: subprocess.run(
[sys.executable, "-c", PARSE_ARGS, *arguments], capture_output=True, text=True
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(subprocess-from-request)


[error] 29-33: Command coming from incoming request
Context: subprocess.run(
[sys.executable, "-c", PARSE_ARGS, "--cache-score", "1", "2", "3"],
capture_output=True,
text=True,
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(subprocess-from-request)


[error] 44-48: Command coming from incoming request
Context: subprocess.run(
[sys.executable, "-c", PARSE_ARGS, "--cache-score", *values],
capture_output=True,
text=True,
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(subprocess-from-request)

🔇 Additional comments (2)
tests-unit/comfy_test/cli_args_test.py (1)

1-51: LGTM!

comfy/cli_args.py (1)

3-3: LGTM!

Also applies to: 142-142

Comment thread comfy/cli_args.py
coderabbitai[bot]
coderabbitai Bot previously approved these changes Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Create caching option that organizes cache based on loading times of cached values

1 participant