Repository navigation
Fix: ValueError: Operation on closed image - #16697
Conversation
📝 WalkthroughWalkthroughThe image2id function in rag/utils/base64_image.py was refactored to pop the "image" field from the input dict before encoding, replacing the prior BytesIO-based encoding with a new encode_image implementation that produces JPEG bytes and tracks owned PIL images for cleanup in a finally block. ChangesImage Encoding Rewrite
Estimated code review effort: 3 (Moderate) | ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
wangq8
left a comment
There was a problem hiding this comment.
Review: Fix ValueError: Operation on closed image
PR #16697 | bugfix/fix-Operation-on-closed-image -> main | +24/-32 (1 file)
What changed
A focused refactor of encode_image() inside image2id in rag/utils/base64_image.py, and reordering of the image lifecycle.
Key analysis
-
Root cause & fix are correct
The ValueError: Operation on closed image occurs when PIL's save() or convert() is called on an image whose underlying data has been freed. The original code would call orig_img.close() before the save operation when the image was RGBA/P mode. If the converted image shared pixel data with the palette-based original (P-mode), the save would fail with Operation on closed image.
The fix applies img.load() before any conversion. This eagerly decodes pixels into memory, breaking the data-sharing link with the original. Both the original and converted images are tracked in owned_images and closed together in finally. This correctly prevents the race/ordering issue.
-
Pop early pattern
Moving image = d.pop("image") to the top removes the image reference from the dict immediately, so async continuation has no stale dict access. The old pattern of deleting it at two separate points is consolidated.
-
Cleaner bytes path
When open_image_for_processing returns bytes, returning bytes(img) avoids the unnecessary BytesIO round-trip. Good micro-optimisation.
-
Exception coverage
except (OSError, ValueError) catches both OSError (PIL save failures) and ValueError (the closed-image error itself as a fallback).
Potential concern (minor)
Edge case: open_image_for_processing throws. If this function raises an exception after image = d.pop("image") has already run, but before owned_images is populated, the raw image value is never closed. In practice open_image_for_processing handles its own cleanup on failure, so this is low risk. Worth a quick check.
Verdict
LGTM, good fix. Clean, minimal, and addresses the exact bug pattern.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@rag/utils/base64_image.py`:
- Line 43: The base64 image encoding path in the image helper drops the original
image field and can return a payload with neither image nor img_id when encoding
fails. Update the failure branch in the base64 image utility so the dictionary
always preserves the img_id contract by setting an explicit empty img_id before
returning, and make sure the upload path that appends the record to MinIO relies
on that field consistently.
- Around line 69-73: The cleanup loop in base64_image.py swallows all exceptions
with a bare `except Exception: pass`, which Ruff flags and also hides failures.
Update the owned image cleanup path in the `owned_images` loop to either log the
exception at debug level using the module logger or add an explicit lint
suppression if this broad guard is intentional; keep the change localized to the
`owned_img.close()` handling.
- Around line 46-49: The image conversion flow in
open_image_for_processing/jpeg_binary is bypassing JPEG encoding for raw bytes
because allow_bytes is set to false, and bytearray inputs can also fall through
incorrectly. Update the call site so raw image bytes are accepted and routed
through the same processing path as other inputs, ensuring jpeg_binary always
returns JPEG-encoded output; use the open_image_for_processing and jpeg_binary
symbols to locate the fix.
🪄 Autofix (Beta)
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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b5fa2b76-e46c-42e1-8d5b-c253a84659eb
📒 Files selected for processing (1)
rag/utils/base64_image.py
| del d["image"] | ||
| return | ||
|
|
||
| image = d.pop("image") |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve the img_id contract when encoding fails.
After Line 43 removes image, Lines 76-77 can return with neither image nor img_id; upload_to_minio then appends this dict, and the API exposes img_id as image_id. Set an explicit empty img_id on encode failure.
Proposed fix
jpeg_binary = await thread_pool_exec(encode_image)
if jpeg_binary is None:
+ d["img_id"] = ""
returnAs per coding guidelines, rag/**/*.py: Keep ingestion, retrieval, LLM integration, and graph RAG logic in the rag/ tree aligned with the current backend architecture.
Also applies to: 75-77
🤖 Prompt for 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.
In `@rag/utils/base64_image.py` at line 43, The base64 image encoding path in the
image helper drops the original image field and can return a payload with
neither image nor img_id when encoding fails. Update the failure branch in the
base64 image utility so the dictionary always preserves the img_id contract by
setting an explicit empty img_id before returning, and make sure the upload path
that appends the record to MinIO relies on that field consistently.
Source: Coding guidelines
| img, close_after = open_image_for_processing(image, allow_bytes=False) | ||
|
|
||
| if isinstance(img, bytes): | ||
| buf.write(img) | ||
| buf.seek(0) | ||
| return buf.getvalue() | ||
| if isinstance(img, bytes): | ||
| return bytes(img) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
ast-grep outline rag/utils/base64_image.py --view expandedRepository: infiniflow/ragflow
Length of output: 905
🏁 Script executed:
rg -n "def open_image_for_processing|open_image_for_processing\(" rag -SRepository: infiniflow/ragflow
Length of output: 350
🏁 Script executed:
sed -n '1,220p' rag/utils/base64_image.pyRepository: infiniflow/ragflow
Length of output: 4422
🏁 Script executed:
sed -n '1,220p' rag/utils/lazy_image.pyRepository: infiniflow/ragflow
Length of output: 3567
rag/utils/base64_image.py:46-49 — Decode raw image bytes before JPEG encoding. allow_bytes=False lets bytes bypass the JPEG save path and makes bytearray return None; pass allow_bytes=True so both go through open_image_for_processing() and jpeg_binary is always JPEG-encoded.
🤖 Prompt for 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.
In `@rag/utils/base64_image.py` around lines 46 - 49, The image conversion flow in
open_image_for_processing/jpeg_binary is bypassing JPEG encoding for raw bytes
because allow_bytes is set to false, and bytearray inputs can also fall through
incorrectly. Update the call site so raw image bytes are accepted and routed
through the same processing path as other inputs, ensuring jpeg_binary always
returns JPEG-encoded output; use the open_image_for_processing and jpeg_binary
symbols to locate the fix.
| for owned_img in owned_images: | ||
| try: | ||
| owned_img.close() | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Log cleanup failures or suppress the linter intentionally.
Ruff flags this new except Exception: pass path. Log at debug level and add an explicit suppression if the broad cleanup guard is intentional.
Proposed fix
- except Exception:
- pass
+ except Exception as e: # noqa: BLE001 - cleanup must not mask encode failures
+ logging.debug("Failed to close owned image: %s", e, exc_info=True)As per coding guidelines, **/*.py: Add logging for new flows.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for owned_img in owned_images: | |
| try: | |
| owned_img.close() | |
| except Exception: | |
| pass | |
| for owned_img in owned_images: | |
| try: | |
| owned_img.close() | |
| except Exception as e: # noqa: BLE001 - cleanup must not mask encode failures | |
| logging.debug("Failed to close owned image: %s", e, exc_info=True) |
🧰 Tools
🪛 Ruff (0.15.20)
[error] 72-73: try-except-pass detected, consider logging the exception
(S110)
[warning] 72-72: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for 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.
In `@rag/utils/base64_image.py` around lines 69 - 73, The cleanup loop in
base64_image.py swallows all exceptions with a bare `except Exception: pass`,
which Ruff flags and also hides failures. Update the owned image cleanup path in
the `owned_images` loop to either log the exception at debug level using the
module logger or add an explicit lint suppression if this broad guard is
intentional; keep the change localized to the `owned_img.close()` handling.
Sources: Coding guidelines, Linters/SAST tools
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16697 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
No description provided.