Repository navigation
Refactor: Move API files - #15151
Refactor: Move API files#15151
Conversation
📝 WalkthroughWalkthroughRelocates chunk parsing and retrieval endpoints from the SDK module into ChangesAPI Endpoint Migration
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ 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. Comment |
d8d73ed to
0b7f166
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/apps/restful_apis/chunk_api.py (1)
133-225: ⚡ Quick winAdd 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
📒 Files selected for processing (11)
api/apps/__init__.pyapi/apps/restful_apis/bot_api.pyapi/apps/restful_apis/chunk_api.pyapi/apps/restful_apis/dify_retrieval_api.pyapi/apps/sdk/doc.pytest/testcases/restful_api/test_dify_retrieval_routes_unit.pytest/testcases/restful_api/test_retrieval.pytest/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.pytest/unit_test/api/apps/sdk/test_dify_retrieval.py
💤 Files with no reviewable changes (1)
- api/apps/sdk/doc.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winUnreachable code: second
if not doc:can never execute.After the check at line 149 continues to the next iteration when
docis 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 valueStale logging prefix after module relocation.
The log message uses
"sdk.retrieval"but this code now resides inrestful_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
📒 Files selected for processing (3)
api/apps/restful_apis/bot_api.pyapi/apps/restful_apis/chunk_api.pyapi/apps/restful_apis/dify_retrieval_api.py
Refactor: Move API files