Skip to content

Fix: ValueError: Operation on closed image - #16697

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-Operation-on-closed-image
Jul 7, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-Operation-on-closed-image

Conversation

@wangq8

@wangq8 wangq8 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

@wangq8 wangq8 added the ci Continue Integration label Jul 7, 2026
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Image Encoding Rewrite

Layer / File(s) Summary
Encoding and cleanup rewrite
rag/utils/base64_image.py
image2id pops "image" from the dict upfront; encode_image is rewritten to handle bytes passthrough, non-PIL, and PIL-to-RGB conversion cases, tracking owned images closed via finally; post-upload logic now only sets d["img_id"] without prior explicit cleanup branch.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Poem

A rabbit hopped through bytes of light,
Closing images, day and night,
No more leaks in memory's den,
JPEG bytes flow clean again,
Hop, hop, hooray for tidy code! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing the required Summary section and provides no context or problem statement. Add a ### Summary section describing the bug, why it happened, and the intended fix or background context.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main fix: preventing the closed-image ValueError during image upload/encoding.

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.

❤️ Share

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

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. 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.

  2. 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.

  3. Cleaner bytes path

    When open_image_for_processing returns bytes, returning bytes(img) avoids the unnecessary BytesIO round-trip. Good micro-optimisation.

  4. 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9eba452 and dd39c37.

📒 Files selected for processing (1)
  • rag/utils/base64_image.py

Comment thread rag/utils/base64_image.py
del d["image"]
return

image = d.pop("image")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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"] = ""
         return

As 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

Comment thread rag/utils/base64_image.py
Comment on lines +46 to +49
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

ast-grep outline rag/utils/base64_image.py --view expanded

Repository: infiniflow/ragflow

Length of output: 905


🏁 Script executed:

rg -n "def open_image_for_processing|open_image_for_processing\(" rag -S

Repository: infiniflow/ragflow

Length of output: 350


🏁 Script executed:

sed -n '1,220p' rag/utils/base64_image.py

Repository: infiniflow/ragflow

Length of output: 4422


🏁 Script executed:

sed -n '1,220p' rag/utils/lazy_image.py

Repository: 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.

Comment thread rag/utils/base64_image.py
Comment on lines +69 to +73
for owned_img in owned_images:
try:
owned_img.close()
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 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.

Suggested change
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

@wangq8
wangq8 marked this pull request as draft July 7, 2026 08:24
@wangq8
wangq8 marked this pull request as ready for review July 7, 2026 08:24
@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9eba452) to head (dd39c37).
⚠️ Report is 4 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit b82169f into infiniflow:main Jul 7, 2026
9 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant