Skip to content

Guard missing storage blobs on preview and image endpoints - #15366

Merged
wangq8 merged 5 commits into
infiniflow:mainfrom
kiannidev:fix/15365-missing-blob-guard-preview-and-images
Jun 3, 2026
Merged

wangq8 merged 5 commits into
infiniflow:mainfrom
kiannidev:fix/15365-missing-blob-guard-preview-and-images

Conversation

@kiannidev

Copy link
Copy Markdown
Contributor

Summary

Fixes #15365 — get_document_image() and document preview call make_response(None) when storage returns no bytes, causing HTTP 500.

Related Issue

Fixes #15365

Change Type

  • Bug fix
  • Regression tests
  • New feature
  • Refactor

What Changed

  • get_document_image() — return get_data_error_result("Image not found.") when storage blob is missing (mirrors get_artifact()).
  • Preview get() — return get_data_error_result("This file is empty.") when storage blob is missing (matches document REST download wording).

Files Changed

File Change
api/apps/restful_apis/document_api.py Empty-blob guards before make_response()
test/testcases/test_web_api/test_document_app/test_document_metadata.py 2 unit tests

Validation

cd /root/gittensor/ragflow
pytest test/testcases/test_web_api/test_document_app/test_document_metadata.py::TestDocumentMetadataUnit::test_get_document_image_missing_blob_unit -v
pytest test/testcases/test_web_api/test_document_app/test_document_metadata.py::TestDocumentMetadataUnit::test_get_preview_missing_blob_unit -v

Test Plan

  • Missing image blob → 4xx "Image not found.", not HTTP 500
  • Missing preview blob → 4xx "This file is empty.", not HTTP 500
  • CI green

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 28, 2026
@coderabbitai

coderabbitai Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The preview endpoint now returns DATA_ERROR ("This file is empty.") when storage returns falsy data; a new unit test verifies the missing-blob preview behavior.

Changes

Document preview empty-data guard

Layer / File(s) Summary
Preview handler guard and unit test
api/apps/restful_apis/document_api.py, test/testcases/test_web_api/test_document_app/test_document_metadata.py
Adds a falsy-data check in the document preview handler to return DATA_ERROR ("This file is empty.") instead of creating a response with empty content; adds test_get_preview_missing_blob_unit that stubs blob retrieval to None and asserts the DATA_ERROR response.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PreviewHandler
  participant ThreadPoolExec
  participant StorageImpl
  Client->>PreviewHandler: GET /documents/<doc_id>/preview
  PreviewHandler->>ThreadPoolExec: thread_pool_exec(STORAGE_IMPL.get, bucket, name)
  ThreadPoolExec->>StorageImpl: STORAGE_IMPL.get(bucket, name)
  StorageImpl-->>ThreadPoolExec: None (falsy data)
  ThreadPoolExec-->>PreviewHandler: None
  PreviewHandler->>Client: DATA_ERROR ("This file is empty.")
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15371: Adds a similar missing-storage-data guard returning RetCode.DATA_ERROR ("This file is empty.") for document file download after STORAGE_IMPL.get/fallback lookup.

Suggested labels

🐖api

Suggested reviewers

  • JinHai-CN
  • yingfeng

Poem

🐰 A blob went missing, bytes ran thin,
I hopped the storage, searched within.
If silence greets the preview call,
I'll answer clean — an error small.
Tests nibble proof to guard the wall.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. 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 describes the main change: guarding missing storage blobs on preview and image endpoints, directly matching the code changes and the linked issue.
Description check ✅ Passed The description comprehensively addresses the template requirements: explains the bug problem (#15365), specifies change type (bug fix + regression tests), lists all files changed, and provides validation steps.
Linked Issues check ✅ Passed The PR fully meets all objectives from issue #15365: adds guards in get_document_image() and preview GET handler to return structured 4xx errors when storage is missing, mirroring get_artifact() patterns, with unit tests validating both missing-blob scenarios.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #15365: document_api.py guards for missing blobs in two endpoints, and test file adds exactly two unit tests for the missing-blob cases as described.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@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: 0

🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)

1673-1674: ⚡ Quick win

Consider adding logging for missing blob scenarios.

As per coding guidelines, "Add logging for new flows". While these guards mirror existing validation patterns that don't log (e.g., lines 1670, 1732), logging when storage returns no data would help diagnose blob availability issues in production.

📝 Suggested logging additions

For the image endpoint guard:

         data = await thread_pool_exec(settings.STORAGE_IMPL.get, bkt, nm)
         if not data:
+            logging.warning(f"Image blob not found in storage: bucket={bkt}, name={nm}")
             return get_data_error_result(message="Image not found.")

For the preview endpoint guard:

         data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)
         if not data:
+            logging.warning(f"Document blob not found in storage: doc_id={doc_id}, bucket={b}, name={n}")
             return get_data_error_result(message="This file is empty.")

As per coding guidelines: "Add logging for new flows" (applies to **/*.py).

Also applies to: 1881-1882

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1673 - 1674, Add a log
entry before the early-return when storage returns no data (the branch that
currently does "if not data: return get_data_error_result(...)") so missing-blob
cases are recorded; use the module's existing logger (e.g., logger or
current_app.logger) to emit a WARN/ERROR with contextual identifiers (image id,
blob key/path, request id/user if available) and then return
get_data_error_result, and do the same for the parallel preview guard around the
lines referenced (the other "if not data" that returns get_data_error_result at
~1881-1882) so both image and preview missing-blob flows are logged with useful
context.
🤖 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.

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1673-1674: Add a log entry before the early-return when storage
returns no data (the branch that currently does "if not data: return
get_data_error_result(...)") so missing-blob cases are recorded; use the
module's existing logger (e.g., logger or current_app.logger) to emit a
WARN/ERROR with contextual identifiers (image id, blob key/path, request id/user
if available) and then return get_data_error_result, and do the same for the
parallel preview guard around the lines referenced (the other "if not data" that
returns get_data_error_result at ~1881-1882) so both image and preview
missing-blob flows are logged with useful context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 715c7d90-bd5b-45f5-abf6-6fa6999aa62f

📥 Commits

Reviewing files that changed from the base of the PR and between 7fc909a and e79b087.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py

@kiannidev

kiannidev commented May 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 1, 2026
@kiannidev
kiannidev force-pushed the fix/15365-missing-blob-guard-preview-and-images branch from 6770501 to 151ee74 Compare June 1, 2026 12:35
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jun 1, 2026

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

🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (2)

1699-1700: ⚡ Quick win

Add logging when blob is missing.

When storage returns no bytes, this could indicate data corruption, missing files, or storage issues. Consider logging at warning level before returning the error to aid operational visibility and debugging.

📝 Proposed logging addition
         data = await thread_pool_exec(settings.STORAGE_IMPL.get, bkt, nm)
         if not data:
+            logging.warning(f"Image blob not found in storage: bucket={bkt}, name={nm}")
             return get_data_error_result(message="Image not found.")

As per coding guidelines, add logging for new flows.

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1699 - 1700, The code
returns get_data_error_result when the retrieved blob bytes variable data is
falsy but does not log this event; add a warning-level log before the return to
aid operations. In the function in document_api.py where data is checked (the
variable name data), call the module's logger (or current_app.logger) to warn
that the blob was missing and include contextual identifiers available in scope
(e.g., document_id, blob_key, or request parameters) and any storage backend
info, then return get_data_error_result as before.

1908-1909: ⚡ Quick win

Add logging when blob is missing.

When storage returns no bytes, this could indicate data corruption, missing files, or storage issues. Consider logging at warning level before returning the error to aid operational visibility and debugging.

📝 Proposed logging addition
         data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)
         if not data:
+            logging.warning(f"Preview blob not found in storage: doc_id={doc_id}, bucket={b}, name={n}")
             return get_data_error_result(message="This file is empty.")

As per coding guidelines, add logging for new flows.

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1908 - 1909, The check
that returns get_data_error_result when data is falsy needs a warning log before
the return: at the 'if not data:' branch (the 'data' variable and
get_data_error_result call identify the spot), emit a logger.warning (or
current_app.logger.warning depending on module conventions) that includes
contextual identifiers available in scope (e.g., file_id, blob_key, object/path
name, bucket, or request id) and a short message like "storage returned empty
blob" so operators can correlate missing bytes with the object; then return
get_data_error_result as before.
🤖 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.

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1699-1700: The code returns get_data_error_result when the
retrieved blob bytes variable data is falsy but does not log this event; add a
warning-level log before the return to aid operations. In the function in
document_api.py where data is checked (the variable name data), call the
module's logger (or current_app.logger) to warn that the blob was missing and
include contextual identifiers available in scope (e.g., document_id, blob_key,
or request parameters) and any storage backend info, then return
get_data_error_result as before.
- Around line 1908-1909: The check that returns get_data_error_result when data
is falsy needs a warning log before the return: at the 'if not data:' branch
(the 'data' variable and get_data_error_result call identify the spot), emit a
logger.warning (or current_app.logger.warning depending on module conventions)
that includes contextual identifiers available in scope (e.g., file_id,
blob_key, object/path name, bucket, or request id) and a short message like
"storage returned empty blob" so operators can correlate missing bytes with the
object; then return get_data_error_result as before.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 49cfc14c-56ad-458b-bc02-eb89caef21b9

📥 Commits

Reviewing files that changed from the base of the PR and between e79b087 and 151ee74.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

I am not sure why #15365 is closed, it isn't fixed.
It will be completed by this PR

@Haruko386 Haruko386 added the ci Continue Integration label Jun 2, 2026
@Haruko386
Haruko386 marked this pull request as draft June 2, 2026 03:44
@Haruko386
Haruko386 marked this pull request as ready for review June 2, 2026 03:44
@codecov

codecov Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (33ef724) to head (afbfbee).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15366   +/-   ##
=======================================
  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 Sentry.
📢 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.

Avoid make_response(None) on empty MinIO/S3 reads for document
preview and /documents/images endpoints.
Fixes infiniflow#15365
@kiannidev
kiannidev force-pushed the fix/15365-missing-blob-guard-preview-and-images branch from 2c4a8d4 to d11225b Compare June 2, 2026 04:15

@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: 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 `@test/testcases/test_web_api/test_document_app/test_document_metadata.py`:
- Around line 529-545: The test test_get_preview_missing_blob_unit fails to stub
DocumentService.accessible so the request may be blocked by the authorization
guard; update the test to monkeypatch DocumentService.accessible to return True
(matching the pattern used in
test_get_route_not_found_success_and_exception_unit) before calling
module.get("doc1") so the code path reaches the blob-fetching logic checked by
the fake_thread_pool_exec and the missing-blob guard.
🪄 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: 29763e65-6239-49b8-bc46-3d199f201ec9

📥 Commits

Reviewing files that changed from the base of the PR and between 2c4a8d4 and d11225b.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/document_api.py

Bypass auth so the unit test reaches the empty-storage guard instead of
returning "Document not found!" first.
@kiannidev
kiannidev force-pushed the fix/15365-missing-blob-guard-preview-and-images branch from 2f1a3e1 to f9bdcb2 Compare June 2, 2026 04:48
@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

@xugangqiang

Copy link
Copy Markdown
Contributor

@wangq8

@xugangqiang
xugangqiang requested a review from wangq8 June 3, 2026 03:32
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:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Document preview and image endpoints return HTTP 500 when storage blob is missing

4 participants