Repository navigation
Go: add context, part14 - #17446
Go: add context, part14#17446
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
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:
📝 WalkthroughWalkthroughThis PR threads request contexts and explicit GORM handles through DAO, service, and handler layers. It also updates transactions, pipeline helpers, authorization checks, validation messages, and related tests. ChangesContext-aware data access and service flow
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
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: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
internal/service/chat_session.go (1)
1349-1349: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRestore the nil-context fallback in
CompletionStream.
CompletionStreamforwardsctxto DAO calls,checkTenantLLMAPIKey,AsyncChat, andupdateSessionMessages; unlikeChatCompletions, it no longer normalizes nil tocontext.Background(), so nil callers can propagate an invalid context downstream.🤖 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 `@internal/service/chat_session.go` at line 1349, Update ChatSessionService.CompletionStream to normalize a nil ctx to context.Background() at the start of the method, before forwarding it to DAO calls, checkTenantLLMAPIKey, AsyncChat, or updateSessionMessages; preserve the existing behavior for non-nil contexts.internal/service/user.go (1)
393-405: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winDo not disclose whether the email is registered.
Line 395 reports an unregistered email while Line 404 reports a password mismatch, allowing account enumeration. Return one generic authentication error for both paths.
Proposed fix
- return nil, common.CodeAuthenticationError, fmt.Errorf("email: %s is not registered", req.Email) + return nil, common.CodeAuthenticationError, fmt.Errorf("invalid email or password") ... - return nil, common.CodeAuthenticationError, fmt.Errorf("email and password do not match") + return nil, common.CodeAuthenticationError, fmt.Errorf("invalid email or password")🤖 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 `@internal/service/user.go` around lines 393 - 405, Update the authentication error handling in the user lookup and password validation flow around GetByEmail and VerifyPassword so both an unknown email and an incorrect password return the same generic authentication error message. Preserve the existing authentication error code and avoid exposing whether the email is registered.internal/admin/service.go (1)
228-318: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winBind the user-provisioning transactions to the request context.
Both methods use
ctxfor pre-transaction reads, but transaction handles are started without context propagation, so latertx.Createcalls can ignore request cancellation/deadlines.
internal/admin/service.go#L215: start the transaction withdao.DB.WithContext(ctx).Begin()before creating user/tenant data.internal/service/user.go#L235: usedb.WithContext(ctx).Transaction(...)so the writes honorRegister’s request context.🤖 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 `@internal/admin/service.go` around lines 228 - 318, Bind both user-provisioning transactions to the request context: in internal/admin/service.go, update the transaction start before the user/tenant creation flow to use dao.DB.WithContext(ctx).Begin(); in internal/service/user.go, update Register’s transaction wrapper to use db.WithContext(ctx).Transaction(...). Apply the context-aware transaction changes at both affected sites.
🧹 Nitpick comments (5)
internal/service/agent_test.go (1)
1453-1454: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the test context for the service operation.
These tests now seed and assert with
ctx, but theirUpdateAgent/PublishAgentcalls still usecontext.Background(), so they do not cover the intended request-context propagation.
internal/service/agent_test.go#L1453-L1454: passctxtoUpdateAgent.internal/service/agent_test.go#L1513-L1524: passctxtoUpdateAgent.internal/service/agent_test.go#L1576-L1585: passctxtoUpdateAgent.internal/service/agent_test.go#L1616-L1626: passctxto bothUpdateAgentcalls.internal/service/agent_test.go#L1677-L1690: passctxtoPublishAgent.internal/service/agent_test.go#L1763-L1800: passctxtoUpdateAgent.🤖 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 `@internal/service/agent_test.go` around lines 1453 - 1454, Replace context.Background() with the existing test ctx when invoking UpdateAgent or PublishAgent throughout internal/service/agent_test.go:1453-1454, 1513-1524, 1576-1585, 1616-1626, 1677-1690, and 1763-1800. Update both UpdateAgent calls in the 1616-1626 site, while leaving setup and assertions unchanged.internal/ingestion/task/pipeline_run_test.go (1)
33-42: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExercise the context-aware read with
ctx.The test seeds the database with
t.Context()but invokesloadDSLFuncwithcontext.Background(), so it does not verify request-context propagation through the new DAO call. Passctxto the load call instead; remove thecontextimport only if it becomes unused.🤖 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 `@internal/ingestion/task/pipeline_run_test.go` around lines 33 - 42, Update the test’s loadDSLFunc invocation to pass the existing ctx from t.Context() instead of context.Background(), ensuring the context-aware DAO read is exercised. Remove the context import only if it becomes unused.internal/service/document/document_artifact.go (1)
148-163: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPropagate
ctxintosandboxArtifactDialogIDsForUsertoo.The new context reaches
canvasDAO.Accessible, butsandboxArtifactDialogIDsForUserstill executes itsdao.DB.Rows()query withoutWithContext(ctx). A canceled request can therefore continue the initial authorization query after the request ends.🤖 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 `@internal/service/document/document_artifact.go` around lines 148 - 163, Update sandboxArtifactAccessible and sandboxArtifactDialogIDsForUser to accept and propagate ctx, ensuring the dialog-ID database query uses the request context via WithContext(ctx) before authorization checks continue.internal/service/chat_session.go (1)
766-768: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid parsing
session.Referencetwice.The reference is already parsed and validated at Lines 735-737, so this reassignment repeats the JSON parsing and validation. Reuse the existing slice here.
🤖 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 `@internal/service/chat_session.go` around lines 766 - 768, In the session handling flow, update the block around parseReferenceList so it reuses the references slice parsed and validated earlier at Lines 735-737 instead of calling parseReferenceList(session.Reference) again. Preserve the existing invalid-reference error behavior while removing the redundant reassignment and validation.internal/dao/user.go (1)
60-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRedundant
.WithContext(ctx)calls ininternal/dao/user.goandinternal/dao/user_tenant.go. BothGetNicknameByIDandGetByUserIDchaindb.WithContext(ctx)twice on the same query — a harmless but copy-pasted no-op from the ctx/db refactor.
internal/dao/user.go#L60-L62: drop the second.WithContext(ctx)inGetNicknameByID's query chain.internal/dao/user_tenant.go#L62-L66: drop the second.WithContext(ctx)inGetByUserID's query chain.🤖 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 `@internal/dao/user.go` around lines 60 - 62, Remove the duplicate WithContext(ctx) call from the query chain in GetNicknameByID in internal/dao/user.go and from GetByUserID in internal/dao/user_tenant.go; retain one context application in each method and leave the remaining query behavior unchanged.
🤖 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 `@internal/dao/user_canvas_version.go`:
- Around line 111-113: Bind the caller context to every transaction write in
UserCanvasVersionDAO by starting each relevant tx chain with
tx.WithContext(ctx). Update CreateTx, DeleteTx, DeleteByCanvasIDTx, the
Create(row) branch in SaveOrReplaceLatestTx, and the cleanup Delete in
deleteAllUnpublishedExcessTx, while preserving their existing query conditions
and write behavior.
In `@internal/handler/tenant.go`:
- Around line 430-434: Reorder the comments immediately above os.ReadFile in the
tenant import flow so the CodeQL suppression line introducing req.FilePath
appears before its continuation and the rationale reads correctly; remove any
stale or malformed documentation rather than retaining it.
In `@internal/service/agent_sessions.go`:
- Around line 701-704: Update internal/service/agent_sessions.go at lines
701-704 in the CheckCanvasAccess error handling to detect
dao.ErrUserCanvasNotFound and return common.CodeOperatingError with the generic
no-permission message; retain server-error handling for other errors. At lines
720-725, change the missing-record check to use errors.Is with
dao.ErrUserCanvasNotFound instead of gorm.ErrRecordNotFound.
In `@internal/service/chat_session.go`:
- Line 391: Update DeleteSessions and CompletionStream so their user-facing
response messages exactly match the corresponding returned and serialized error
messages, including capitalization and punctuation. Use one consistent message
for each authorization/model error across both channels, preserving the existing
error codes and control flow.
In `@internal/service/chunk_types.go`:
- Line 138: Update ChunkService.Get in chunk_types.go to accept and use the
caller-provided ctx for tenant and knowledge-base lookups, removing any
context.Background() shadowing. Ensure ChunkHandler.Get’s c.Request.Context()
propagates through the existing ChunkService.Get call, and remove the legacy
context parameter only if it is genuinely unused.
In `@internal/service/connector.go`:
- Around line 219-225: Update ConnectorService.canAccessConnector to return both
the access result and an error, preserving expected no-membership outcomes as
false while propagating unexpected DAO errors; update every caller to handle and
return that error. In internal/service/dataset/helpers.go:176-179, check the
tenant lookup error before calling Accessible and return it immediately when
present.
In `@internal/service/dataset/helpers.go`:
- Around line 159-162: Update the size-limit error in the parser configuration
validation around len(data) to report the measured unit accurately: change
“characters” to “bytes” while preserving the existing byte-based limit and size
calculation.
In `@internal/service/oauth_login.go`:
- Around line 263-279: Update registerOAuthUser so the user, tenant, user-tenant
relation, and root-file creations execute inside a single
dao.DB.WithContext(ctx).Transaction callback. Return any insert error from the
transaction and preserve the existing registration error response, removing the
compensating deletes because transaction rollback must handle partial failures.
---
Outside diff comments:
In `@internal/admin/service.go`:
- Around line 228-318: Bind both user-provisioning transactions to the request
context: in internal/admin/service.go, update the transaction start before the
user/tenant creation flow to use dao.DB.WithContext(ctx).Begin(); in
internal/service/user.go, update Register’s transaction wrapper to use
db.WithContext(ctx).Transaction(...). Apply the context-aware transaction
changes at both affected sites.
In `@internal/service/chat_session.go`:
- Line 1349: Update ChatSessionService.CompletionStream to normalize a nil ctx
to context.Background() at the start of the method, before forwarding it to DAO
calls, checkTenantLLMAPIKey, AsyncChat, or updateSessionMessages; preserve the
existing behavior for non-nil contexts.
In `@internal/service/user.go`:
- Around line 393-405: Update the authentication error handling in the user
lookup and password validation flow around GetByEmail and VerifyPassword so both
an unknown email and an incorrect password return the same generic
authentication error message. Preserve the existing authentication error code
and avoid exposing whether the email is registered.
---
Nitpick comments:
In `@internal/dao/user.go`:
- Around line 60-62: Remove the duplicate WithContext(ctx) call from the query
chain in GetNicknameByID in internal/dao/user.go and from GetByUserID in
internal/dao/user_tenant.go; retain one context application in each method and
leave the remaining query behavior unchanged.
In `@internal/ingestion/task/pipeline_run_test.go`:
- Around line 33-42: Update the test’s loadDSLFunc invocation to pass the
existing ctx from t.Context() instead of context.Background(), ensuring the
context-aware DAO read is exercised. Remove the context import only if it
becomes unused.
In `@internal/service/agent_test.go`:
- Around line 1453-1454: Replace context.Background() with the existing test ctx
when invoking UpdateAgent or PublishAgent throughout
internal/service/agent_test.go:1453-1454, 1513-1524, 1576-1585, 1616-1626,
1677-1690, and 1763-1800. Update both UpdateAgent calls in the 1616-1626 site,
while leaving setup and assertions unchanged.
In `@internal/service/chat_session.go`:
- Around line 766-768: In the session handling flow, update the block around
parseReferenceList so it reuses the references slice parsed and validated
earlier at Lines 735-737 instead of calling
parseReferenceList(session.Reference) again. Preserve the existing
invalid-reference error behavior while removing the redundant reassignment and
validation.
In `@internal/service/document/document_artifact.go`:
- Around line 148-163: Update sandboxArtifactAccessible and
sandboxArtifactDialogIDsForUser to accept and propagate ctx, ensuring the
dialog-ID database query uses the request context via WithContext(ctx) before
authorization checks continue.
🪄 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 Plus
Run ID: c4b85203-6cdb-4233-9a3d-ec0297f26c88
📒 Files selected for processing (46)
internal/admin/handler.gointernal/admin/handler_ee.gointernal/admin/service.gointernal/admin/service_ee.gointernal/dao/user.gointernal/dao/user_canvas.gointernal/dao/user_canvas_test.gointernal/dao/user_canvas_version.gointernal/dao/user_canvas_version_test.gointernal/dao/user_tenant.gointernal/handler/agent.gointernal/handler/api_token.gointernal/handler/tenant.gointernal/handler/user.gointernal/ingestion/task/pipeline_executor.gointernal/ingestion/task/pipeline_run_test.gointernal/service/agent.gointernal/service/agent_sessions.gointernal/service/agent_test.gointernal/service/bot.gointernal/service/chat.gointernal/service/chat_channel.gointernal/service/chat_session.gointernal/service/chat_session_contract_test.gointernal/service/chat_session_test.gointernal/service/chunk/chunk.gointernal/service/chunk_types.gointernal/service/connector.gointernal/service/dataset/create_test.gointernal/service/dataset/crud.gointernal/service/dataset/helpers.gointernal/service/dataset/update.gointernal/service/dataset/update_test.gointernal/service/document/document_artifact.gointernal/service/document/document_dataset_update.gointernal/service/document/document_list.gointernal/service/document/document_test.gointernal/service/ingestion_task_service.gointernal/service/model_service.gointernal/service/oauth_login.gointernal/service/pipeline_params.gointernal/service/search.gointernal/service/stats.gointernal/service/tenant.gointernal/service/tenant_test.gointernal/service/user.go
| } | ||
| if !ok { | ||
| return false, "No authorization.", common.CodeAuthenticationError, errors.New("No authorization.") | ||
| return false, "No authorization.", common.CodeAuthenticationError, errors.New("no authorization") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Keep returned and serialized error messages consistent.
DeleteSessions still returns "No authorization." in its response while returning "no authorization" as the error. Likewise, CompletionStream emits "Cannot use specified model..." before returning the lower-case error. Clients can therefore observe different contracts depending on which channel they inspect.
Also applies to: 1379-1381
🤖 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 `@internal/service/chat_session.go` at line 391, Update DeleteSessions and
CompletionStream so their user-facing response messages exactly match the
corresponding returned and serialized error messages, including capitalization
and punctuation. Use one consistent message for each authorization/model error
across both channels, preserving the existing error codes and control flow.
| func (s *ConnectorService) canAccessConnector(ctx context.Context, connector *entity.Connector, userID string) bool { | ||
| if connector.TenantID == userID { | ||
| return true | ||
| } | ||
|
|
||
| _, err := s.userTenantDAO.FilterByUserIDAndTenantID(userID, connector.TenantID) | ||
| _, err := s.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, userID, connector.TenantID) | ||
| return err == nil |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Preserve errors from context-aware authorization lookups.
Both paths currently convert DAO failures into normal access results, hiding cancellation and database outages from callers.
internal/service/connector.go#L219-L225: preserve expected no-membership results asfalse, but return unexpected DAO errors and update all callers to propagate them.internal/service/dataset/helpers.go#L176-L179: check the tenant lookup error and return it before invokingAccessible.
📍 Affects 2 files
internal/service/connector.go#L219-L225(this comment)internal/service/dataset/helpers.go#L176-L179
🤖 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 `@internal/service/connector.go` around lines 219 - 225, Update
ConnectorService.canAccessConnector to return both the access result and an
error, preserving expected no-membership outcomes as false while propagating
unexpected DAO errors; update every caller to handle and return that error. In
internal/service/dataset/helpers.go:176-179, check the tenant lookup error
before calling Accessible and return it immediately when present.
| if len(data) > 65535 { | ||
| return fmt.Errorf("Parser config exceeds size limit (max 65,535 characters). Current size: %d", len(data)) | ||
| return fmt.Errorf("parser config exceeds size limit (max 65,535 characters). Current size: %d", len(data)) | ||
| } | ||
| return nil |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Report parser configuration size in bytes.
len(data) counts bytes, but the error says “characters.” For non-ASCII JSON, the reported size is incorrect; either change the message to “bytes” or count characters if the limit is truly character-based.
🤖 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 `@internal/service/dataset/helpers.go` around lines 159 - 162, Update the
size-limit error in the parser configuration validation around len(data) to
report the measured unit accurately: change “characters” to “bytes” while
preserving the existing byte-based limit and size calculation.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py`:
- Line 926: Update the assertion in the relevant chat SDK route test to validate
the complete empty-name error message, including the new punctuation, rather
than matching only a substring. Ensure the test fails if the response still uses
the old trailing-period text.
In
`@test/testcases/test_http_api/test_session_management/test_chat_completions.py`:
- Line 89: Update the assertion in the session-management chat completions test
to validate the complete normalized authorization message returned in
res["message"], ensuring the expected trailing punctuation behavior is enforced
rather than accepting any string containing “no authorization”.
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py`:
- Around line 91-92: Update the remaining authorization-message assertions in
test_paser_documents.py, including the referenced additional locations, to
expect lowercase “no authorization” for response code 109. Keep the existing
test cases and response-code assertions unchanged.
🪄 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 Plus
Run ID: 12232f9b-52ea-4122-8b79-3a4c1dc20543
📒 Files selected for processing (52)
api/apps/restful_apis/chat_api.pyapi/apps/restful_apis/chat_channel_api.pyapi/apps/restful_apis/connector_api.pyapi/apps/restful_apis/dataset_api.pyapi/apps/restful_apis/dify_retrieval_api.pyapi/apps/restful_apis/document_api.pyapi/apps/restful_apis/file2document_api.pyapi/apps/restful_apis/search_api.pyapi/apps/restful_apis/tenant_api.pyapi/apps/services/dataset_api_service.pyapi/apps/services/file_api_service.pyapi/db/services/conversation_service.pyapi/db/services/knowledgebase_service.pyapi/utils/validation_utils.pyinternal/dao/memory.gointernal/dao/user.gointernal/dao/user_tenant.gointernal/ingestion/task/pipeline_run_test.gointernal/service/agent_test.gointernal/service/chat_session.gointernal/service/document/document_artifact.gotest/testcases/restful_api/test_chats.pytest/testcases/restful_api/test_connector_routes_unit.pytest/testcases/restful_api/test_datasets.pytest/testcases/restful_api/test_documents.pytest/testcases/restful_api/test_file_routes_unit.pytest/testcases/restful_api/test_sessions.pytest/testcases/restful_api/test_user_tenant_routes_unit.pytest/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.pytest/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.pytest/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.pytest/testcases/test_http_api/test_dataset_management/test_create_dataset.pytest/testcases/test_http_api/test_dataset_management/test_update_dataset.pytest/testcases/test_http_api/test_file_app/test_file_routes.pytest/testcases/test_http_api/test_file_management_within_dataset/test_update_document.pytest/testcases/test_http_api/test_session_management/test_chat_completions.pytest/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.pytest/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.pytest/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.pytest/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.pytest/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.pytest/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.pytest/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.pytest/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.pytest/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.pytest/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.pytest/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.pytest/testcases/test_web_api/test_document_app/test_paser_documents.pytest/testcases/test_web_api/test_document_app/test_upload_documents.pytest/testcases/test_web_api/test_file_app/test_file2document_routes_unit.pytest/testcases/test_web_api/test_user_app/test_tenant_app_unit.py
💤 Files with no reviewable changes (1)
- internal/service/chat_session.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/service/document/document_artifact.go
- internal/dao/user.go
- internal/ingestion/task/pipeline_run_test.go
- internal/dao/user_tenant.go
| _set_request_json(monkeypatch, module, {"name": ""}) | ||
| res = _run(module.update_session.__wrapped__("chat-1", "session-1")) | ||
| assert "`name` can not be empty." in res["message"] | ||
| assert "`name` can not be empty" in res["message"] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Keep the empty-name assertion strict enough to verify the new contract.
Line 926 uses a substring without the trailing period, so it passes for both the old and new response text. Assert the complete message, or additionally verify that the response does not retain the trailing period.
🤖 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
`@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py`
at line 926, Update the assertion in the relevant chat SDK route test to
validate the complete empty-name error message, including the new punctuation,
rather than matching only a substring. Ensure the test fails if the response
still uses the old trailing-period text.
| ) | ||
| assert res["code"] == 109, res | ||
| assert "No authorization." in res.get("message", ""), res | ||
| assert "no authorization" in res.get("message", ""), res |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Verify the complete normalized authorization message.
Line 89 checks only that "no authorization" occurs, so "no authorization." would also pass. Assert the complete message, or explicitly verify that the trailing period is absent.
🤖 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
`@test/testcases/test_http_api/test_session_management/test_chat_completions.py`
at line 89, Update the assertion in the session-management chat completions test
to validate the complete normalized authorization message returned in
res["message"], ensuring the expected trailing punctuation behavior is enforced
rather than accepting any string containing “no authorization”.
| pytest.param({"doc_ids": ["invalid_id"], "run": "1"}, 109, "no authorization", marks=pytest.mark.p3), | ||
| pytest.param({"doc_ids": ["\n!?。;!?\"'"], "run": "1"}, 109, "no authorization", marks=pytest.mark.p3), |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Update the remaining authorization assertion in this file.
The changed cases now establish that this endpoint returns lowercase no authorization, but unchanged Line 134 still asserts No authorization. Since it covers the same response code (109), the test suite remains inconsistent and may fail.
Change Line 134 to no authorization.
Also applies to: 124-124, 304-305, 354-354
🧰 Tools
🪛 Ruff (0.15.21)
[warning] 92-92: String contains ambiguous ; (FULLWIDTH SEMICOLON). Did you mean ; (SEMICOLON)?
(RUF001)
[warning] 92-92: String contains ambiguous ! (FULLWIDTH EXCLAMATION MARK). Did you mean ! (EXCLAMATION MARK)?
(RUF001)
[warning] 92-92: String contains ambiguous ? (FULLWIDTH QUESTION MARK). Did you mean ? (QUESTION MARK)?
(RUF001)
🤖 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 `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around
lines 91 - 92, Update the remaining authorization-message assertions in
test_paser_documents.py, including the referenced additional locations, to
expect lowercase “no authorization” for response code 109. Keep the existing
test cases and response-code assertions unchanged.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17446 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 `@internal/handler/connector_test.go`:
- Around line 295-298: Update the wantData expectation in
TestConnectorHandlerDeleteConnector for the authentication-error
fakeConnectorService case to false, matching connectorErrorResponse’s data value
for service.ErrConnectorNoAuth.
🪄 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 Plus
Run ID: e86fc61a-0bbb-4286-9d53-ee600b78cabb
📒 Files selected for processing (24)
api/apps/restful_apis/document_api.pydocs/references/http_api_reference.mdinternal/handler/chat.gointernal/handler/chat_channel.gointernal/handler/chat_channel_test.gointernal/handler/chat_test.gointernal/handler/connector.gointernal/handler/connector_test.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/search.gointernal/handler/tenant.gointernal/service/chat_session.gointernal/service/connector.gointernal/service/dataset/tags.gointernal/service/dataset/tags_list_test.gointernal/service/dataset/tags_rename_test.gointernal/service/document/file2document.gointernal/service/file/file_content.gointernal/service/file/file_delete.gointernal/service/file/file_test.gotest/testcases/restful_api/test_documents.pytest/testcases/restful_api/test_searches.pytest/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
🚧 Files skipped from review as they are similar to previous changes (5)
- test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
- api/apps/restful_apis/document_api.py
- internal/service/connector.go
- internal/handler/tenant.go
- internal/service/chat_session.go
| service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")}, | ||
| wantCode: common.CodeAuthenticationError, | ||
| wantData: nil, | ||
| wantMsg: "No authorization.", | ||
| wantMsg: "no authorization", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Match the test data expectation to the handler response.
connectorErrorResponse returns data=false for service.ErrConnectorNoAuth, but this case expects wantData: nil; TestConnectorHandlerDeleteConnector will therefore fail. Change the expectation to false.
Proposed fix
- wantData: nil,
+ wantData: false,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")}, | |
| wantCode: common.CodeAuthenticationError, | |
| wantData: nil, | |
| wantMsg: "No authorization.", | |
| wantMsg: "no authorization", | |
| service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")}, | |
| wantCode: common.CodeAuthenticationError, | |
| wantData: false, | |
| wantMsg: "no authorization", |
🤖 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 `@internal/handler/connector_test.go` around lines 295 - 298, Update the
wantData expectation in TestConnectorHandlerDeleteConnector for the
authentication-error fakeConnectorService case to false, matching
connectorErrorResponse’s data value for service.ErrConnectorNoAuth.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
No description provided.