Repository navigation
Go: add context to DAO - #17269
Go: add context to DAO#17269
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:
📝 WalkthroughWalkthroughHandlers, services, startup, migrations, and DAOs now propagate request or signal-aware contexts through API-token, agent-session, chatbot, chat, authentication, statistics, and database operations. ChangesRequest Context Propagation
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 1
🧹 Nitpick comments (1)
internal/dao/api_token.go (1)
116-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the migration-reference documentation.
Keep the runtime behavior description, but remove the Python implementation comparison.
As per coding guidelines,
**/*.godocumentation comments must be aligned with the current runtime path rather than migration history.🤖 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/api_token.go` around lines 116 - 120, Update the documentation comment associated with Update in api_token.go by removing the Python conversation_service migration comparison and its reference, while preserving the description of the current runtime behavior for updating api_4_conversation rows.Source: Coding guidelines
🤖 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/api_token.go`:
- Around line 131-132: Update API4ConversationDAO.Stats to apply the received
ctx to the root database query before the statistics query is built and scanned.
Ensure the Scan operation propagates cancellation and deadlines through the
context-aware DB chain, while preserving the existing filters and results.
---
Nitpick comments:
In `@internal/dao/api_token.go`:
- Around line 116-120: Update the documentation comment associated with Update
in api_token.go by removing the Python conversation_service migration comparison
and its reference, while preserving the description of the current runtime
behavior for updating api_4_conversation rows.
🪄 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: 27976e3a-aff8-4073-b2d1-49a49730cdc2
📒 Files selected for processing (12)
internal/admin/handler.gointernal/admin/service.gointernal/dao/api_token.gointernal/handler/agent.gointernal/handler/api_token.gointernal/handler/stats.gointernal/service/agent.gointernal/service/agent_sessions.gointernal/service/api_token.gointernal/service/bot_completion.gointernal/service/stats.gointernal/service/user.go
| // Stats returns daily conversation aggregates for a tenant. | ||
| func (dao *API4ConversationDAO) Stats(tenantID, fromDate, toDate string, source *string) ([]ConversationStatsRow, error) { | ||
| func (dao *API4ConversationDAO) Stats(ctx context.Context, tenantID, fromDate, toDate string, source *string) ([]ConversationStatsRow, error) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate file =="
git ls-files | rg '(^|/)api_token\.go$|(^|/)models|gorm|database' || true
echo "== inspect relevant file outline/sections =="
if [ -f internal/dao/api_token.go ]; then
wc -l internal/dao/api_token.go
sed -n '1,220p' internal/dao/api_token.go | cat -n
fi
echo "== search DB globals and WithContext usage =="
rg -n "^(var|func)\s+(DB|DB2)\b|With\(Context|WithContext|DB\.Table|DB\.\(" internal pkg . --glob '*.go' | head -200Repository: infiniflow/ragflow
Length of output: 40258
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== GORM module version if present =="
if [ -f go.mod ]; then
rg 'gorm.io/gorm|gorm.io/driver/mysql|gorm.io/driver/postgres' go.mod go.sum | head -40
fi
echo "== local GORM WithContext implementation if vendored/modules cache present =="
modcache="$(go env GOMODCACHE 2>/dev/null || true)"
echo "GOMODCACHE=$modcache"
if [ -n "$modcache" ] && [ -d "$modcache/gorm.io/gorm" ]; then
rg -n "func \\(db \\*DB\\) WithContext|WithContext\\(" "$modcache/gorm.io/gorm" --glob '*.go' | head -80
sed -n '1,80p' "$modcache/gorm.io/gorm/gorm.go" | nl
else
echo "No local gorm.io/gorm source available"
fi
echo "== local DB declaration/initialization =="
sed -n '1,160p' internal/dao/database.go | cat -nRepository: infiniflow/ragflow
Length of output: 6042
Apply ctx to the statistics query.
Stats receives ctx, but the root query starts from the global DB without WithContext, so cancellation/deadlines are not propagated through the Scan(...) at lines 154-156.
Proposed fix
- db := DB.Table("api_4_conversation AS a").
+ db := DB.WithContext(ctx).Table("api_4_conversation AS a").📝 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.
| // Stats returns daily conversation aggregates for a tenant. | |
| func (dao *API4ConversationDAO) Stats(tenantID, fromDate, toDate string, source *string) ([]ConversationStatsRow, error) { | |
| func (dao *API4ConversationDAO) Stats(ctx context.Context, tenantID, fromDate, toDate string, source *string) ([]ConversationStatsRow, error) { | |
| db := DB.WithContext(ctx).Table("api_4_conversation AS a"). |
🤖 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/api_token.go` around lines 131 - 132, Update
API4ConversationDAO.Stats to apply the received ctx to the root database query
before the statistics query is built and scanned. Ensure the Scan operation
propagates cancellation and deadlines through the context-aware DB chain, while
preserving the existing filters and results.
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/dao/database.go`:
- Line 69: Make database initialization consistently cancellation-aware: update
InitDB in internal/dao/database.go (69-69), autoMigrateSafely in
internal/dao/migration.go (32-67), and SeedCanvasTemplates in
internal/dao/canvas_template_seed.go (39-40) to use DB.WithContext(ctx) for all
database operations, and propagate ctx through any startup helpers performing DB
work so cancellation stops remaining migrations and prevents reporting success
afterward.
🪄 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: ec987d70-6d52-4e85-8c86-2379fbd0bf9c
📒 Files selected for processing (14)
build.shcmd/ragflow_server.gointernal/dao/api_token_beta_test.gointernal/dao/api_token_test.gointernal/dao/canvas_template.gointernal/dao/canvas_template_seed.gointernal/dao/canvas_template_seed_test.gointernal/dao/database.gointernal/dao/migration.gointernal/handler/agent.gointernal/service/agent.gointernal/service/agent_test.gointernal/service/bot_completion_history_test.goragflow_deps/download_go_deps.py
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/handler/agent.go
|
|
||
| // InitDB initialize database connection | ||
| func InitDB(migrateDB bool) error { | ||
| func InitDB(ctx context.Context, migrateDB bool) error { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
git ls-files | rg '^internal/dao/(database|migration|canvas_template_seed)\.go$' || true
echo "== outlines =="
for f in internal/dao/database.go internal/dao/migration.go internal/dao/canvas_template_seed.go; do
if [ -f "$f" ]; then
echo "--- $f ($(wc -l < "$f") lines) ---"
ast-grep outline "$f" --view compact || true
fi
done
echo "== relevant contents =="
for f in internal/dao/database.go internal/dao/migration.go internal/dao/canvas_template_seed.go; do
if [ -f "$f" ]; then
echo "--- $f ---"
sed -n '1,140p' "$f" | cat -n
fi
doneRepository: infiniflow/ragflow
Length of output: 16734
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== database.go continuation =="
sed -n '140,220p' internal/dao/database.go | cat -n
echo "== migration helper outlines/search =="
rg -n "func (RunMigrations|addColumnIfNotExists|addColumnIfNotExistsWithDefault|renameColumnIfExists|migrate.*Context|modifyColumnTypes)" internal/dao -S
echo "== migration.go lines 80-240 =="
sed -n '80,240p' internal/dao/migration.go | cat -n
echo "== migration.go lines 240-679 =="
sed -n '240,679p' internal/dao/migration.go | cat -n
echo "== canvas_template_seed seed helpers lines 39-180 =="
sed -n '39,180p' internal/dao/canvas_template_seed.go | cat -nRepository: infiniflow/ragflow
Length of output: 37893
Make DB initialization consistently cancellation-aware.
Auto migrations use a plain DB for every model; if InitDB is canceled after the first model, remaining migrations still run and InitDB can later report success after the signal context is canceled. Use DB.WithContext(ctx) for autoMigrateSafely and SeedCanvasTemplates as well, and propagate context cancellation through any startup helper that performs DB work.
📍 Affects 3 files
internal/dao/database.go#L69-L69(this comment)internal/dao/migration.go#L32-L67internal/dao/canvas_template_seed.go#L39-L40
🤖 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/database.go` at line 69, Make database initialization
consistently cancellation-aware: update InitDB in internal/dao/database.go
(69-69), autoMigrateSafely in internal/dao/migration.go (32-67), and
SeedCanvasTemplates in internal/dao/canvas_template_seed.go (39-40) to use
DB.WithContext(ctx) for all database operations, and propagate ctx through any
startup helpers performing DB work so cancellation stops remaining migrations
and prevents reporting success afterward.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17269 +/- ##
==========================================
- Coverage 94.56% 90.65% -3.91%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 650 -28
- Misses 25 39 +14
- Partials 14 28 +14 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/dao/chat.go (1)
203-214: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winPropagate cancellation through the fallback existence check.
In
ChatDAO.UpdateByID,DB.Model(...).Count(...)bypassesWithContext(ctx), so the zero-row existence probe can continue after the original request context is cancelled.Proposed fix
- if err := DB.Model(&entity.Chat{}).Where("id = ?", id).Count(&count).Error; err != nil { + if err := DB.WithContext(ctx).Model(&entity.Chat{}).Where("id = ?", id).Count(&count).Error; err != nil {🤖 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/chat.go` around lines 203 - 214, Update the fallback existence check in ChatDAO.UpdateByID to apply the request context to the GORM query before Count, matching the existing context-aware Updates call. Keep the current count handling and gorm.ErrRecordNotFound behavior unchanged.
🧹 Nitpick comments (1)
internal/handler/chat_channel_test.go (1)
26-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLet fake callbacks observe the forwarded context.
The fake accepts
ctxbut drops it before invoking its callback, so handler tests cannot detect a regression that substitutes or omits the request context. Includecontext.Contextin the callback fields and assert it in a handler test.🤖 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/chat_channel_test.go` around lines 26 - 58, Update fakeChatChannelService callback fields and method invocations so CreateChatChannel, List, GetChatChannel, UpdateChatChannel, and DeleteChatChannel forward their context.Context argument to callbacks. Add or update a handler test to assert the callback receives the original request context, ensuring substitutions or omissions are detected.
🤖 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/chat_channel_test.go`:
- Line 4: Update the no-CGO PDF parser implementation, especially
PDFParser.ParseWithResult and its backend helper, to accept and propagate
context.Context so GetParser() satisfies the ParseResultProducer contract in
every build path. Keep the CGO and existing parsing behavior unchanged while
passing ctx through all affected PDF parsing calls.
In `@internal/service/chat_channel.go`:
- Around line 62-64: Propagate the request context through every ChatChannelDAO
operation in ChatChannelService: update List to call ListByTenantID with ctx;
make Insert and GetByID context-aware; pass ctx through accessible and channel
reloads; and update authorization, update, reload, and deletion calls to use
context-aware DAO methods. Apply these changes at
internal/service/chat_channel.go ranges 62-64, 66-97, 126-142, 145-216, and
219-234, preserving existing behavior while ensuring each persistence operation
receives the request context.
In `@internal/service/chat.go`:
- Around line 1278-1280: Update the error handling in GetChat around
QueryByTenantIDAndID so context cancellation and deadline-exceeded errors are
returned immediately instead of being treated as authorization failures; only
non-context query errors should continue to the next tenant.
---
Outside diff comments:
In `@internal/dao/chat.go`:
- Around line 203-214: Update the fallback existence check in ChatDAO.UpdateByID
to apply the request context to the GORM query before Count, matching the
existing context-aware Updates call. Keep the current count handling and
gorm.ErrRecordNotFound behavior unchanged.
---
Nitpick comments:
In `@internal/handler/chat_channel_test.go`:
- Around line 26-58: Update fakeChatChannelService callback fields and method
invocations so CreateChatChannel, List, GetChatChannel, UpdateChatChannel, and
DeleteChatChannel forward their context.Context argument to callbacks. Add or
update a handler test to assert the callback receives the original request
context, ensuring substitutions or omissions are detected.
🪄 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: 9cb61bf2-e204-425e-b807-94150243e2ab
📒 Files selected for processing (13)
cmd/ragflow_server.gointernal/dao/chat.gointernal/handler/chat.gointernal/handler/chat_channel.gointernal/handler/chat_channel_test.gointernal/handler/mcp_server.gointernal/service/chat.gointernal/service/chat_channel.gointernal/service/chat_channel_test.gointernal/service/chat_delete_test.gointernal/service/chat_list_test.gointernal/service/chat_rest_update_test.gointernal/service/openai_chat.go
🚧 Files skipped from review as they are similar to previous changes (1)
- cmd/ragflow_server.go
| package handler | ||
|
|
||
| import ( | ||
| "context" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
bash build.sh --test ./internal/parser/parserRepository: infiniflow/ragflow
Length of output: 849
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "== relevant Go files =="
git ls-files | rg '(^|/)(parser\.go|.*parser.*\.go|.*parser.*_test\.go)$' | sed -n '1,120p'
echo
echo "== build.sh section around parser/native dependency =="
sed -n '1,260p' build.sh | nl -ba | sed -n '1,260p'
echo
echo "== parse producer/interface definitions =="
rg -n "type ParseResultProducer|interface\\s+ParseResultProducer|func \\(|Context\\)\\s*" -g '*.go' internal | sed -n '1,220p'Repository: infiniflow/ragflow
Length of output: 6201
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "== candidate parser files =="
python3 - <<'PY'
import subprocess, pathlib, re
files = subprocess.check_output(['git','ls-files'], text=True).splitlines()
m = pathlib.Path()
for f in sorted(files):
if f.endswith('.go') and 'parser' in f.lower():
print(f)
PY
echo
echo "== exact definitions/usages =="
rg -n "type ParseResultProducer|interface ParseResultProducer|func .*Parser|New.*Parser|Parse\\(" -g '*.go' internal/parser internal | sed -n '1,240p'Repository: infiniflow/ragflow
Length of output: 33895
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "== parse_result.go =="
sed -n '1,180p' internal/parser/parser/parse_result.go
echo
echo "== office_parsers_no_cgo.go =="
sed -n '1,140p' internal/parser/parser/office_parsers_no_cgo.go
echo
echo "== pdf nocgo/cgo helpers context signatures =="
for f in internal/parser/parser/pdf_parser_nocgo.go internal/parser/parser/pdf_parser_cgo.go internal/parser/parser/pdf_parser_plaintext_nocgo.go internal/parser/parser/pdf_parser_plaintext_cgo.go internal/parser/parser/pdf_parser_mineru.go internal/parser/parser/pdf_parser_tcadp.go internal/parser/parser/pdf_parser_somark.go internal/parser/parser/pdf_parser_opendataloader.go internal/parser/parser/pdf_parser_paddleocr.go; do
echo "--- $f"
rg -n "func .*|parsePDF|parsePDFWith|NewParser|ParseWithResult|context.Context" "$f"
done
echo
echo "== pdf common interface/usages around parser ctx =="
sed -n '1,220p' internal/parser/parser/pdf_parser_common.goRepository: infiniflow/ragflow
Length of output: 16864
Add ctx parameters to the remaining PDF parser paths.
GetParser() still returns PDFParser for ParseResultProducer, but pdf_parser_nocgo.go defines ParseWithResult without a context.Context argument, so the no-CGO build path does not implement the package contract. Update the Nocgo implementation and any PDF backend helper that currently omits ctx.
🤖 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/chat_channel_test.go` at line 4, Update the no-CGO PDF
parser implementation, especially PDFParser.ParseWithResult and its backend
helper, to accept and propagate context.Context so GetParser() satisfies the
ParseResultProducer contract in every build path. Keep the CGO and existing
parsing behavior unchanged while passing ctx through all affected PDF parsing
calls.
Sources: Coding guidelines, Linters/SAST tools
| chats, err := s.chatDAO.QueryByTenantIDAndID(ctx, tenant.TenantID, chatID, "1") | ||
| if err != nil { | ||
| continue // Try next tenant |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Do not convert cancellation into “no authorization.”
A cancelled/deadline-exceeded query is ignored here, causing GetChat to return an authorization error instead of the request error.
Proposed fix
if err != nil {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
continue
}📝 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.
| chats, err := s.chatDAO.QueryByTenantIDAndID(ctx, tenant.TenantID, chatID, "1") | |
| if err != nil { | |
| continue // Try next tenant | |
| chats, err := s.chatDAO.QueryByTenantIDAndID(ctx, tenant.TenantID, chatID, "1") | |
| if err != nil { | |
| if ctx.Err() != nil { | |
| return nil, ctx.Err() | |
| } | |
| continue // Try next tenant |
🤖 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.go` around lines 1278 - 1280, Update the error handling
in GetChat around QueryByTenantIDAndID so context cancellation and
deadline-exceeded errors are returned immediately instead of being treated as
authorization failures; only non-context query errors should continue to the
next tenant.
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/service/chat_channel.go`:
- Around line 100-101: Update userTenantDAO.GetTenantIDsByUserID to accept a
context.Context parameter, then pass the ctx received by
ChatChannelService.accessible into that call so tenant-membership authorization
queries honor request cancellation.
🪄 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: f6aa7e28-6703-4c1e-8954-c0e99a9d6ff9
📒 Files selected for processing (3)
internal/dao/chat_channel.gointernal/dao/chat_channel_test.gointernal/service/chat_channel.go
| func (s *ChatChannelService) accessible(ctx context.Context, userID, channelID string) (*entity.ChatChannel, bool, error) { | ||
| channel, err := s.chatChannelDAO.GetByIDOnly(ctx, channelID) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Propagate ctx to the tenant-membership authorization query.
accessible now accepts ctx, but its userTenantDAO.GetTenantIDsByUserID(userID) call remains contextless. A cancelled request can therefore leave this authorization DB read running. Make that DAO method context-aware and pass ctx 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_channel.go` around lines 100 - 101, Update
userTenantDAO.GetTenantIDsByUserID to accept a context.Context parameter, then
pass the ctx received by ChatChannelService.accessible into that call so
tenant-membership authorization queries honor request cancellation.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/service/chat_session.go (2)
2127-2146: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftPropagate session-persistence failures.
updateSessionMessageslogsUpdateByIDerrors and returns no error, so completion methods can report success while the answer was not persisted. Return an error from this helper and handle it atCompletion,CompletionStream, andChatCompletionscall sites.🤖 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 2127 - 2146, The updateSessionMessages helper should return errors instead of logging and swallowing marshal or UpdateByID failures. Propagate each failure to its callers, and update Completion, CompletionStream, and ChatCompletions to handle the returned error so they do not report success when session persistence fails.
1349-1423: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winMake SSE sends cancellation-aware.
CompletionStreamnow receivesctx, but directstreamChan <- ...sends can block indefinitely after the client disconnects and the handler stops consuming the channel. Select onctx.Done()for every send and return on cancellation to avoid leaking the streaming goroutine.🤖 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 1349 - 1423, Update CompletionStream so every streamChan send, including validation, error, and result messages, selects between sending and ctx.Done(). Return the context cancellation error when cancellation wins, while preserving existing responses and normal streaming behavior.
🧹 Nitpick comments (1)
internal/service/chat_session.go (1)
177-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the compatibility-only entrypoint or verify an active external contract.
RemoveChatSessionsis explicitly retained for older callers. The repository guidelines prefer deletion over compatibility shims; remove this surface unless a current contract still requires it.As per coding guidelines, compatibility-only surfaces and migration-history wording should be removed unless required by the current implementation.
🤖 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 177 - 179, Remove the compatibility-only ChatSessionService.RemoveChatSessions entrypoint and its migration-history comment, along with any now-unused references or supporting code; preserve the current chat-session removal API and behavior required by active callers.Source: Coding guidelines
🤖 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/service/chat_session.go`:
- Line 180: Thread the request context through
UserTenantDAO.GetTenantIDsByUserID and TenantDAO.GetByID, updating their
signatures and all chat-session call sites for tenant lookups and the
default-model lookup to use ctx rather than background context. Remove the
compatibility-only RemoveChatSessions, Completion, and CompletionStream
entrypoint wrappers, along with stale tests that only protect those paths.
---
Outside diff comments:
In `@internal/service/chat_session.go`:
- Around line 2127-2146: The updateSessionMessages helper should return errors
instead of logging and swallowing marshal or UpdateByID failures. Propagate each
failure to its callers, and update Completion, CompletionStream, and
ChatCompletions to handle the returned error so they do not report success when
session persistence fails.
- Around line 1349-1423: Update CompletionStream so every streamChan send,
including validation, error, and result messages, selects between sending and
ctx.Done(). Return the context cancellation error when cancellation wins, while
preserving existing responses and normal streaming behavior.
---
Nitpick comments:
In `@internal/service/chat_session.go`:
- Around line 177-179: Remove the compatibility-only
ChatSessionService.RemoveChatSessions entrypoint and its migration-history
comment, along with any now-unused references or supporting code; preserve the
current chat-session removal API and behavior required by active callers.
🪄 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: 82c7bdca-06d9-4252-ae99-534d69b37ae0
📒 Files selected for processing (13)
cmd/ragflow_server.gointernal/dao/chat_session.gointernal/dao/chat_session_test.gointernal/handler/agent.gointernal/handler/chat_session.gointernal/service/agent_sessions.gointernal/service/agent_test.gointernal/service/bot.gointernal/service/bot_completion.gointernal/service/chat_channel_test.gointernal/service/chat_session.gointernal/service/chat_session_contract_test.gointernal/service/chat_session_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
- internal/service/bot_completion.go
- internal/handler/agent.go
- internal/service/chat_channel_test.go
- internal/service/agent_sessions.go
- cmd/ragflow_server.go
| // Kept as a compatibility entrypoint for older chat-session callers. | ||
| func (s *ChatSessionService) RemoveChatSessions(userID string, chatSessions []string) error { | ||
| func (s *ChatSessionService) RemoveChatSessions(ctx context.Context, userID string, chatSessions []string) error { | ||
| tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
git ls-files | rg '(^|/)internal/service/chat_session\.go$|userTenantDAO|TenantID|AsyncChat|GetTenantIDs|DefaultModel|ChatSessions' || true
echo
echo "== outline chat_session =="
ast-grep outline internal/service/chat_session.go --match 'ChatSession' --view expanded || true
echo
echo "== relevant sections =="
sed -n '150,270p' internal/service/chat_session.go
echo "----"
sed -n '650,700p' internal/service/chat_session.go
echo "----"
sed -n '1080,1130p' internal/service/chat_session.go
echo "----"
sed -n '1240,1330p' internal/service/chat_session.go
echo "----"
sed -n '1510,1575p' internal/service/chat_session.goRepository: infiniflow/ragflow
Length of output: 17397
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== search GetTenantIDsByUserID definition/usages =="
rg -n "GetTenantIDsByUserID|type userTenantStore|AsyncChat|NewTenantDAO\\(\\)\\.GetByID|checkTenantLLMAPIKey|buildDefaultCompletionDialog|CreateSessionFor" --glob '*.go' .
echo
echo "== candidate DAO files =="
fd -e go -t f . . | rg 'user.*tenant|tenant|session|pipeline|model|doc.*engine' || true
echo
echo "== chat_pipeline runner definitions =="
rg -n "type .*chatPipelineRunner|func .*AsyncChat|AsyncChat\\(" --glob '*.go' internal || trueRepository: infiniflow/ragflow
Length of output: 25873
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== user_tenant DAO =="
sed -n '1,120p' internal/dao/user_tenant.go
echo
echo "== tenant DAO GetByID =="
sed -n '1,220p' internal/dao/tenant.go
echo
echo "== chat_session service relevant sections =="
sed -n '130,260p' internal/service/chat_session.go
echo "----"
sed -n '660,700p' internal/service/chat_session.go
echo "----"
sed -n '1345,1405p' internal/service/chat_session.go
echo "----"
sed -n '1565,1635p' internal/service/chat_session.go
echo "----"
sed -n '1788,1815p' internal/service/chat_session.go
echo "----"
sed -n '1945,2085p' internal/service/chat_session.goRepository: infiniflow/ragflow
Length of output: 25133
Propagate ctx to uncancelled DB operations throughout chat-session flow.
UserTenantDAO.GetTenantIDsByUserID and TenantDAO.GetByID still run with default/background DB context, while later persistence calls use ctx. Thread the request context through these stores/DAO methods before the tenant lookups at 180, 247, 684, 1116 and the default-model lookup at 1549. Also remove the compatibility-only RemoveChatSessions/Completion/CompletionStream entrypoint wrappers so tests don’t guard stale paths.
🤖 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 180, Thread the request context
through UserTenantDAO.GetTenantIDsByUserID and TenantDAO.GetByID, updating their
signatures and all chat-session call sites for tenant lookups and the
default-model lookup to use ctx rather than background context. Remove the
compatibility-only RemoveChatSessions, Completion, and CompletionStream
entrypoint wrappers, along with stale tests that only protect those paths.
Summary
DAO layer doesn't use context, this PR is to fix it.