Skip to content

fix(sdk): retain image IDs on chunks - #19505

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
AnnaSuSu:fix/sdk-chunk-image-id
Sep 14, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
AnnaSuSu:fix/sdk-chunk-image-id

Conversation

@AnnaSuSu

Copy link
Copy Markdown
Contributor

Summary

Document.add_chunk(), Document.list_chunks(), and RAGFlow.retrieve() discard the image_id returned by the server. Chunk.__init__ removes response keys that do not have a corresponding instance attribute, and image_id is missing from that list. Accessing the documented chunk.image_id raises AttributeError, even when the HTTP response contains an image reference.

Initialize image_id to an empty string so the SDK retains the returned identifier and includes it in to_json(). Responses without an image field get the documented empty default.

Validation

  • Added eight focused tests. Six use the real SDK and Requests against a local HTTP peer to exercise all three entry points with non-empty and empty image IDs; two cover missing-field defaults and continued filtering of unrelated fields.
  • Unchanged main 5bd80b345: 7 failed, 1 passed. Fix branch: 8 passed.
  • Ruff check, Ruff format check, and git diff --check pass for the touched Python files.
  • The tests use synthetic responses matching the current API envelopes. No full RAGFlow service, parser/embedding model, or image-download end-to-end test was run.

The API reference already documents image_id on Chunk, and the current add/list/retrieval handlers already return it. Checked the adjacent image/audio/metadata PRs (#18889, #15766, #15868, #15732); none changes the SDK Chunk model.

Copilot AI lite review requested due to automatic review settings September 10, 2026 11:09
@coderabbitai

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: e6534760-4cce-436d-ac11-088f59d58e88

📥 Commits

Reviewing files that changed from the base of the PR and between 06f2b0c and 5903559.

📒 Files selected for processing (1)
  • test/unit_test/sdk/test_chunk_image_id.py

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


📝 Walkthrough

Walkthrough

The SDK adds Chunk.image_id with an empty-string default. Tests verify image ID preservation across add, list, and retrieve operations, JSON serialization, missing fields, and unknown-field filtering.

Changes

Chunk image ID support

Layer / File(s) Summary
Chunk image ID contract
sdk/python/ragflow_sdk/modules/chunk.py, test/unit_test/sdk/test_chunk_image_id.py
Chunk initializes image_id to an empty string. Tests verify the default and unknown-field filtering.
Chunk API preservation tests
test/unit_test/sdk/test_chunk_image_id.py
A local HTTP server and parameterized tests verify image_id for add, list, and retrieve operations, including populated and empty values. Tests also verify request serialization and response content.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 59035

The SDK now retains server-provided chunk image IDs across the supported operations, with defaults and response filtering covered by tests. No merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: retaining image IDs on SDK chunks.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, implementation, test coverage, validation results, and scope limitations.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files.
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.

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

A rabbit checks each chunk with care
An image ID now waits there
Add and list and fetch agree
Empty strings stay orderly
JSON keeps the fields in line
Hop by hop, the tests all shine

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

Copilot AI 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.

🟢 Approval recommended

The change is minimal and consistent with existing API behavior (image_id already emitted), and the added tests directly validate the corrected SDK behavior across all affected entry points.

Pull request overview

Fixes the Python SDK’s Chunk model so it retains the server-provided image_id field across chunk creation, listing, and retrieval, matching the documented chunk.image_id API and preventing AttributeError when consumers access it.

Changes:

  • Add image_id as a first-class Chunk attribute (defaulting to "") so it is not dropped by the SDK’s response-key filtering.
  • Add unit tests that exercise Document.add_chunk(), Document.list_chunks(), and RAGFlow.retrieve() against a local HTTP stub to verify image_id is preserved (including empty-string defaults) and unknown fields remain filtered.
File summaries
File Description
sdk/python/ragflow_sdk/modules/chunk.py Adds image_id to Chunk’s known fields so it survives key-filtering and appears in to_json().
test/unit_test/sdk/test_chunk_image_id.py Adds focused tests covering image_id preservation/defaulting across SDK endpoints and continued filtering of unknown fields.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@euvre

euvre commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

LGTM 🚀

What the change does — Chunk.__init__ pops any response key that has no matching instance attribute (sdk/python/ragflow_sdk/modules/chunk.py:49-51), so the server-provided image_id was silently discarded and the documented chunk.image_id (docs/references/python_api_reference.md:957) raised AttributeError. Pre-initializing image_id = "" follows the exact pattern used for every other documented field, and covers all three construction sites (sdk/python/ragflow_sdk/modules/document.py:90, document.py:102, sdk/python/ragflow_sdk/ragflow.py:234).

Cross-check of the premise — the server really does emit image_id on all three entry points, in both API implementations: add (internal/service/chunk/chunk.go:1458-1460; api/apps/restful_apis/chunk_api.py:1145,1172), list (internal/service/chunk_types.go:447-451; api/apps/restful_apis/chunk_api.py:601,629), retrieve (internal/service/nlp/retrieval.go:261-264; rag/nlp/search.py:773,951,1007).

What was verified

  • Unit tier: pytest test/unit_test/sdk/test_chunk_image_id.py → 8/8 passed on the PR head. After temporarily removing the one-line fix, the same suite reports exactly 7 failed, 1 passed, every failure being AttributeError: 'Chunk' object has no attribute 'image_id' — the base behavior matches the PR description bit-for-bit. ruff check and ruff format --check pass on both touched files.
  • Live service drive — no UI surface (Python SDK library change): verified by driving the PR-head SDK programmatically against a running RAGFlow service instead of the browser. Scenarios covered: add_chunk without an image → chunk.image_id == "" (documented default, also present in to_json()); add_chunk with a base64 image → chunk.image_id == "<dataset_id>-<chunk_id>", matching the server's generation format (api/apps/restful_apis/chunk_api.py:1145); list_chunks → both chunks returned with their correct image_id values preserved; adjacent regression: text-only chunks (the no-image default path) round-trip correctly and to_json() keeps unknown fields filtered, as asserted by the added tests. The /retrieval endpoint was exercised live as well, but returns no hits for SDK-added chunks because of a pre-existing server-side quirk (below) — retrieve-side image_id retention is therefore covered by the added unit tests (real SDK, real envelope) plus the server formatter at rag/nlp/search.py:773.

Nits (non-blocking)

  1. test/unit_test/sdk/test_chunk_image_id.py — the stub returns the chunks envelope for any request that is not the add-chunk POST, so a retrieve call hitting a wrong path would still pass; asserting the expected path per endpoint (e.g. /retrieval for retrieve) would make the tests tighter.
  2. Test functions lack docstrings (bot review flagged docstring coverage) — style only.

Out-of-scope observations found during live verification (pre-existing, not introduced here — no action required in this PR)

  • SDK-created chunks are invisible to retrieval: the add path never writes available_int, while retrieval filters on "available_int": 1 (api/apps/restful_apis/chunk_api.py add path vs rag/nlp/search.py:643). Worth a follow-up issue if confirmed intended-vs-bug by maintainers.

@AnnaSuSu

Copy link
Copy Markdown
Contributor Author

@euvre Thanks for the detailed review and service verification. Addressed both non-blocking nits in 5903559:

  • The HTTP peer now accepts only the expected method/path pairs for add, list and retrieval and returns 404 otherwise. Each endpoint case also asserts the exact method and path.
  • Added docstrings to the test functions and HTTP helpers.

Validation: all 8 chunk tests pass; Ruff check, format check and diff check pass. A local HTTP control probe confirmed that a wrong retrieval path received 200 from the old peer and receives 404 after this change.

The separate retrieval observation remains outside this PR as suggested. Any follow-up should establish the backend-specific behavior first: the Elasticsearch/OpenSearch adapters handle missing availability fields differently from a strict equality filter. I have not independently repeated the live-service verification.

@euvre

euvre commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

LGTM 🚀

Follow-up review — re-checked after 59035593f. Both nits from the earlier review are properly resolved:

  1. The HTTP peer now serves only the exact (method, path) combinations for add/list/retrieve and returns 404 for anything unexpected, and the assertion was upgraded from "exactly one request" to the exact (method, path) tuple (test/unit_test/sdk/test_chunk_image_id.py:91-96). urlsplit strips the query string, so the GET-path assertion stays robust to the SDK's pagination parameters while still pinning the path.
  2. Docstrings were added to the fixture, the handler helpers, and all three test functions.

What was verified

  • Unit tier (CI-style: ragflow_sdk installed editable from the PR head): 8/8 passed. Negative control: with sdk/python/ragflow_sdk/modules/chunk.py temporarily reverted to the merge-base version, the same suite reports exactly 7 failed, 1 passed, every failure being AttributeError: 'Chunk' object has no attribute 'image_id' — the PR's stated base behavior reproduces bit-for-bit; restoring the one-line fix returns the suite to 8/8.
  • Live service drive — no UI surface (Python SDK library change): verified by driving the PR-head SDK programmatically against a running RAGFlow service instead of the browser. Scenarios covered: add_chunk text-only → chunk.image_id == "" (documented default at docs/references/python_api_reference.md:957, also present in to_json()); add_chunk with a base64 image → image_id == "<dataset_id>-<chunk_id>", matching the server's generation format at api/apps/restful_apis/chunk_api.py:1145; list_chunks → both chunks returned with their correct image_id values; retrieve → 2 hits with image_id preserved on both, including the empty default on the text-only chunk, so retrieval-side retention is confirmed live this round (the availability quirk noted in the earlier review did not reproduce on this stack). Adjacent regression paths: a response without an image_id field still defaults to "", and unrelated response fields are still filtered out of to_json().

The fix itself follows the established one-attribute-default pattern in Chunk.__init__ and touches nothing else: the unknown-key filtering loop (sdk/python/ragflow_sdk/modules/chunk.py:50-52) is unchanged, so serialization semantics for all other fields are unaffected. No scope creep — both commits modify only chunk.py and the new test file.

@euvre euvre added the ci Continue Integration label Sep 11, 2026
@codecov

codecov Bot commented Sep 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 37.37%. Comparing base (5bd80b3) to head (5903559).
⚠️ Report is 42 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##           main   #19505       +/-   ##
=========================================
+ Coverage      0   37.37%   +37.37%     
=========================================
  Files         0       54       +54     
  Lines         0    15375    +15375     
  Branches      0      125      +125     
=========================================
+ Hits          0     5747     +5747     
- Misses        0     9601     +9601     
- Partials      0       27       +27     

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

@JinHai-CN
JinHai-CN merged commit 464e672 into infiniflow:main Sep 14, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants