Skip to content

Go: add context, part4 - #17381

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
JinHai-CN:fix580
Jul 26, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
JinHai-CN:fix580

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

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

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dcf43b18-0e96-4da1-b07e-6760a2127851

📥 Commits

Reviewing files that changed from the base of the PR and between 8df1134 and 2c25c3f.

📒 Files selected for processing (2)
  • internal/ingestion/service/execute_task_ack_test.go
  • internal/ingestion/testutil/helpers.go

📝 Walkthrough

Walkthrough

Ingestion-task, ingestion-log, and file-commit database operations now accept explicit contexts and database handles. Contexts propagate through ingestion execution, cancellation, progress, document, chunk, file, and admin services, with tests updated for the new APIs.

Changes

Context propagation

Layer / File(s) Summary
Context-aware DAO access
internal/dao/file_commit.go, internal/dao/ingestion.go, internal/dao/ingestion_task_test.go
DAO methods now accept context.Context and *gorm.DB, using context-bound database queries.
Ingestion service and execution context
internal/service/ingestion_task_service.go, internal/ingestion/service/*, internal/ingestion/task/pipeline_e2e_test.go
Ingestion state transitions, cancellation checks, settlement, progress updates, and execution paths forward context values.
Application caller wiring
internal/admin/*, internal/service/document/*, internal/service/chunk/*, internal/service/file/*
Updated service and DAO callers pass request contexts and explicit database handles; one chunk error message uses lowercase capitalization.

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

Suggested labels: ☯️ refactor

Suggested reviewers: xugangqiang, yingfeng, yuzhichang

Poem

I’m a rabbit with context tucked tight,
Passing through burrows from morning to night.
DAOs hold databases, tasks hop in line,
Cancellations and progress now travel just fine.
With tests following softly behind—
The whole carrot patch stays well aligned!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided, so the required Summary section and background context are missing. Add the template's Summary section with the PR goal, brief background, and any key implementation notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 42.42% 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 matches the general theme, but it is too vague to identify the main change. Use a concise title that names the primary change, such as propagating request context through ingestion and DAO layers.
✅ 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.

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
internal/ingestion/service/ingestion_service.go (2)

388-400: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Persist terminal state with a non-canceled context.

When polling cancels taskCtx.Ctx, runDocumentTask returns context.Canceled, then Line 392 calls markStopped with that already-canceled context. Both state writes fail, leaving the task non-terminal and repeatedly nacked. Use a durable context for terminal persistence, as the earlier cancellation branch already does.

🤖 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/service/ingestion_service.go` around lines 388 - 400,
Update the context passed to terminal state persistence in the context.Canceled
branch of the runDocumentTask error handling: call markStopped with the
durable/non-canceled context used by the earlier cancellation flow, while
preserving the existing cancellation logging and progress update.

560-570: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Cancel outstanding polling checks when the task exits.

checkOnce runs cancelCheck(e.ctx, ...); its DB fallback can block beyond cancelDone, and each tick can leave another goroutine behind. Derive a polling context canceled during executeTask cleanup and pass it into cancelCheck.

🤖 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/service/ingestion_service.go` around lines 560 - 570,
Update the polling flow around Ingestor.pollCancel and its caller executeTask to
use a derived polling context, pass that context to cancelCheck instead of
e.ctx, and cancel it during executeTask cleanup so blocked or outstanding
polling checks terminate when the task exits.
internal/service/document/document_parse.go (1)

77-87: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not clear parse results after a failed task-state lookup.

The ignored lookup error makes this path proceed to counter/chunk deletion without proving the task is terminal. DeleteIfTerminal preserves a RUNNING task row, but the worker can still write into results being cleared. Return the lookup error before continuing.

Proposed fix
-	if task, _ := s.ingestionTaskDAO.GetByDocumentID(ctx, dao.DB, doc.ID); task != nil {
+	task, err := s.ingestionTaskDAO.GetByDocumentID(ctx, dao.DB, doc.ID)
+	if err != nil {
+		return fmt.Errorf("get ingestion task for %s: %w", doc.ID, err)
+	}
+	if task != 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/service/document/document_parse.go` around lines 77 - 87, Update the
ingestion-task lookup in the document re-parse flow before the status check to
capture and return any error from ingestionTaskDAO.GetByDocumentID immediately.
Only continue to task-state validation and DeleteIfTerminal after a successful
lookup, preserving the existing RUNNING/STOPPING handling.
🧹 Nitpick comments (1)
internal/ingestion/service/ingestion_service.go (1)

73-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove migration-history wording from runtime comments.

Describe the current Go handler and cancel behavior without “migrated” or references to Python implementation history. As per coding guidelines, “keep package and documentation comments 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/ingestion/service/ingestion_service.go` around lines 73 - 83, Update
the comments for runDocumentTask and cancelCheck to describe only their current
Go dispatch and cancellation behavior. Remove the “migrated” wording and the
reference to Python’s has_canceled() implementation history, while retaining the
testing override and cancellation polling details.

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/ingestion/service/execute_task_ack_test.go`:
- Line 136: Update the executeTask invocation in the cancellation test to pass
the already-canceled ctx instead of t.Context(). Keep the existing newAckTaskCtx
arguments unchanged so the test exercises pre-execution cancellation.

In `@internal/service/file/file_commit.go`:
- Around line 54-56: Update CreateCommit to start the creation transaction from
the request context ctx rather than the unbound dao.DB handle, ensuring all
transactional database operations respect cancellation and deadlines before
commit writes proceed.

---

Outside diff comments:
In `@internal/ingestion/service/ingestion_service.go`:
- Around line 388-400: Update the context passed to terminal state persistence
in the context.Canceled branch of the runDocumentTask error handling: call
markStopped with the durable/non-canceled context used by the earlier
cancellation flow, while preserving the existing cancellation logging and
progress update.
- Around line 560-570: Update the polling flow around Ingestor.pollCancel and
its caller executeTask to use a derived polling context, pass that context to
cancelCheck instead of e.ctx, and cancel it during executeTask cleanup so
blocked or outstanding polling checks terminate when the task exits.

In `@internal/service/document/document_parse.go`:
- Around line 77-87: Update the ingestion-task lookup in the document re-parse
flow before the status check to capture and return any error from
ingestionTaskDAO.GetByDocumentID immediately. Only continue to task-state
validation and DeleteIfTerminal after a successful lookup, preserving the
existing RUNNING/STOPPING handling.

---

Nitpick comments:
In `@internal/ingestion/service/ingestion_service.go`:
- Around line 73-83: Update the comments for runDocumentTask and cancelCheck to
describe only their current Go dispatch and cancellation behavior. Remove the
“migrated” wording and the reference to Python’s has_canceled() implementation
history, while retaining the testing override and cancellation polling details.
🪄 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: 6d937ec3-296e-4f76-bd73-efb11c91ee64

📥 Commits

Reviewing files that changed from the base of the PR and between f4646d4 and f280f3f.

📒 Files selected for processing (22)
  • internal/admin/handler.go
  • internal/admin/service.go
  • internal/dao/file_commit.go
  • internal/dao/ingestion.go
  • internal/dao/ingestion_task_test.go
  • internal/ingestion/service/execute_task_ack_test.go
  • internal/ingestion/service/execute_task_test.go
  • internal/ingestion/service/ingestion_service.go
  • internal/ingestion/service/ingestor_lifecycle_test.go
  • internal/ingestion/service/progress_sink.go
  • internal/ingestion/service/progress_sink_test.go
  • internal/ingestion/service/run_task_test.go
  • internal/ingestion/task/pipeline_e2e_test.go
  • internal/service/chunk/chunk.go
  • internal/service/chunk/chunk_test.go
  • internal/service/document/document_crud.go
  • internal/service/document/document_ingest.go
  • internal/service/document/document_parse.go
  • internal/service/document/document_test.go
  • internal/service/file/file_commit.go
  • internal/service/ingestion_task_service.go
  • internal/service/ingestion_task_service_test.go

Comment thread internal/service/file/file_commit.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: 2

🤖 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/kb.go`:
- Around line 83-85: Update the callers of KnowledgebaseDAO methods in
kb_test.go, including the cases around the referenced test calls, to pass the
required context and *gorm.DB arguments matching the new GetByID signatures. Use
the appropriate existing test context and database handle, then validate the DAO
package with the repository’s build.sh rather than raw go test.
- Around line 68-85: Update the DAO methods shown, including Update, UpdateByID,
Delete, and GetByID, to use db.WithContext(ctx) as the GORM root instead of the
package-global DB. Preserve each method’s existing query, update, and return
behavior while ensuring caller-provided transactions, databases, and context
cancellation are honored; apply the same change to any nearby DB.Raw operations.
🪄 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: d4bc6c58-9d02-41b6-b239-c95d294d5fec

📥 Commits

Reviewing files that changed from the base of the PR and between f280f3f and 7f6da20.

📒 Files selected for processing (3)
  • internal/dao/kb.go
  • internal/ingestion/service/execute_task_ack_test.go
  • internal/service/file/file_commit.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/file/file_commit.go
  • internal/ingestion/service/execute_task_ack_test.go

Comment thread internal/dao/kb.go Outdated
Comment on lines 68 to 85
func (dao *KnowledgebaseDAO) Update(ctx context.Context, db *gorm.DB, kb *entity.Knowledgebase) error {
return DB.Save(kb).Error
}

// UpdateByID updates a knowledge base by ID with the given fields
func (dao *KnowledgebaseDAO) UpdateByID(id string, updates map[string]interface{}) error {
func (dao *KnowledgebaseDAO) UpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) error {
return DB.Model(&entity.Knowledgebase{}).Where("id = ?", id).Updates(updates).Error
}

// Delete soft deletes a knowledge base by setting status to invalid
func (dao *KnowledgebaseDAO) Delete(id string) error {
func (dao *KnowledgebaseDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
return DB.Model(&entity.Knowledgebase{}).Where("id = ?", id).Update("status", string(entity.StatusInvalid)).Error
}

// GetByID retrieves a knowledge base by ID
func (dao *KnowledgebaseDAO) GetByID(id string) (*entity.Knowledgebase, error) {
func (dao *KnowledgebaseDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.Knowledgebase, error) {
var kb entity.Knowledgebase
err := DB.Where("id = ? AND status = ?", id, string(entity.StatusValid)).First(&kb).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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
git ls-files | rg '(^|/)kb\.go$|internal/dao' || true

echo
echo "kb.go outline:"
ast-grep outline internal/dao/kb.go --view expanded || true

echo
echo "kb.go relevant sections:"
sed -n '1,90p' internal/dao/kb.go
printf '\n---\n'
sed -n '90,185p' internal/dao/kb.go
printf '\n---\n'
sed -n '225,325p' internal/dao/kb.go
printf '\n---\n'
sed -n '360,435p' internal/dao/kb.go
printf '\n---\n'
sed -n '455,495p' internal/dao/kb.go
printf '\n---\n'
sed -n '555,580p' internal/dao/kb.go

echo
echo "Search DB/KnowledgebaseDAO usages:"
rg -n '\bDB\.|Update\(.*context|UpdateByID\(.*context|Delete\(.*context|GetByID\(.*context|KnowledgebaseDAO' internal -S || true

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "kb.go import package context check:"
sed -n '1,15p' internal/dao/kb.go

echo
echo "KnowledgebaseDAO method calls, grouped by call target and line:"
python3 - <<'PY'
import pathlib, re
p=pathlib.Path('internal/dao/kb.go')
text=p.read_text()
for m in re.finditer(r'(NewKnowledgebaseDAO|GetTenantIDByKBID)\b|[A-Z][a-zA-Z0-9_]*(ctx context\.Context, db \*gorm\.DB)[^=\n]*(?:\[.*\])?\{\n|ReturnStatement', text):
    pass
PY

# Programmatic read-only verifier: scan KnowledgebaseDAO methods and helper GetTenantIDByKBID for DB vs db usage.
python3 - <<'PY'
import pathlib, re

p=pathlib.Path('internal/dao/kb.go')
text = p.read_text()
lines = text.splitlines()

# Extract function declarations by line number from relevant section using simple source-ish scan.
decls = []
for i,l in enumerate(lines,1):
    if re.search(r'(?:func \(dao \*KnowledgebaseDAO\)|func GetTenantIDByKBID)\b', l):
        # collect until next same-level func declaration
        start=i
        depth=0
        func_re=re.compile(r'\bfunc\b')
        body = []
        in_body=False
        for j in range(i, len(lines)+1):
            s=lines[j-1]
            if j>i and func_re.search(s) and re.search(r'\bfunc\b', s) and s.count('{)<=0 and s.count(')')<=1:
                continue
            if j==i:
                in_body=True
            if in_body:
                body.append((j, s))
                if j==i:
                    open_b=s.count('{')
                    close_b=s.count('}')
                else:
                    open_b += s.count('{')
                    close_b += s.count('}')
                if open_b>0 and open_b==close_b:
                    decls.append((start, tuple(body)))
                    break

import ast
print(f"KnowledgebaseDAO-like declarations found: {len(decls)}")
problems=[]
ctx_re=re.compile(r'\bctx\b')
db_param_re=re.compile(r'\bdb\s*:\s*\*gorm\.DB\b')
for start,body in decls:
    head=start
    txt='\n'.join(s for _,s in body)
    if 'ctx' not in txt and 'db' not in txt:
        continue
    uses_glob_DB = bool(re.search(r'\bDB\b', txt))
    uses_param_db = bool(re.search(r'\bdb(?!\.)\b', txt))
    if uses_glob_DB and uses_param_db and head<180 or uses_glob_DB:
        # Keep direct calls from KnowledgebaseDAO methods/GetTenantIDByKBID for clarity
        locs=', '.join(str(line) for line,(s) in body if re.search(r'\b(?:DB|db\.WithContext|db\.With)', s))
        print(f"{head}-{body[-1][0]} uses_global_DB={uses_glob_DB} uses_param_db_handle={uses_param_db} lines={locs}")
        problems.append((head,body[-1][0], uses_glob_DB, uses_param_db))

if not problems:
    print("No problems found.")
else:
    print(f"Total problematic declarations that still use package-global DB: {sum(p[2] for p in problems)}")
PY

Repository: infiniflow/ragflow

Length of output: 1184


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "package context import:"
sed -n '1,40p' internal/dao/kb.go

echo
echo "KnowledgebaseDAO/GetTenantIDByKBID lines still using package-global DB:"
python3 - <<'PY'
from pathlib import Path
import re

lines = Path("internal/dao/kb.go").read_text().splitlines()
state = None
current = []

for i, raw in enumerate(lines, 1):
    if state is None:
        if re.search(r'(?:func \(dao \*KnowledgebaseDAO\)|func GetTenantIDByKBID)\b', raw):
            state = "start"
    if state == "start":
        state = "body"
    if state == "body":
        current.append((i, raw))
        if current:
            open_braces = sum(s.count("{") for _, s in current)
            close_braces = sum(s.count("}") for _, s in current)
            if open_braces > 0 and open_braces == close_braces:
                body_text = "\n".join(s for _, s in current)
                uses_global_db = bool(re.search(r"\bDB\b", body_text))
                uses_context = bool(re.search(r"context\.Context", body_text))
                if uses_global_db:
                    db_lines = ", ".join(map(str, [line for line, s in current if re.search(r"\bDB\b", s)]))
                    print(f"{current[0][0]}-{current[-1][0]} accepts_context={'context.Context' in body_text} DB_lines={db_lines}")
                current = []
                state = None

if current:
    body_text = "\n".join(s for _, s in current)
    if re.search(r"\bDB\b", body_text):
        db_lines = ", ".join(map(str, [line for line, s in current if re.search(r"\bDB\b", s)]))
        print(f"{current[0][0]}-{current[-1][0]} accepts_context={'context.Context' in body_text} DB_lines={db_lines}")
PY

Repository: infiniflow/ragflow

Length of output: 1510


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "KnowledgebaseDAO/GetTenantIDByKBID global DB lines with relevant code:"
python3 - <<'PY'
from pathlib import Path
import re

lines = Path("internal/dao/kb.go").read_text().splitlines()
state = None
current = []

for i, raw in enumerate(lines, 1):
    if state is None:
        if re.search(r'(?:func \(dao \*KnowledgebaseDAO\)|func GetTenantIDByKBID)\b', raw):
            state = "start"
    if state == "start":
        state = "body"
    if state == "body":
        current.append((i, raw))
        if current:
            open_braces = sum(s.count("{") for _, s in current)
            close_braces = sum(s.count("}") for _, s in current)
            if open_braces > 0 and open_braces == close_braces:
                print("---")
                print(f"Range: {current[0][0]}-{current[-1][0]} imports_context={'context.Context' in '\\n'.join(s for _, s in current)}")
                for line, s in current:
                    if re.search(r'\bDB\b', s):
                        print(f"{line}: {s}")
                current = []
                state = None

if current:
    print("---")
    print(f"Range: {current[0][0]}-{current[-1][0]} imports_context={'context.Context' in '\\n'.join(s for _, s in current)}")
    for line, s in current:
        if re.search(r'\bDB\b', s):
            print(f"{line}: {s}")
PY

Repository: infiniflow/ragflow

Length of output: 572


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "KnowledgebaseDAO/GetTenantIDByKBID global DB lines with relevant code:"
python3 - <<'PY'
from pathlib import Path
import re

lines = Path("internal/dao/kb.go").read_text().splitlines()
state = None
current = []
def join_current():
    return "\n".join(s for _, s in current)

for i, raw in enumerate(lines, 1):
    if state is None:
        if re.search(r'(?:func \(dao \*KnowledgebaseDAO\)|func GetTenantIDByKBID)\b', raw):
            state = "start"
    if state == "start":
        state = "body"
    if state == "body":
        current.append((i, raw))
        if current:
            open_braces = sum(s.count("{") for _, s in current)
            close_braces = sum(s.count("}") for _, s in current)
            if open_braces > 0 and open_braces == close_braces:
                print("---")
                print("Range:", f"{current[0][0]}-{current[-1][0]}")
                print("imports_context:", "context.Context" in join_current())
                for line, s in current:
                    if re.search(r'\bDB\b', s):
                        print(f"{line}: {s}")
                current = []
                state = None

if current:
    print("---")
    print("Range:", f"{current[0][0]}-{current[-1][0]}")
    print("imports_context:", "context.Context" in join_current())
    for line, s in current:
        if re.search(r'\bDB\b', s):
            print(f"{line}: {s}")
PY

Repository: infiniflow/ragflow

Length of output: 358


Use the injected db and bind ctx for every DAO operation.

These methods accept ctx and db, but continue using package-global DB, so caller-provided transactions, test databases, and request cancellation are ignored. Replace each DB root, including DB.Raw, with a handle derived from db.WithContext(ctx).

Proposed pattern
- return DB.Save(kb).Error
+ return db.WithContext(ctx).Save(kb).Error

- err := DB.Where("id = ? AND status = ?", id, status).First(&kb).Error
+ err := db.WithContext(ctx).
+   Where("id = ? AND status = ?", id, status).
+   First(&kb).Error
📝 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
func (dao *KnowledgebaseDAO) Update(ctx context.Context, db *gorm.DB, kb *entity.Knowledgebase) error {
return DB.Save(kb).Error
}
// UpdateByID updates a knowledge base by ID with the given fields
func (dao *KnowledgebaseDAO) UpdateByID(id string, updates map[string]interface{}) error {
func (dao *KnowledgebaseDAO) UpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) error {
return DB.Model(&entity.Knowledgebase{}).Where("id = ?", id).Updates(updates).Error
}
// Delete soft deletes a knowledge base by setting status to invalid
func (dao *KnowledgebaseDAO) Delete(id string) error {
func (dao *KnowledgebaseDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
return DB.Model(&entity.Knowledgebase{}).Where("id = ?", id).Update("status", string(entity.StatusInvalid)).Error
}
// GetByID retrieves a knowledge base by ID
func (dao *KnowledgebaseDAO) GetByID(id string) (*entity.Knowledgebase, error) {
func (dao *KnowledgebaseDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.Knowledgebase, error) {
var kb entity.Knowledgebase
err := DB.Where("id = ? AND status = ?", id, string(entity.StatusValid)).First(&kb).Error
func (dao *KnowledgebaseDAO) Update(ctx context.Context, db *gorm.DB, kb *entity.Knowledgebase) error {
return db.WithContext(ctx).Save(kb).Error
}
// UpdateByID updates a knowledge base by ID with the given fields
func (dao *KnowledgebaseDAO) UpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) error {
return db.WithContext(ctx).Model(&entity.Knowledgebase{}).Where("id = ?", id).Updates(updates).Error
}
// Delete soft deletes a knowledge base by setting status to invalid
func (dao *KnowledgebaseDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
return db.WithContext(ctx).Model(&entity.Knowledgebase{}).Where("id = ?", id).Update("status", string(entity.StatusInvalid)).Error
}
// GetByID retrieves a knowledge base by ID
func (dao *KnowledgebaseDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.Knowledgebase, error) {
var kb entity.Knowledgebase
err := db.WithContext(ctx).Where("id = ? AND status = ?", id, string(entity.StatusValid)).First(&kb).Error
🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 76-76: : # ragflow/internal/dao [ragflow/internal/dao.test]
internal/dao/kb_test.go:76:48: not enough arguments in call to dao.DecreaseDocumentNum
have (string, number, number, number)
want ("context".Context, *gorm.DB, string, int64, int64, int64)
internal/dao/kb_test.go:81:25: not enough arguments in call to dao.GetByID
have (string)
want ("context".Context, *gorm.DB, string)
internal/dao/kb_test.go:103:47: not enough arguments in call to dao.DecreaseDocumentNum
have (string, number, number, number)
want ("context".Context, *gorm.DB, string, int64, int64, int64)
internal/dao/kb_test.go:108:25: not enough arguments in call to dao.GetByID
have (string)
want ("context".Context, *gorm.DB, string)

(typecheck)

🤖 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/kb.go` around lines 68 - 85, Update the DAO methods shown,
including Update, UpdateByID, Delete, and GetByID, to use db.WithContext(ctx) as
the GORM root instead of the package-global DB. Preserve each method’s existing
query, update, and return behavior while ensuring caller-provided transactions,
databases, and context cancellation are honored; apply the same change to any
nearby DB.Raw operations.

Comment thread internal/dao/kb.go Outdated
Comment on lines 83 to 85
func (dao *KnowledgebaseDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.Knowledgebase, error) {
var kb entity.Knowledgebase
err := DB.Where("id = ? AND status = ?", id, string(entity.StatusValid)).First(&kb).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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Update callers to the new DAO signatures.

golangci-lint reports old-arity calls in internal/dao/kb_test.go at lines 76, 81, 103, and 108, which currently prevents the DAO test package from compiling. Pass the appropriate context and database handle to those calls.

As per coding guidelines, validate the Go package with the repository’s build.sh rather than raw go test.

Also applies to: 378-385

🤖 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/kb.go` around lines 83 - 85, Update the callers of
KnowledgebaseDAO methods in kb_test.go, including the cases around the
referenced test calls, to pass the required context and *gorm.DB arguments
matching the new GetByID signatures. Use the appropriate existing test context
and database handle, then validate the DAO package with the repository’s
build.sh rather than raw go test.

Sources: Coding guidelines, Linters/SAST tools

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN merged commit 53e83dc into infiniflow:main Jul 26, 2026
3 checks passed
This was referenced 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant