Skip to content

Go: add context, part14 - #17446

Merged
JinHai-CN merged 15 commits into
infiniflow:mainfrom
JinHai-CN:fix591
Jul 28, 2026
Merged

JinHai-CN merged 15 commits into
infiniflow:mainfrom
JinHai-CN:fix591

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 27, 2026 14:10
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 27, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 27, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Context-aware data access and service flow

Layer / File(s) Summary
DAO contracts and transactions
internal/dao/*
User, canvas, canvas-version, and tenant DAO methods now accept context.Context and explicit *gorm.DB handles, including transactional helpers.
Service and handler propagation
internal/admin/*, internal/handler/*, internal/service/*
Request contexts are passed through authentication, administration, tenant, agent, chat, connector, dataset, document, model, search, and statistics operations.
Validation and test alignment
api/*, internal/*_test.go, test/testcases/*
Authorization and validation messages are normalized, and Go/Python tests are updated to match the revised contracts. OAuth registration now uses a transaction, and pipeline tests use context-bound database calls.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

Poem

A rabbit hops through every call,
With context carried through them all.
DAOs follow each request’s trail,
Tests and transactions align without fail.
Thump, thump—the paths now rhyme!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing, so it does not follow the required Summary template. Add a Summary section that briefly states the PR goal and the background context for these context-propagation changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.23% 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 is related to the code changes, but 'part14' makes it too vague to understand the main change at a glance. Use a short, specific title describing the primary change, such as context propagation for admin/service/DAO calls.
✅ 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.

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.

@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: 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 win

Restore the nil-context fallback in CompletionStream.

CompletionStream forwards ctx to DAO calls, checkTenantLLMAPIKey, AsyncChat, and updateSessionMessages; unlike ChatCompletions, it no longer normalizes nil to context.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 win

Do 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 win

Bind the user-provisioning transactions to the request context.

Both methods use ctx for pre-transaction reads, but transaction handles are started without context propagation, so later tx.Create calls can ignore request cancellation/deadlines.

  • internal/admin/service.go#L215: start the transaction with dao.DB.WithContext(ctx).Begin() before creating user/tenant data.
  • internal/service/user.go#L235: use db.WithContext(ctx).Transaction(...) so the writes honor Register’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 win

Use the test context for the service operation.

These tests now seed and assert with ctx, but their UpdateAgent/PublishAgent calls still use context.Background(), so they do not cover the intended request-context propagation.

  • internal/service/agent_test.go#L1453-L1454: pass ctx to UpdateAgent.
  • internal/service/agent_test.go#L1513-L1524: pass ctx to UpdateAgent.
  • internal/service/agent_test.go#L1576-L1585: pass ctx to UpdateAgent.
  • internal/service/agent_test.go#L1616-L1626: pass ctx to both UpdateAgent calls.
  • internal/service/agent_test.go#L1677-L1690: pass ctx to PublishAgent.
  • internal/service/agent_test.go#L1763-L1800: pass ctx to UpdateAgent.
🤖 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 win

Exercise the context-aware read with ctx.

The test seeds the database with t.Context() but invokes loadDSLFunc with context.Background(), so it does not verify request-context propagation through the new DAO call. Pass ctx to the load call instead; remove the context import 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 win

Propagate ctx into sandboxArtifactDialogIDsForUser too.

The new context reaches canvasDAO.Accessible, but sandboxArtifactDialogIDsForUser still executes its dao.DB.Rows() query without WithContext(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 win

Avoid parsing session.Reference twice.

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 value

Redundant .WithContext(ctx) calls in internal/dao/user.go and internal/dao/user_tenant.go. Both GetNicknameByID and GetByUserID chain db.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) in GetNicknameByID's query chain.
  • internal/dao/user_tenant.go#L62-L66: drop the second .WithContext(ctx) in GetByUserID'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

📥 Commits

Reviewing files that changed from the base of the PR and between 76acd49 and 05e9cbf.

📒 Files selected for processing (46)
  • internal/admin/handler.go
  • internal/admin/handler_ee.go
  • internal/admin/service.go
  • internal/admin/service_ee.go
  • internal/dao/user.go
  • internal/dao/user_canvas.go
  • internal/dao/user_canvas_test.go
  • internal/dao/user_canvas_version.go
  • internal/dao/user_canvas_version_test.go
  • internal/dao/user_tenant.go
  • internal/handler/agent.go
  • internal/handler/api_token.go
  • internal/handler/tenant.go
  • internal/handler/user.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_run_test.go
  • internal/service/agent.go
  • internal/service/agent_sessions.go
  • internal/service/agent_test.go
  • internal/service/bot.go
  • internal/service/chat.go
  • internal/service/chat_channel.go
  • internal/service/chat_session.go
  • internal/service/chat_session_contract_test.go
  • internal/service/chat_session_test.go
  • internal/service/chunk/chunk.go
  • internal/service/chunk_types.go
  • internal/service/connector.go
  • internal/service/dataset/create_test.go
  • internal/service/dataset/crud.go
  • internal/service/dataset/helpers.go
  • internal/service/dataset/update.go
  • internal/service/dataset/update_test.go
  • internal/service/document/document_artifact.go
  • internal/service/document/document_dataset_update.go
  • internal/service/document/document_list.go
  • internal/service/document/document_test.go
  • internal/service/ingestion_task_service.go
  • internal/service/model_service.go
  • internal/service/oauth_login.go
  • internal/service/pipeline_params.go
  • internal/service/search.go
  • internal/service/stats.go
  • internal/service/tenant.go
  • internal/service/tenant_test.go
  • internal/service/user.go

Comment thread internal/dao/user_canvas_version.go Resolved
Comment thread internal/handler/tenant.go Resolved
Comment thread internal/service/agent_sessions.go Resolved
Comment thread internal/service/chat_session.go Outdated
}
if !ok {
return false, "No authorization.", common.CodeAuthenticationError, errors.New("No authorization.")
return false, "No authorization.", common.CodeAuthenticationError, errors.New("no authorization")

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.

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

Comment thread internal/service/chunk_types.go Resolved
Comment thread internal/service/connector.go Outdated
Comment on lines 219 to 225
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

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.

🩺 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 as false, 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 invoking Accessible.
📍 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.

Comment on lines 159 to 162
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

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.

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

Comment thread internal/service/oauth_login.go Resolved

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 18d31ee and edd194b.

📒 Files selected for processing (52)
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/chat_channel_api.py
  • api/apps/restful_apis/connector_api.py
  • api/apps/restful_apis/dataset_api.py
  • api/apps/restful_apis/dify_retrieval_api.py
  • api/apps/restful_apis/document_api.py
  • api/apps/restful_apis/file2document_api.py
  • api/apps/restful_apis/search_api.py
  • api/apps/restful_apis/tenant_api.py
  • api/apps/services/dataset_api_service.py
  • api/apps/services/file_api_service.py
  • api/db/services/conversation_service.py
  • api/db/services/knowledgebase_service.py
  • api/utils/validation_utils.py
  • internal/dao/memory.go
  • internal/dao/user.go
  • internal/dao/user_tenant.go
  • internal/ingestion/task/pipeline_run_test.go
  • internal/service/agent_test.go
  • internal/service/chat_session.go
  • internal/service/document/document_artifact.go
  • test/testcases/restful_api/test_chats.py
  • test/testcases/restful_api/test_connector_routes_unit.py
  • test/testcases/restful_api/test_datasets.py
  • test/testcases/restful_api/test_documents.py
  • test/testcases/restful_api/test_file_routes_unit.py
  • test/testcases/restful_api/test_sessions.py
  • test/testcases/restful_api/test_user_tenant_routes_unit.py
  • test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
  • test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
  • test/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
  • test/testcases/test_http_api/test_dataset_management/test_create_dataset.py
  • test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
  • test/testcases/test_http_api/test_file_app/test_file_routes.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
  • test/testcases/test_http_api/test_session_management/test_chat_completions.py
  • test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
  • test/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
  • test/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
  • test/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
  • test/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.py
  • test/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.py
  • test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py
  • test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py
  • test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
  • test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
  • test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
  • test/testcases/test_web_api/test_document_app/test_paser_documents.py
  • test/testcases/test_web_api/test_document_app/test_upload_documents.py
  • test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
  • test/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"]

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.

🎯 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

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.

🎯 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”.

Comment on lines +91 to +92
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),

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.

🎯 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

codecov Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (b7ddf45) to head (ce51f84).
⚠️ Report is 2 commits behind head on main.

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

Signed-off-by: Jin Hai <[email protected]>

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between edd194b and ea97896.

📒 Files selected for processing (24)
  • api/apps/restful_apis/document_api.py
  • docs/references/http_api_reference.md
  • internal/handler/chat.go
  • internal/handler/chat_channel.go
  • internal/handler/chat_channel_test.go
  • internal/handler/chat_test.go
  • internal/handler/connector.go
  • internal/handler/connector_test.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/handler/search.go
  • internal/handler/tenant.go
  • internal/service/chat_session.go
  • internal/service/connector.go
  • internal/service/dataset/tags.go
  • internal/service/dataset/tags_list_test.go
  • internal/service/dataset/tags_rename_test.go
  • internal/service/document/file2document.go
  • internal/service/file/file_content.go
  • internal/service/file/file_delete.go
  • internal/service/file/file_test.go
  • test/testcases/restful_api/test_documents.py
  • test/testcases/restful_api/test_searches.py
  • test/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

Comment on lines +295 to +298
service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")},
wantCode: common.CodeAuthenticationError,
wantData: nil,
wantMsg: "No authorization.",
wantMsg: "no authorization",

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.

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

Suggested change
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.

@JinHai-CN
JinHai-CN merged commit 7f21a7b into infiniflow:main Jul 28, 2026
7 of 8 checks passed
buua436 pushed a commit to buua436/ragflow that referenced this pull request Jul 29, 2026
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