Skip to content

Refactor: Move API files - #15151

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
wangq8:refactor/move-api-files
May 22, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
wangq8:refactor/move-api-files

Conversation

@wangq8

@wangq8 wangq8 commented May 22, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor: Move API files

@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Relocates chunk parsing and retrieval endpoints from the SDK module into api/apps/restful_apis/chunk_api.py, simplifies route prefix logic in api/apps/__init__.py, and updates tests to load and mock the relocated RESTful handlers.

Changes

API Endpoint Migration

Layer / File(s) Summary
Chunk and retrieval endpoints in RESTful API layer
api/apps/restful_apis/chunk_api.py
Adds logging and expanded imports, reference-metadata helper wrappers, POST /datasets/<dataset_id>/chunks (parse), DELETE /datasets/<dataset_id>/chunks (stop_parsing), and POST /retrieval (retrieval) with validation, deduplication, task queue interactions, state updates, optional metadata enrichment, and structured error handling.
URL routing simplification
api/apps/__init__.py
register_page url_prefix selection now depends only on whether the page path contains restful_apis; previous sdk special-case removed.
Test alignment with relocated endpoints
test/testcases/restful_api/test_dify_retrieval_routes_unit.py, test/testcases/restful_api/test_retrieval.py, test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py, test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py, test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py, test/unit_test/api/apps/sdk/test_dify_retrieval.py
Tests now dynamically import RESTful API modules instead of SDK modules; test_doc_sdk_routes_unit.py expands sys.modules mocks for api.apps, common.* utilities, and api.utils helpers including reference-metadata stubs.
Minor retrieval error-handling tweaks
api/apps/restful_apis/bot_api.py, api/apps/restful_apis/dify_retrieval_api.py
Exception handlers now detect "not_found" using direct substring membership ("not_found" in str(e)) instead of find(...) > 0 checks.

Sequence Diagram

sequenceDiagram
  participant Client
  participant ChunkAPI_Parse as ChunkAPI.Parse
  participant DocService
  participant TaskQueue
  participant ChunkAPI_Retrieval as ChunkAPI.Retrieval
  participant EmbeddingService
  Client->>ChunkAPI_Parse: POST /datasets/<dataset_id>/chunks (document_ids)
  ChunkAPI_Parse->>DocService: validate ownership & run-state
  ChunkAPI_Parse->>TaskQueue: enqueue parse tasks
  TaskQueue-->>ChunkAPI_Parse: ack/task ids
  ChunkAPI_Parse-->>Client: success / partial errors
  Client->>ChunkAPI_Retrieval: POST /retrieval (dataset_ids, question, params)
  ChunkAPI_Retrieval->>EmbeddingService: select/enforce embedding model
  ChunkAPI_Retrieval->>DocService: apply filters / enrich reference metadata
  ChunkAPI_Retrieval-->>Client: retrieval results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

size:L, 🐖api, 🧪 test

Suggested reviewers

  • JinHai-CN

Poem

🐰 I hopped through code to move a route,

From SDK burrow to RESTful route.
Tests followed close with mocks in tow,
Parsers queued, retrievals go—
A tiny rabbit clap: "All systems go!"

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is identical to the title and lacks all required template sections: problem statement, type of change checkbox selection, and detailed explanation. Complete the description template by explaining what problem this refactoring solves, select the 'Refactoring' checkbox, and provide context about the endpoint migration from SDK to RESTful APIs.
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Refactor: Move API files' is vague and generic, lacking specificity about which files are being moved and why. Provide a more specific title that clarifies the scope of the refactoring, such as 'Refactor: Move document chunk and retrieval endpoints from sdk to restful_apis' or similar.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

✏️ 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.

@wangq8
wangq8 force-pushed the refactor/move-api-files branch from d8d73ed to 0b7f166 Compare May 22, 2026 08:38
@wangq8
wangq8 requested review from buua436 and euvre May 22, 2026 08:40
@wangq8 wangq8 added the ci Continue Integration label May 22, 2026
@wangq8
wangq8 marked this pull request as ready for review May 22, 2026 08:41
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 22, 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.

Actionable comments posted: 2

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

133-225: ⚡ Quick win

Add structured logs for the newly added parse/stop/retrieval flows.

The new handlers have many early-return error branches but almost no audit logging, which makes incident/debug tracing hard after migration. Also, the existing log prefix at Line 331 still says sdk.retrieval, which is stale in this module.

♻️ Suggested logging pattern
 `@token_required`
 async def parse(tenant_id, dataset_id):
+    logging.info("chunk.parse start tenant_id=%s dataset_id=%s", tenant_id, dataset_id)
     if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
+        logging.warning("chunk.parse denied tenant_id=%s dataset_id=%s", tenant_id, dataset_id)
         return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
@@
 `@token_required`
 async def stop_parsing(tenant_id, dataset_id):
+    logging.info("chunk.stop_parsing start tenant_id=%s dataset_id=%s", tenant_id, dataset_id)
@@
         if doc[0].run != TaskStatus.RUNNING.value:
+            logging.warning(
+                "chunk.stop_parsing invalid_state tenant_id=%s dataset_id=%s document_id=%s run=%s",
+                tenant_id, dataset_id, id, doc[0].run
+            )
             return construct_json_result(...)
@@
-            logging.info("sdk.retrieval reference_metadata enabled dataset_ids=%s fields=%s chunks=%s", ...)
+            logging.info("chunk.retrieval reference_metadata enabled dataset_ids=%s fields=%s chunks=%s", ...)

As per coding guidelines **/*.py: "Add logging for new flows".

Also applies to: 228-349

🤖 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/chunk_api.py` around lines 133 - 225, Add structured
audit logging to the parse and stop_parsing handlers: instrument early-return
error branches and key success paths in parse and stop_parsing to emit
structured logs containing tenant_id, dataset_id, document_ids (or current id),
success_count, not_found/duplicate_messages, and error messages; use the module
logger (get a logger for this module) and replace the stale log prefix
"sdk.retrieval" with an appropriate module prefix (e.g., this module name) so
entries are searchable; add INFO logs for high-level entry/exit (including
request payload summary) and WARN/ERROR logs for each early-return branch where
DocumentService.query / filter_update / get_by_id / DocumentService.update_by_id
/ settings.docStoreConn.delete / cancel_all_task_of fail or block processing,
and include contextual fields (function=parse/stop_parsing, tenant_id,
dataset_id, document_id, error) to aid tracing.
🤖 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 `@api/apps/restful_apis/chunk_api.py`:
- Line 243: The error message returned by get_result in chunk_api.py is
malformed (extra double-quote) — update the get_result call that currently
returns "Datasets use different embedding models.\"" so the message reads
"Datasets use different embedding models." (no stray quote) while keeping the
same RetCode.DATA_ERROR and overall return statement intact; locate the
get_result invocation in the function that performs dataset model checks and
correct the string literal.
- Around line 346-347: The current check if str(e).find("not_found") > 0 misses
matches at index 0; update the error detection in chunk_api.py to use a correct
substring test (e.g., if "not_found" in str(e) or if str(e).find("not_found") >=
0) so the branch that returns get_result(message="No chunk found! Check the
chunk status please!", code=RetCode.DATA_ERROR) executes when the error contains
"not_found" at any position.

---

Nitpick comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 133-225: Add structured audit logging to the parse and
stop_parsing handlers: instrument early-return error branches and key success
paths in parse and stop_parsing to emit structured logs containing tenant_id,
dataset_id, document_ids (or current id), success_count,
not_found/duplicate_messages, and error messages; use the module logger (get a
logger for this module) and replace the stale log prefix "sdk.retrieval" with an
appropriate module prefix (e.g., this module name) so entries are searchable;
add INFO logs for high-level entry/exit (including request payload summary) and
WARN/ERROR logs for each early-return branch where DocumentService.query /
filter_update / get_by_id / DocumentService.update_by_id /
settings.docStoreConn.delete / cancel_all_task_of fail or block processing, and
include contextual fields (function=parse/stop_parsing, tenant_id, dataset_id,
document_id, error) to aid tracing.
🪄 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: 0f625086-9fc5-492b-9e54-250f1049ba9d

📥 Commits

Reviewing files that changed from the base of the PR and between 7e68441 and c13276b.

📒 Files selected for processing (11)
  • api/apps/__init__.py
  • api/apps/restful_apis/bot_api.py
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/dify_retrieval_api.py
  • api/apps/sdk/doc.py
  • test/testcases/restful_api/test_dify_retrieval_routes_unit.py
  • test/testcases/restful_api/test_retrieval.py
  • test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
  • test/unit_test/api/apps/sdk/test_dify_retrieval.py
💤 Files with no reviewable changes (1)
  • api/apps/sdk/doc.py

Comment thread api/apps/restful_apis/chunk_api.py Resolved
Comment thread api/apps/restful_apis/chunk_api.py Resolved
@codecov

codecov Bot commented May 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (f9ce07c) to head (9eb4fed).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15151   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  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.

@wangq8 wangq8 changed the title Move API files Refactor: Move API files May 22, 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/chunk_api.py (1)

149-153: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Unreachable code: second if not doc: can never execute.

After the check at line 149 continues to the next iteration when doc is falsy, the subsequent check at line 152 will never be true. This appears to be leftover code from a merge or refactor.

🐛 Proposed fix to remove dead code
         doc = DocumentService.query(id=id, kb_id=dataset_id)
         if not doc:
             not_found.append(id)
             continue
-        if not doc:
-            return get_error_data_result(message=f"You don't own the document {id}.")
         info = {"run": "1", "progress": 0, "progress_msg": "", "chunk_num": 0, "token_num": 0}
🤖 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/chunk_api.py` around lines 149 - 153, The second "if
not doc:" block is unreachable and should be removed; keep the initial check
that appends to not_found and continues, and delete the redundant conditional
that returns get_error_data_result. If the intent was to validate ownership
instead of existence, replace the redundant block with an ownership check (e.g.,
check the document owner via the same "doc" object and call
get_error_data_result(...) only when ownership fails) — refer to the
variables/expressions "doc", "not_found", and the function
"get_error_data_result" to locate the code to change.
🧹 Nitpick comments (1)
api/apps/restful_apis/chunk_api.py (1)

331-331: 💤 Low value

Stale logging prefix after module relocation.

The log message uses "sdk.retrieval" but this code now resides in restful_apis/chunk_api.py. Consider updating the prefix to reflect the new location.

♻️ Suggested update
-            logging.info("sdk.retrieval reference_metadata enabled dataset_ids=%s fields=%s chunks=%s", kb_ids, sorted(metadata_fields) if metadata_fields else None, len(ranks["chunks"]))
+            logging.info("restful_apis.retrieval reference_metadata enabled dataset_ids=%s fields=%s chunks=%s", kb_ids, sorted(metadata_fields) if metadata_fields else None, len(ranks["chunks"]))
🤖 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/chunk_api.py` at line 331, The log line in chunk_api.py
uses the stale prefix "sdk.retrieval"; update the logging prefix to reflect this
module (e.g., "restful_apis.chunk_api" or similar) by changing the logging.info
call that formats kb_ids, metadata_fields, and len(ranks["chunks"]) so the
message reads something like "restful_apis.chunk_api reference_metadata enabled
dataset_ids=%s fields=%s chunks=%s" while keeping the same arguments (kb_ids,
sorted(metadata_fields) if metadata_fields else None, len(ranks["chunks"])) to
preserve 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.

Outside diff comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 149-153: The second "if not doc:" block is unreachable and should
be removed; keep the initial check that appends to not_found and continues, and
delete the redundant conditional that returns get_error_data_result. If the
intent was to validate ownership instead of existence, replace the redundant
block with an ownership check (e.g., check the document owner via the same "doc"
object and call get_error_data_result(...) only when ownership fails) — refer to
the variables/expressions "doc", "not_found", and the function
"get_error_data_result" to locate the code to change.

---

Nitpick comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Line 331: The log line in chunk_api.py uses the stale prefix "sdk.retrieval";
update the logging prefix to reflect this module (e.g., "restful_apis.chunk_api"
or similar) by changing the logging.info call that formats kb_ids,
metadata_fields, and len(ranks["chunks"]) so the message reads something like
"restful_apis.chunk_api reference_metadata enabled dataset_ids=%s fields=%s
chunks=%s" while keeping the same arguments (kb_ids, sorted(metadata_fields) if
metadata_fields else None, len(ranks["chunks"])) to preserve context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fdba0f49-db19-449e-a722-b851ec6e9893

📥 Commits

Reviewing files that changed from the base of the PR and between c13276b and 9eb4fed.

📒 Files selected for processing (3)
  • api/apps/restful_apis/bot_api.py
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/dify_retrieval_api.py

@wangq8
wangq8 merged commit 8791865 into infiniflow:main May 22, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant