Skip to content

Go: add context to DAO - #17269

Merged
JinHai-CN merged 8 commits into
infiniflow:mainfrom
JinHai-CN:fix575
Jul 23, 2026
Merged

JinHai-CN merged 8 commits into
infiniflow:mainfrom
JinHai-CN:fix575

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

DAO layer doesn't use context, this PR is to fix it.

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 23, 2026 02:20
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 23, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 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

Handlers, services, startup, migrations, and DAOs now propagate request or signal-aware contexts through API-token, agent-session, chatbot, chat, authentication, statistics, and database operations.

Changes

Request Context Propagation

Layer / File(s) Summary
Context-aware DAO operations
internal/dao/api_token.go, internal/dao/chat.go, internal/dao/chat_channel.go, internal/dao/chat_session.go, internal/dao/canvas_template.go
DAO methods accept contexts and use DB.WithContext(ctx) for database operations.
Database initialization and migrations
internal/dao/database.go, internal/dao/migration.go, internal/dao/canvas_template_seed.go
Initialization, template seeding, and migration helpers forward contexts through schema operations.
Admin API-token and authentication context flow
internal/admin/*, internal/handler/api_token.go, internal/service/api_token.go, internal/service/user.go
Admin API-token management, system operations, and authentication flows pass request contexts into service and DAO layers.
Agent, chatbot, and statistics context flow
internal/handler/agent.go, internal/service/agent.go, internal/service/agent_sessions.go, internal/service/bot_completion.go, internal/handler/stats.go, internal/service/stats.go
Agent-session, agent-run, chatbot persistence, and statistics operations use propagated request contexts for database access.
Chat, channel, and session context flow
internal/handler/chat*.go, internal/service/chat*.go, internal/dao/chat_channel.go, internal/handler/mcp_server.go
Chat and chat-channel handlers and services pass contexts through authorization, listing, persistence, streaming, and MCP chat operations.
Test context propagation and signal-aware startup
internal/dao/*_test.go, internal/service/*_test.go, cmd/ragflow_server.go, build.sh, ragflow_deps/download_go_deps.py
Tests call context-aware DAO/service methods using t.Context(); server startup creates signal-aware contexts for database and API initialization; native dependency instructions reference download_go_deps.py.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

Suggested labels: ☯️ refactor

Suggested reviewers: haruko386, hz-186, euvre

Poem

I'm a rabbit with context in tow,
Through handlers and DAOs I go.
Queries now heed each request's flow,
Sessions and chats hop just so.
Hop, hop—cancellation can grow!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: adding context propagation to the DAO layer.
Description check ✅ Passed The description includes the required Summary section and clearly states the PR’s goal to add context to the DAO layer.
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: 1

🧹 Nitpick comments (1)
internal/dao/api_token.go (1)

116-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the migration-reference documentation.

Keep the runtime behavior description, but remove the Python implementation comparison.

As per coding guidelines, **/*.go documentation 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

📥 Commits

Reviewing files that changed from the base of the PR and between a5aa948 and 303e9ca.

📒 Files selected for processing (12)
  • internal/admin/handler.go
  • internal/admin/service.go
  • internal/dao/api_token.go
  • internal/handler/agent.go
  • internal/handler/api_token.go
  • internal/handler/stats.go
  • internal/service/agent.go
  • internal/service/agent_sessions.go
  • internal/service/api_token.go
  • internal/service/bot_completion.go
  • internal/service/stats.go
  • internal/service/user.go

Comment thread internal/dao/api_token.go
Comment on lines 131 to +132
// 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) {

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 | ⚡ 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 -200

Repository: 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 -n

Repository: 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.

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 303e9ca and b48578b.

📒 Files selected for processing (14)
  • build.sh
  • cmd/ragflow_server.go
  • internal/dao/api_token_beta_test.go
  • internal/dao/api_token_test.go
  • internal/dao/canvas_template.go
  • internal/dao/canvas_template_seed.go
  • internal/dao/canvas_template_seed_test.go
  • internal/dao/database.go
  • internal/dao/migration.go
  • internal/handler/agent.go
  • internal/service/agent.go
  • internal/service/agent_test.go
  • internal/service/bot_completion_history_test.go
  • ragflow_deps/download_go_deps.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/agent.go

Comment thread internal/dao/database.go

// InitDB initialize database connection
func InitDB(migrateDB bool) error {
func InitDB(ctx context.Context, migrateDB bool) error {

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 | ⚡ 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
done

Repository: 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 -n

Repository: 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-L67
  • internal/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

codecov Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 23, 2026
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: 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 win

Propagate cancellation through the fallback existence check.

In ChatDAO.UpdateByID, DB.Model(...).Count(...) bypasses WithContext(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 win

Let fake callbacks observe the forwarded context.

The fake accepts ctx but drops it before invoking its callback, so handler tests cannot detect a regression that substitutes or omits the request context. Include context.Context in 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

📥 Commits

Reviewing files that changed from the base of the PR and between b48578b and 1bba476.

📒 Files selected for processing (13)
  • cmd/ragflow_server.go
  • internal/dao/chat.go
  • internal/handler/chat.go
  • internal/handler/chat_channel.go
  • internal/handler/chat_channel_test.go
  • internal/handler/mcp_server.go
  • internal/service/chat.go
  • internal/service/chat_channel.go
  • internal/service/chat_channel_test.go
  • internal/service/chat_delete_test.go
  • internal/service/chat_list_test.go
  • internal/service/chat_rest_update_test.go
  • internal/service/openai_chat.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/ragflow_server.go

package handler

import (
"context"

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail
bash build.sh --test ./internal/parser/parser

Repository: 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.go

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

Comment thread internal/service/chat_channel.go Resolved
Comment thread internal/service/chat.go
Comment on lines +1278 to 1280
chats, err := s.chatDAO.QueryByTenantIDAndID(ctx, tenant.TenantID, chatID, "1")
if err != nil {
continue // Try next tenant

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

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1bba476 and 5f6687e.

📒 Files selected for processing (3)
  • internal/dao/chat_channel.go
  • internal/dao/chat_channel_test.go
  • internal/service/chat_channel.go

Comment on lines +100 to +101
func (s *ChatChannelService) accessible(ctx context.Context, userID, channelID string) (*entity.ChatChannel, bool, error) {
channel, err := s.chatChannelDAO.GetByIDOnly(ctx, channelID)

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

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.

@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

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 lift

Propagate session-persistence failures.

updateSessionMessages logs UpdateByID errors 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 at Completion, CompletionStream, and ChatCompletions call 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 win

Make SSE sends cancellation-aware.

CompletionStream now receives ctx, but direct streamChan <- ... sends can block indefinitely after the client disconnects and the handler stops consuming the channel. Select on ctx.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 win

Remove the compatibility-only entrypoint or verify an active external contract.

RemoveChatSessions is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5f6687e and 82b771e.

📒 Files selected for processing (13)
  • cmd/ragflow_server.go
  • internal/dao/chat_session.go
  • internal/dao/chat_session_test.go
  • internal/handler/agent.go
  • internal/handler/chat_session.go
  • internal/service/agent_sessions.go
  • internal/service/agent_test.go
  • internal/service/bot.go
  • internal/service/bot_completion.go
  • internal/service/chat_channel_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_contract_test.go
  • internal/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)

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

🧩 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.go

Repository: 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 || true

Repository: 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.go

Repository: 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.

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