Repository navigation
Add backward compat APIs - #14427
Add backward compat APIs#14427
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a backward-compatibility blueprint registered at startup exposing deprecated /api/v1 routes that log deprecation warnings, adapt legacy payloads when needed, and forward requests to current REST handlers. Also converts three file-related GET handlers to async. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant BC as BackwardCompat Blueprint
participant Auth as Auth (login_required)
participant NewAPI as New REST Handlers
Client->>BC: HTTP request to /api/v1/...
BC->>Auth: enforce authentication
Auth-->>BC: authenticated context
BC->>BC: log deprecation warning
BC->>NewAPI: forward request (adapt params if needed)
NewAPI-->>BC: response
BC-->>Client: response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/backward_compat.py`:
- Around line 330-343: The decorator on the deprecated_healthz view
(manager.route("/v1/system/healthz")) causes a double-prefixed route when the
blueprint is mounted at /api/v1; update the routing so only one route is
created: either change the decorator to manager.route("/system/healthz") or
remove the decorator and register the endpoint explicitly via
manager.add_url_rule("/v1/system/healthz", endpoint="deprecated_healthz",
view_func=deprecated_healthz) (also fix the same pattern around the other
handler mentioned at lines 414-423) so you don’t accidentally expose
/api/v1/v1/system/healthz.
- Around line 107-126: The deprecated_delete_chats route registers a conflicting
DELETE /chats handler; remove this separate view and instead fold its legacy
body-parsing logic into the existing DELETE /chats handler (the current
bulk-delete implementation) so both contracts coexist in one endpoint: detect
when the incoming JSON contains "chat_id" (using request.get_json and
get_data_error_result for validation) and call chat_api.delete_chat(chat_id) in
that branch; delete the deprecated_delete_chats function and its route decorator
so no second DELETE /chats route is registered.
- Around line 49-64: The deprecated_chat_completions route logs the deprecation
but fails to forward the chat_id to the new handler, so old requests lose the
intended assistant context; modify deprecated_chat_completions to inject the
path chat_id into the forwarded request shape (e.g., add chat_id to the request
body or pass it as an argument) before calling chat_api.chat_completions(),
ensuring the new handler receives the chat_id (reference symbols:
deprecated_chat_completions and chat_api.chat_completions).
- Around line 38-40: The import list in backward_compat.py includes unused
symbols causing Ruff errors—remove the unused imports `app`, `search_api`, and
`get_json_result` from the top import lines (the lines that import from
`api.apps`, `api.apps.restful_apis`, and `api.utils.api_utils`) so only actually
used names remain; alternatively, if any of those are intended to be used for
backward compatibility, reference them in a clear no-op (e.g., a module-level
alias comment) but preferably delete the unused imports to satisfy linting.
- Around line 120-126: The endpoint incorrectly awaits a synchronous function:
remove the await when forwarding to the new API by calling
chat_api.delete_chat(chat_id) directly and return its result; locate the call in
the deprecated DELETE handler that currently does "return await
chat_api.delete_chat(chat_id)" and change it to "return
chat_api.delete_chat(chat_id)" so the synchronous function
(chat_api.delete_chat) is not awaited; keep the preceding request.get_json and
get_data_error_result checks unchanged.
In `@docs/references/http_api_reference.md`:
- Around line 3289-3291: Update the deprecation caution to state that only the
legacy request body shape {"chat_id": ...} for the DELETE /api/v1/chats endpoint
is deprecated (not the entire endpoint), and reference the supported bulk-delete
contract described later in the doc; specifically, modify the text around DELETE
/api/v1/chats to say "Deprecated: legacy body shape {"chat_id": ...} — use the
bulk-delete request format documented below" and ensure the bulk-delete endpoint
description remains linked or referenced so readers know the correct
alternative.
- Around line 2918-2923: The docs table uses the wrong field name "frequency
penalty" (with a space); update the parameter entries and any table headers/rows
that show this to use the correct JSON key "frequency_penalty" (underscore) so
it matches the examples and returned objects; search for the literal "frequency
penalty" and replace it with "frequency_penalty" (also verify the related
description text remains accurate) — this also needs the same fix in the other
occurrence that currently shows the spaced form.
🪄 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: f9cd861f-b0ea-4974-9775-f1944e589193
📒 Files selected for processing (3)
api/apps/__init__.pyapi/apps/backward_compat.pydocs/references/http_api_reference.md
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
api/apps/backward_compat.py (3)
119-125:⚠️ Potential issue | 🔴 CriticalDon't await the synchronous
delete_chathandler.
chat_api.delete_chatis defined as a normaldef, soawaithere will raiseTypeErrorthe first time this deprecated endpoint is used.♻️ Suggested fix
- return await chat_api.delete_chat(chat_id) + return chat_api.delete_chat(chat_id)#!/bin/bash set -euo pipefail echo "Call site in backward compat layer:" sed -n '119,126p' api/apps/backward_compat.py echo echo "Definition of delete_chat:" rg -n -C2 '^def delete_chat\s*\(' api/apps/restful_apis/chat_api.py🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 119 - 125, The code is awaiting a synchronous handler: replace the incorrect await usage so the sync function is called directly; change the call in the backward compatibility endpoint from await chat_api.delete_chat(chat_id) to just return chat_api.delete_chat(chat_id) (or, if you need it to run off the event loop, submit chat_api.delete_chat to an executor), while keeping the surrounding async handler that calls request.get_json and returning get_data_error_result on missing chat_id unchanged.
48-63:⚠️ Potential issue | 🔴 CriticalForward
chat_idinto the deprecated chat-completions call.This shim only logs the path
chat_id; it never passes it tochat_api.chat_completions(). Old clients calling/api/v1/chats/{chat_id}/completionswill lose the assistant/chat context.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 48 - 63, The deprecated_chat_completions endpoint logs chat_id but never forwards it, so callers lose chat context; change deprecated_chat_completions to pass chat_id through to chat_api.chat_completions (e.g., call chat_api.chat_completions(chat_id=chat_id) or include chat_id in the forwarded request payload/kwargs) ensuring the argument name matches chat_api.chat_completions' signature and any incoming body/query params are preserved when forwarding.
37-39:⚠️ Potential issue | 🟡 MinorRemove the unused imports blocking Ruff.
app,search_api,system_api, andget_json_resultare still unused here, and CI is already failing on this file because of it.♻️ Suggested cleanup
-from api.apps import app, login_required -from api.apps.restful_apis import chat_api, file_api, search_api, chunk_api, system_api, openai_api, document_api -from api.utils.api_utils import get_json_result, get_data_error_result, add_tenant_id_to_kwargs +from api.apps import login_required +from api.apps.restful_apis import chat_api, file_api, chunk_api, openai_api, document_api +from api.utils.api_utils import get_data_error_result, add_tenant_id_to_kwargsAs per coding guidelines,
**/*.py: Userufffor linting and formatting Python code.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 37 - 39, Remove the unused imports that are causing Ruff failures: drop app from the import that currently reads "from api.apps import app, login_required", drop search_api and system_api from "from api.apps.restful_apis import chat_api, file_api, search_api, chunk_api, system_api, openai_api, document_api", and drop get_json_result from "from api.utils.api_utils import get_json_result, get_data_error_result, add_tenant_id_to_kwargs"; keep only the symbols actually used (login_required, chat_api, file_api, chunk_api, openai_api, document_api, get_data_error_result, add_tenant_id_to_kwargs) and re-run ruff/CI to verify the lint error is resolved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/backward_compat.py`:
- Around line 297-303: Validate the legacy rename payload before rewriting:
check that request.get_json() returns a dict and that it contains both "file_id"
and "name" before popping them; if the body is missing or keys are absent,
return or raise a structured client error (e.g., BadRequest/HTTP 400) rather
than letting the code throw, then rewrite req["src_file_ids"] =
[req.pop("file_id")] and req["new_name"] = req.pop("name") and call
file_api.move(tenant_id=tenant_id) as before.
---
Duplicate comments:
In `@api/apps/backward_compat.py`:
- Around line 119-125: The code is awaiting a synchronous handler: replace the
incorrect await usage so the sync function is called directly; change the call
in the backward compatibility endpoint from await chat_api.delete_chat(chat_id)
to just return chat_api.delete_chat(chat_id) (or, if you need it to run off the
event loop, submit chat_api.delete_chat to an executor), while keeping the
surrounding async handler that calls request.get_json and returning
get_data_error_result on missing chat_id unchanged.
- Around line 48-63: The deprecated_chat_completions endpoint logs chat_id but
never forwards it, so callers lose chat context; change
deprecated_chat_completions to pass chat_id through to chat_api.chat_completions
(e.g., call chat_api.chat_completions(chat_id=chat_id) or include chat_id in the
forwarded request payload/kwargs) ensuring the argument name matches
chat_api.chat_completions' signature and any incoming body/query params are
preserved when forwarding.
- Around line 37-39: Remove the unused imports that are causing Ruff failures:
drop app from the import that currently reads "from api.apps import app,
login_required", drop search_api and system_api from "from api.apps.restful_apis
import chat_api, file_api, search_api, chunk_api, system_api, openai_api,
document_api", and drop get_json_result from "from api.utils.api_utils import
get_json_result, get_data_error_result, add_tenant_id_to_kwargs"; keep only the
symbols actually used (login_required, chat_api, file_api, chunk_api,
openai_api, document_api, get_data_error_result, add_tenant_id_to_kwargs) and
re-run ruff/CI to verify the lint error is resolved.
🪄 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: ab5cacb3-d185-44ba-883f-addc9424c328
📒 Files selected for processing (2)
api/apps/backward_compat.pyapi/apps/restful_apis/file_api.py
There was a problem hiding this comment.
♻️ Duplicate comments (3)
api/apps/backward_compat.py (3)
48-63:⚠️ Potential issue | 🔴 CriticalForward
chat_idinto the forwarded completion request.
chat_idis only used in the warning, so legacy/chats/{chat_id}/completionsrequests lose the assistant context when they fall through tochat_api.chat_completions().🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 48 - 63, The deprecated handler deprecated_chat_completions logs chat_id but does not forward it, causing loss of assistant context; update deprecated_chat_completions to pass chat_id into the new handler by forwarding it in the request call to chat_api.chat_completions (e.g., call chat_api.chat_completions(chat_id=chat_id) or include chat_id in the payload/kwargs expected by chat_api.chat_completions), ensuring the legacy path preserves context when delegating to chat_api.chat_completions.
297-303:⚠️ Potential issue | 🟠 MajorGuard the rename shim before rewriting keys.
A missing JSON body,
file_id, ornamewill raise here beforefile_api.move()can return its normal client error, so bad legacy rename requests become 500s instead of a structured validation response.♻️ Suggested fix
# Transform the old API format to new format req = await request.get_json() + if not isinstance(req, dict): + return get_data_error_result(message="JSON body is required") # Old API used `file_id` and `name`, new API uses `src_file_ids` and `new_name` - req["src_file_ids"] = [req.pop("file_id")] - req["new_name"] = req.pop("name") + file_id = req.pop("file_id", None) + new_name = req.pop("name", None) + if not file_id or not new_name: + return get_data_error_result(message="`file_id` and `name` are required") + req["src_file_ids"] = [file_id] + req["new_name"] = new_name # Call the new API return await file_api.move(tenant_id=tenant_id)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 297 - 303, The shim that rewrites legacy rename payloads currently assumes a JSON body and presence of "file_id" and "name", causing uncaught exceptions; before mutating the dict from await request.get_json(), validate that the JSON exists and contains "file_id" and "name" (or return the appropriate client/validation response), then set req["src_file_ids"] = [req.pop("file_id")] and req["new_name"] = req.pop("name") and call file_api.move(tenant_id=tenant_id); ensure you do not pop missing keys (check with "in" or get and raise a controlled error) so missing fields produce the expected structured validation error instead of a 500.
119-128:⚠️ Potential issue | 🔴 CriticalValidate the legacy delete body and drop the
awaitondelete_chat.This block assumes
await request.get_json()returned a dict, and Line 125 awaitschat_api.delete_chat(chat_id)even though that target is a synchronousdef. That means malformed bodies hit the generic internal-error path, and valid ones will raiseTypeErrorwhen forwarded.♻️ Suggested fix
try: req = await request.get_json() + if not isinstance(req, dict): + return get_data_error_result(message="JSON body is required") chat_id = req.get("chat_id") if not chat_id: return get_data_error_result(message="`chat_id` is required for deprecated DELETE /api/v1/chats") # Forward to the new API implementation - return await chat_api.delete_chat(chat_id) + return chat_api.delete_chat(chat_id)Verify the forwarded handler contract in
api/apps/restful_apis/chat_api.py; if the output showsdef delete_chat(rather thanasync def, theawaithere must be removed.#!/bin/bash rg -n -C2 '^(async\s+def|def)\s+delete_chat\s*\(' api/apps/restful_apis/chat_api.py🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/backward_compat.py` around lines 119 - 128, The try block assumes request.get_json() returns a dict and incorrectly awaits a synchronous handler; validate that req is a mapping (e.g., isinstance(req, dict)) before using req.get("chat_id") and return get_data_error_result(...) if it's not a dict or missing chat_id, and remove the await when calling chat_api.delete_chat(chat_id) because delete_chat is a synchronous def; keep the existing exception logging/return behavior otherwise and reference request.get_json, chat_api.delete_chat, and get_data_error_result to locate the changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@api/apps/backward_compat.py`:
- Around line 48-63: The deprecated handler deprecated_chat_completions logs
chat_id but does not forward it, causing loss of assistant context; update
deprecated_chat_completions to pass chat_id into the new handler by forwarding
it in the request call to chat_api.chat_completions (e.g., call
chat_api.chat_completions(chat_id=chat_id) or include chat_id in the
payload/kwargs expected by chat_api.chat_completions), ensuring the legacy path
preserves context when delegating to chat_api.chat_completions.
- Around line 297-303: The shim that rewrites legacy rename payloads currently
assumes a JSON body and presence of "file_id" and "name", causing uncaught
exceptions; before mutating the dict from await request.get_json(), validate
that the JSON exists and contains "file_id" and "name" (or return the
appropriate client/validation response), then set req["src_file_ids"] =
[req.pop("file_id")] and req["new_name"] = req.pop("name") and call
file_api.move(tenant_id=tenant_id); ensure you do not pop missing keys (check
with "in" or get and raise a controlled error) so missing fields produce the
expected structured validation error instead of a 500.
- Around line 119-128: The try block assumes request.get_json() returns a dict
and incorrectly awaits a synchronous handler; validate that req is a mapping
(e.g., isinstance(req, dict)) before using req.get("chat_id") and return
get_data_error_result(...) if it's not a dict or missing chat_id, and remove the
await when calling chat_api.delete_chat(chat_id) because delete_chat is a
synchronous def; keep the existing exception logging/return behavior otherwise
and reference request.get_json, chat_api.delete_chat, and get_data_error_result
to locate the changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fd1cb271-3603-4c7a-acb6-fa71702e4c91
📒 Files selected for processing (1)
api/apps/backward_compat.py
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py`:
- Around line 82-85: The test stubs
api.apps.backward_compat.register_backward_compat_routes as a no-op so the
startup hook invocation isn't verified; change the stub to set a flag (e.g., set
attribute _called = True) when invoked and after calling _load_apps_module(...)
assert that sys.modules["api.apps.backward_compat"]._called is True;
specifically update the monkeypatched ModuleType to provide a
register_backward_compat_routes implementation that mutates a unique symbol
(module._called) and add an assertion after invoking _load_apps_module to verify
the hook ran.
🪄 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: 1cd4a504-03dd-438e-9b17-c4955df9c902
📒 Files selected for processing (1)
test/testcases/test_web_api/test_system_app/test_apps_init_unit.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14427 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
fade34e to
81ed643
Compare
### What problem does this PR solve? Add backward compat APIs: ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Add backward compat APIs: ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
What problem does this PR solve?
Add backward compat APIs:
Type of change