Skip to content

feat: migrate DELETE /api/v1/datasets/:dataset_id/documents to Go - #15577

Merged
yingfeng merged 2 commits into
infiniflow:mainfrom
xugangqiang:feat/go-delete-documents
Jun 3, 2026
Merged

yingfeng merged 2 commits into
infiniflow:mainfrom
xugangqiang:feat/go-delete-documents

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Migrate the batch document deletion endpoint from Python to Go. Two modes supported: explicit ids list and delete_all.

Changes

File Change
internal/dao/file2document.go Add GetByDocumentID, DeleteByDocumentID
internal/dao/file2document_test.go 5 new tests
internal/dao/kb_test.go 2 new tests (DecreaseDocumentNum)
internal/service/document.go Add deleteDocumentFull + DeleteDocuments, refactor DeleteDocument
internal/service/document_test.go 10 new tests
internal/handler/document.go Add documentServiceIface + DeleteDocuments handler
internal/handler/document_test.go 7 new tests
internal/router/router.go Register DELETE /:dataset_id/documents
cmd/server_main.go Support RAGFLOW_DICT_PATH env var
internal/binding/rag_analyzer.go Use -lpcre2-8 dynamic linking
internal/dao/database.go Skip Error 1091/1138 during migration
internal/service/llm.go Fix vet warning

Per-document cleanup

  • Delete tasks from DB
  • Hard-delete document + decrement KB counters
  • Delete chunks from document engine (nil-guarded)
  • Delete metadata from document engine (nil-guarded)
  • Remove file2document mapping + file record + storage blob

Test Results

24 unit tests all passing (7 DAO + 10 service + 7 handler) using SQLite :memory: + gin.TestMode.

See test report for manual integration test results.

🤖 Generated with Claude Code
Co-Authored-By: Claude Opus 4.8 [email protected]

Migrate the batch document deletion endpoint from Python to Go.
Two modes supported: explicit ids list, and delete_all.

Changes:
- dao/file2document: add GetByDocumentID, DeleteByDocumentID
- dao/kb: add DecrementCounters (already existed) with tests
- service/document: add deleteDocumentFull (per-doc cleanup) + DeleteDocuments (batch orchestration)
- handler/document: add DeleteDocuments handler with request validation
- router: register DELETE /:dataset_id/documents route
- cmd/server_main: support RAGFLOW_DICT_PATH env var for tokenizer dict path
- binding/rag_analyzer: use -lpcre2-8 dynamic linking (fixes host dev)
- dao/database: skip Error 1091/1138 during migration (coexist with Python schema)
- service/llm: fix non-constant format string vet warning

Per-document cleanup includes:
- Task deletion from DB
- Document hard-delete + KB counter decrement
- Chunk deletion from document engine (nil-guarded)
- Metadata deletion from document engine (nil-guarded)
- File2document mapping + file record + storage blob removal

Unit tests: 24 passing (7 DAO + 10 service + 7 handler)
Tested with SQLite :memory: + gin.TestMode, no external deps.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 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

Adds staged per-document cleanup, bulk DeleteDocuments, and StopParseDocuments cancellation with DAO helpers, handler/router wiring, extensive unit tests, go.mod/build/runtime updates, and a manual test report.

Changes

Document Deletion Feature

Layer / File(s) Summary
DAO Foundation — File2Document, Task, KB tests
internal/dao/file2document.go, internal/dao/file2document_test.go, internal/dao/task.go, internal/dao/task_test.go, internal/dao/kb_test.go, internal/dao/database.go
Adds GetByDocumentID/DeleteByDocumentID and TaskDAO.GetByDocID, KB decrement tests, DB AutoMigrate filtering for MySQL errors 1091/1138, and DAO unit tests covering single/multi/not-found/delete-noop cases.
Service Layer — full deletion, bulk DeleteDocuments, StopParseDocuments
internal/service/document.go, internal/service/document_test.go
Refactors DeleteDocument to a staged deleteDocumentFull, adds DeleteDocuments bulk API (access checks, delete-all resolution, deduplication, best-effort per-document cleanup) and StopParseDocuments cancellation (task lookup, Redis cancel keys, doc run update). Extensive service tests cover deletion and cancellation matrices and helper units.
Handler & Router — API endpoints and tests
internal/handler/document.go, internal/handler/document_test.go, internal/router/router.go
Introduces documentServiceIface, implements DocumentHandler.DeleteDocuments and StopParseDocuments with JSON/param validation and auth checks, registers DELETE /api/v1/datasets/:dataset_id/documents, and adds handler tests for validation, auth, service errors, and cancellation behavior.
Supporting Changes — build, deps, runtime, docs
cmd/server_main.go, go.mod, internal/binding/rag_analyzer.go, internal/service/llm.go, build.sh, docs/test_report_delete_documents.md
Tokenizer dict path now reads RAGFLOW_DICT_PATH with fallback. Bumps gorm.io/gorm and adds SQLite-related indirect deps. Updates PCRE2 linkage to -lpcre2-8 and broaden build detection for .a/.so; refines Darwin messaging. Fixes fmt.Errorf usage in LLM SetAPIKey. Adds manual test report for deletion endpoint.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Router
  participant DocumentHandler
  participant DocumentService
  participant TaskDAO
  participant DocEngine
  participant DocumentDAO
  participant File2DocumentDAO
  participant KnowledgebaseDAO

  Client->>Router: DELETE /api/v1/datasets/:dataset_id/documents (ids/delete_all)
  Router->>DocumentHandler: handle DeleteDocuments
  DocumentHandler->>DocumentService: DeleteDocuments(ids, deleteAll, datasetID, userID)
  DocumentService->>DocumentService: resolve IDs, validate access
  loop per document
    DocumentService->>TaskDAO: delete tasks for docID
    DocumentService->>DocEngine: delete chunks/metadata for docID
    DocumentService->>DocumentDAO: hard-delete document row
    DocumentService->>KnowledgebaseDAO: decrement counters for KB
    DocumentService->>File2DocumentDAO: delete mappings & cleanup unreferenced files
  end
  DocumentService-->>DocumentHandler: deleted count / errors
  DocumentHandler-->>Client: JSON response with deleted count
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested labels

💞 feature, 🧪 test

Suggested reviewers

  • JinHai-CN
  • Haruko386
  • Hz-186

Poem

🐰 I nibble code and tidy trails,

Tasks and chunks fall off like scales.
Mappings cleared and counters light,
Handlers hum and tests take flight.
Hooray — the datastore sleeps tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.78% 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 PR title accurately and concisely describes the main change: migrating the DELETE endpoint for batch document deletion to Go.
Description check ✅ Passed The PR description covers the problem statement, lists all changed files with their modifications, documents the cleanup flow, reports test results, and references the test report—meeting all template requirements.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@xugangqiang
xugangqiang requested a review from JinHai-CN June 3, 2026 08:15

@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

🧹 Nitpick comments (2)
internal/service/document.go (1)

306-340: 💤 Low value

Hoist the mapping delete and fileDAO out of the loop.

DeleteByDocumentID(docID) deletes all file2document rows for docID in one statement, but it's invoked once per mapping iteration, issuing redundant deletes. Likewise dao.NewFileDAO() is reconstructed on every iteration. Resolve the mapping deletion once after iterating files.

♻️ Proposed refactor
 	mappings, mapErr := s.file2DocumentDAO.GetByDocumentID(docID)
 	if mapErr != nil {
 		common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: failed to get file2document mappings for %s: %v", docID, mapErr))
 	}
+	fileDAO := dao.NewFileDAO()
 	for _, m := range mappings {
 		if m.FileID == nil {
 			continue
 		}
 		fileID := *m.FileID
-		// Delete the mapping
-		if delErr := s.file2DocumentDAO.DeleteByDocumentID(docID); delErr != nil {
-			common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: failed to delete f2d mapping for %s: %v", docID, delErr))
-		}
 		// Get file to remove storage blob
-		fileDAO := dao.NewFileDAO()
 		file, fErr := fileDAO.GetByID(fileID)
 		if fErr != nil || file == nil {
 			common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: file not found %s: %v", fileID, fErr))
 			continue
 		}
 		// Delete file record
 		if _, delErr := fileDAO.DeleteByIDs([]string{fileID}); delErr != nil {
 			common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: failed to delete file %s: %v", fileID, delErr))
 		}
 		// Delete storage blob
 		if file.Location != nil && *file.Location != "" {
 			storageImpl := storage.GetStorageFactory().GetStorage()
 			if storageImpl != nil {
 				if rmErr := storageImpl.Remove(file.ParentID, *file.Location); rmErr != nil {
 					common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: failed to remove blob %s/%s: %v", file.ParentID, *file.Location, rmErr))
 				}
 			}
 		}
 	}
+	// Delete the f2d mappings once (deletes all rows for this docID)
+	if delErr := s.file2DocumentDAO.DeleteByDocumentID(docID); delErr != nil {
+		common.Logger.Warn(fmt.Sprintf("deleteDocumentFull: failed to delete f2d mapping for %s: %v", docID, delErr))
+	}
🤖 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.go` around lines 306 - 340, The loop is calling
s.file2DocumentDAO.DeleteByDocumentID(docID) and dao.NewFileDAO() on every
mapping iteration which is redundant; change deleteDocumentFull so you construct
fileDAO once (move dao.NewFileDAO() out of the for loop), iterate mappings to
handle per-mapping file lookup, file deletion and storage blob removal using
that single fileDAO, and only after the loop call
s.file2DocumentDAO.DeleteByDocumentID(docID) once to remove all mappings; keep
existing warnings and nil checks (mappings, m.FileID, file==nil, file.Location)
intact.
internal/handler/document.go (1)

299-304: ⚡ Quick win

Body parsing is skipped when Content-Length is absent or chunked.

c.Request.ContentLength is -1 for chunked transfer-encoding and 0 when the client omits the header, so a valid {"ids":[...]} / {"delete_all":true} body would be silently ignored and the request rejected with the "provide ids or delete_all" error. Most clients (e.g. the documented curl -d) set Content-Length, so impact is limited, but binding directly and tolerating an empty-body EOF is more robust.

♻️ Tolerate empty body instead of gating on ContentLength
-	if c.Request.ContentLength > 0 {
-		if err := c.ShouldBindJSON(&req); err != nil {
-			jsonError(c, common.CodeDataError, err.Error())
-			return
-		}
-	}
+	if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
+		jsonError(c, common.CodeDataError, err.Error())
+		return
+	}

This requires importing io (errors is already imported).

🤖 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/document.go` around lines 299 - 304, The current check uses
c.Request.ContentLength to decide whether to call c.ShouldBindJSON, which skips
parsing for chunked or missing Content-Length; instead always attempt to bind
JSON (call c.ShouldBindJSON(&req)) and if it returns an error treat io.EOF as an
empty body (tolerate and continue) while returning other errors via jsonError;
add an import for io (errors is already present) and reference
c.Request.ContentLength only for logging if needed, but remove it as the gate so
functions jsonError, c.ShouldBindJSON and the request body handling accept
chunked/missing Content-Length cases.
🤖 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 `@docs/test_report_delete_documents.md`:
- Around line 15-23: The markdown uses unlabeled fenced code blocks for test
output which triggers MD040; update each backtick fence around the test lists to
include a fence language (use "text") for the blocks containing the test names
such as TestFile2DocumentDAO_GetByDocumentID, TestDeleteDocumentFull_Basic, and
TestDeleteDocumentsHandler_Success so the three unnamed fences are changed from
``` to ```text (apply the same change for the blocks that include the test
groups listed around lines containing those test names).

In `@internal/binding/rag_analyzer.go`:
- Line 21: The cgo LDFLAGS in internal/binding/rag_analyzer.go currently uses
"-lpcre2-8" which can cause dynamic runtime dependency on libpcre2-8.so; either
ensure the runtime images install the distro PCRE2 package (e.g., libpcre2-8 /
libpcre2-8-dev) so server_main/admin_server have the shared library at runtime,
or change the cgo link flags to force static PCRE2 linking (for example replace
"-lpcre2-8" with an explicit path to the static archive built by CMake like
../cpp/cmake-build-release/libpcre2-8.a or wrap with "-Wl,-Bstatic -lpcre2-8
-Wl,-Bdynamic") so the final binaries do not depend on libpcre2-8.so; update
either the Docker/base runtime provisioning to install PCRE2 or adjust LDFLAGS
in rag_analyzer.go to reference the static lib (and keep alignment with
internal/cpp/CMakeLists.txt PCRE2_LIB).

---

Nitpick comments:
In `@internal/handler/document.go`:
- Around line 299-304: The current check uses c.Request.ContentLength to decide
whether to call c.ShouldBindJSON, which skips parsing for chunked or missing
Content-Length; instead always attempt to bind JSON (call
c.ShouldBindJSON(&req)) and if it returns an error treat io.EOF as an empty body
(tolerate and continue) while returning other errors via jsonError; add an
import for io (errors is already present) and reference c.Request.ContentLength
only for logging if needed, but remove it as the gate so functions jsonError,
c.ShouldBindJSON and the request body handling accept chunked/missing
Content-Length cases.

In `@internal/service/document.go`:
- Around line 306-340: The loop is calling
s.file2DocumentDAO.DeleteByDocumentID(docID) and dao.NewFileDAO() on every
mapping iteration which is redundant; change deleteDocumentFull so you construct
fileDAO once (move dao.NewFileDAO() out of the for loop), iterate mappings to
handle per-mapping file lookup, file deletion and storage blob removal using
that single fileDAO, and only after the loop call
s.file2DocumentDAO.DeleteByDocumentID(docID) once to remove all mappings; keep
existing warnings and nil checks (mappings, m.FileID, file==nil, file.Location)
intact.
🪄 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

Run ID: 2122f206-9154-4a0d-8b98-36b79bd603c0

📥 Commits

Reviewing files that changed from the base of the PR and between a678ed7 and e773d7f.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (14)
  • cmd/server_main.go
  • docs/test_report_delete_documents.md
  • go.mod
  • internal/binding/rag_analyzer.go
  • internal/dao/database.go
  • internal/dao/file2document.go
  • internal/dao/file2document_test.go
  • internal/dao/kb_test.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/llm.go

Comment thread docs/test_report_delete_documents.md Resolved
/*
#cgo CXXFLAGS: -std=c++20 -I${SRCDIR}/..
#cgo linux LDFLAGS: ${SRCDIR}/../cpp/cmake-build-release/librag_tokenizer_c_api.a -lstdc++ -lm -lpthread /usr/lib/x86_64-linux-gnu/libpcre2-8.a
#cgo linux LDFLAGS: ${SRCDIR}/../cpp/cmake-build-release/librag_tokenizer_c_api.a -lstdc++ -lm -lpthread -lpcre2-8

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read-only verification: check whether repo provisioning installs PCRE2 shared library on Linux images.
# Expected: Dockerfiles/scripts/docs contain installation of libpcre2-8 (or distro equivalent).

set -euo pipefail

echo "== Candidate container/provisioning files =="
fd -i 'dockerfile|compose|install|setup|build|ci|workflow|mk|makefile|readme'

echo
echo "== Search for PCRE2/system package installation hints =="
rg -n -C 2 --iglob '*Dockerfile*' --iglob '*docker*' --iglob '*.yml' --iglob '*.yaml' --iglob '*.sh' --iglob 'README*' \
  'pcre2|libpcre2|apt-get install|apk add|yum install|dnf install|ldconfig'

Repository: infiniflow/ragflow

Length of output: 10249


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Search for PCRE2/libpcre2 usage in repo (esp. Docker/runtime images) =="

rg -n --hidden --glob '!**/node_modules/**' \
  'libpcre2-8|pcre2-8|libpcre2|PCRE2|pcre2' \
  Dockerfile* docker/** docs/** internal/** build.sh check_comment_ascii.py README* \
  || true

echo
echo "== Inspect Dockerfile.* and docker/ compose for libpcre2/pcre2 installs (limited context) =="

rg -n -C 3 --iglob 'Dockerfile*' --iglob 'docker*' \
  'libpcre2-8|pcre2|pcre2-8|libpcre2' Dockerfile* docker/** || true

echo
echo "== Check rag_analyzer.go cgo LDFLAGS context (lines around the snippet) =="

FILE="internal/binding/rag_analyzer.go"
if [ -f "$FILE" ]; then
  sed -n '1,80p' "$FILE" | nl -ba
else
  echo "Missing $FILE"
fi

Repository: infiniflow/ragflow

Length of output: 50436


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Docker/runtime provisioning: look for libpcre2-8 / pcre2 runtime installs =="
rg -n --hidden --glob 'Dockerfile*' --glob 'docker/**' \
  '(libpcre2-8|pcre2-8|libpcre2\b|pcre2\b)' Dockerfile* docker/** || true

echo
echo "== Build-time deps: look for libpcre2-dev installs =="
rg -n --hidden --glob 'build.sh' --glob 'Dockerfile*' --glob 'docker/**' \
  '(libpcre2-dev|pcre2-dev|apt-get install .*pcre2|apk add .*pcre2|yum install .*pcre2|dnf install .*pcre2)' Dockerfile* docker/** build.sh || true

echo
echo "== cgo LDFLAGS in internal/binding/rag_analyzer.go (around line 21) =="
FILE="internal/binding/rag_analyzer.go"
if [ -f "$FILE" ]; then
  sed -n '1,80p' "$FILE" | sed -n '15,40p'
else
  echo "Missing $FILE"
fi

echo
echo "== What C++ build system links against PCRE2? (search around internal/cpp) =="
rg -n --hidden 'pcre2|PCRE2' internal/cpp/Makefile internal/cpp/**/*.{cmake,CMakeLists.txt,txt,md,sh} 2>/dev/null || true

echo
echo "== Locate where LDFLAGS is defined in rag_analyzer.go =="
rg -n 'LDFLAGS|cgo linux LDFLAGS|libpcre2|pcre2' internal/binding/rag_analyzer.go || true

Repository: infiniflow/ragflow

Length of output: 2033


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Search Docker/Helm/CI for libpcre2/pcre2 runtime packages (libpcre2-8, pcre2, libpcre2-8.so) =="

rg -n --hidden \
  --glob 'Dockerfile*' --glob 'docker/**' --glob 'helm/**' --glob '.github/**' --glob '*.yml' --glob '*.yaml' --glob '*.sh' \
  '(libpcre2-8|libpcre2\b|pcre2\b|PCRE2)' \
  Dockerfile* docker/** helm/** .github/** *.yml *.yaml *.sh 2>/dev/null || true

echo
echo "== Inspect internal/cpp/Makefile around PCRE2 link flags =="

FILE="internal/cpp/Makefile"
if [ -f "$FILE" ]; then
  sed -n '1,120p' "$FILE" | nl -ba
else
  echo "Missing $FILE"
fi

echo
echo "== Search internal/cpp build scripts for static/shared linkage hints (Bstatic/static) =="

rg -n --hidden --glob '*Makefile*' --glob '*CMakeLists*' --glob '*.cmake' \
  'Bstatic|whole-archive|--static| -static |LINK_OPTIONS|target_link_options|find_package\(.+PCRE2|pcre2' \
  internal/cpp 2>/dev/null || true

echo
echo "== Locate where librag_tokenizer_c_api.a is produced (CMake/C++ build files) =="

rg -n --hidden '(rag_tokenizer_c_api\.a|librag_tokenizer_c_api|tokenizer_c_api)' internal/cpp 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 1316


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Inspect internal/cpp/Makefile around PCRE2 link flags =="
FILE="internal/cpp/Makefile"
if [ -f "$FILE" ]; then
  sed -n '1,120p' "$FILE" | sed -n '35,80p' 
else
  echo "Missing $FILE"
fi

echo
echo "== Find how librag_tokenizer_c_api.a is defined/linked (internal/cpp) =="
rg -n --hidden 'librag_tokenizer_c_api\.a|rag_tokenizer_c_api|tokenizer_c_api' internal/cpp || true

echo
echo "== Search Docker/runtime images for any 'pcre2' mention =="
rg -n --hidden --glob 'Dockerfile*' --glob 'docker/**' --glob '*.yml' --glob '*.yaml' \
  'pcre2|libpcre2' Dockerfile* docker/** *.yml *.yaml 2>/dev/null || true

echo
echo "== Inspect Dockerfile candidates that look like runtime/scratch =="
for f in Dockerfile Dockerfile.deps Dockerfile.scratch.oc9 docker/docker-compose*.yml docker/docker-compose*.yaml; do
  if [ -f "$f" ]; then
    echo "--- $f (first 120 lines) ---"
    sed -n '1,120p' "$f" | cat
  fi
done 2>/dev/null || true

echo
echo "== Search final Go/cgo link flags usage of -lpcre2-8 =="
rg -n --hidden 'lpcre2-8|libpcre2-8|pcre2' internal/binding/rag_analyzer.go internal/binding/**/*.go internal/**/rag_analyzer.go || true

Repository: infiniflow/ragflow

Length of output: 24632


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Search Dockerfile(s) for Go/C++ build steps and prebuilt artifact copies =="

rg -n --hidden \
  --glob 'Dockerfile*' --glob 'docker/**' \
  '(go build|CGO_ENABLED|cmake-build-release|librag_tokenizer_c_api|rag_tokenizer_c_api|c_api|build\.sh|make rag_tokenizer_c_api|cmake .*rag_tokenizer_c_api)' \
  Dockerfile* docker/** || true

echo
echo "== Search for libpcre2(-dev) package install anywhere in Dockerfiles/scripts =="

rg -n --hidden \
  --glob 'Dockerfile*' --glob 'docker/**' --glob '*.sh' \
  '(libpcre2-8|libpcre2-dev|pcre2-dev|apt(-get)? .*pcre2|apk add .*pcre2|yum .*pcre2|dnf .*pcre2)' \
  Dockerfile* docker/** *.sh || true

echo
echo "== Locate where cmake-build-release path is used in build scripts =="

rg -n --hidden \
  '(cmake-build-release|librag_tokenizer_c_api\.a)' internal/cpp build.sh build*.sh admin/build_cli_release.sh .github/workflows/* docs/** || true

Repository: infiniflow/ragflow

Length of output: 1764


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== build.sh: show PCRE2-related checks (first ~220 lines) =="
sed -n '1,220p' build.sh | cat

echo
echo "== internal/cpp/CMakeLists.txt: find PCRE2 discovery / PCRE2_LIB setting =="
rg -n 'PCRE2|pcre2|PCRE2_LIB' internal/cpp/CMakeLists.txt internal/cpp/**/*.cmake internal/cpp/**/CMakeLists.txt 2>/dev/null || true

echo
echo "== internal/cpp/CMakeLists.txt: show around where ${PCRE2_LIB} is used =="
# show likely region around add_library and target_link_libraries (based on earlier hit at ~133-167)
sed -n '110,190p' internal/cpp/CMakeLists.txt | cat

echo
echo "== internal/cpp/CMakeLists.txt: show earlier region too (first 110 lines) =="
sed -n '1,110p' internal/cpp/CMakeLists.txt | cat

Repository: infiniflow/ragflow

Length of output: 7820


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="internal/cpp/CMakeLists.txt"
echo "== $FILE (lines 1-90) =="
sed -n '1,90p' "$FILE" | cat

echo
echo "== $FILE (lines 90-190) =="
sed -n '90,190p' "$FILE" | cat

echo
echo "== $FILE: all lines mentioning PCRE2_LIB / pcre2 =="
rg -n 'PCRE2_LIB|pcre2-8|find_library\(PCRE2_LIB|libpcre2-8\.a|target_link_libraries\(.*pcre2' "$FILE" || true

Repository: infiniflow/ragflow

Length of output: 5486


Ensure Linux runtime images have PCRE2 runtime (or link PCRE2 statically)

  • internal/binding/rag_analyzer.go sets cgo Linux LDFLAGS to include -lpcre2-8, which can cause the final Go binary to require the shared libpcre2-8.so at runtime.
  • internal/cpp/CMakeLists.txt explicitly uses libpcre2-8.a for Linux (PCRE2_LIB), but the cgo link step still uses the generic -l form, so runtime linkage needs to be aligned.
  • Repo Docker/runtime provisioning doesn’t install libpcre2-8 / libpcre2-dev, so deployments can fail if the binary is dynamically linked to PCRE2.

Update the Linux runtime Dockerfiles/base image to install the PCRE2 runtime package (distro equivalent) or force static PCRE2 in the cgo link (e.g., link libpcre2-8.a / use -Wl,-Bstatic for PCRE2) so server_main/admin_server don’t depend on libpcre2-8.so at runtime.

🤖 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/binding/rag_analyzer.go` at line 21, The cgo LDFLAGS in
internal/binding/rag_analyzer.go currently uses "-lpcre2-8" which can cause
dynamic runtime dependency on libpcre2-8.so; either ensure the runtime images
install the distro PCRE2 package (e.g., libpcre2-8 / libpcre2-8-dev) so
server_main/admin_server have the shared library at runtime, or change the cgo
link flags to force static PCRE2 linking (for example replace "-lpcre2-8" with
an explicit path to the static archive built by CMake like
../cpp/cmake-build-release/libpcre2-8.a or wrap with "-Wl,-Bstatic -lpcre2-8
-Wl,-Bdynamic") so the final binaries do not depend on libpcre2-8.so; update
either the Docker/base runtime provisioning to install PCRE2 or adjust LDFLAGS
in rag_analyzer.go to reference the static lib (and keep alignment with
internal/cpp/CMakeLists.txt PCRE2_LIB).

Comment thread internal/service/document.go Resolved
@xugangqiang
xugangqiang requested a review from Haruko386 June 3, 2026 08:15
@Haruko386 Haruko386 added the ci Continue Integration label Jun 3, 2026
@Haruko386
Haruko386 marked this pull request as draft June 3, 2026 08:24
@Haruko386
Haruko386 marked this pull request as ready for review June 3, 2026 08:24

@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 (3)
build.sh (3)

92-95: ⚡ Quick win

Consider supporting ARM64 Linux paths.

Same hardcoded /usr/lib/x86_64-linux-gnu/ path issue as in check_cpp_deps(). On ARM64 Linux, pcre2 would be at /usr/lib/aarch64-linux-gnu/. Consider using multiarch detection or checking both architecture paths.

🔧 Suggested multiarch approach
     # Check for pcre2 library — known Linux paths + macOS Homebrew (Apple Silicon
-    # at /opt/homebrew, Intel Macs at /usr/local). Checks both .a and .so.
-    if [ -f "/usr/lib/x86_64-linux-gnu/libpcre2-8.a" ] \
-       || [ -f "/usr/lib/x86_64-linux-gnu/libpcre2-8.so" ] \
+    # at /opt/homebrew, Intel Macs at /usr/local). Checks both .a and .so.
+    MULTIARCH_TRIPLET=$(dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null || echo "x86_64-linux-gnu")
+    if [ -f "/usr/lib/${MULTIARCH_TRIPLET}/libpcre2-8.a" ] \
+       || [ -f "/usr/lib/${MULTIARCH_TRIPLET}/libpcre2-8.so" ] \
        || [ -f "/usr/local/lib/libpcre2-8.a" ] \
        || [ -f "/usr/local/lib/libpcre2-8.so" ] \
        || [ -f "/opt/homebrew/lib/libpcre2-8.a" ]; then
🤖 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 `@build.sh` around lines 92 - 95, Update the PCRE2 existence check in build.sh
to also handle ARM64 multiarch paths: detect the machine arch (e.g. via uname -m
or dpkg-architecture -qDEB_HOST_MULTIARCH) and construct/check the appropriate
multiarch lib directory names (e.g. x86_64-linux-gnu and aarch64-linux-gnu) or
simply check both patterns (/usr/lib/*-linux-gnu/) instead of only the x86_64
path; modify the if condition that currently tests /usr/lib/x86_64-linux-gnu/...
and /usr/local/lib/... so it iterates/checks the computed arch-specific dirs (or
wildcard multiarch dir) for libpcre2-8.a/.so before proceeding.

96-96: 💤 Low value

Consider checking for .so variant in Homebrew path for consistency.

Line 96 only checks for libpcre2-8.a in /opt/homebrew/lib/ but not the .so variant, while other paths check both. Although Homebrew typically provides .a files, adding the .so check would maintain consistency with the rest of the detection logic.

♻️ Suggested addition
        || [ -f "/usr/local/lib/libpcre2-8.a" ] \
        || [ -f "/usr/local/lib/libpcre2-8.so" ] \
-       || [ -f "/opt/homebrew/lib/libpcre2-8.a" ]; then
+       || [ -f "/opt/homebrew/lib/libpcre2-8.a" ] \
+       || [ -f "/opt/homebrew/lib/libpcre2-8.so" ]; then
🤖 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 `@build.sh` at line 96, Update the Homebrew libpcre2 check to also test the
shared object variant: extend the existing condition that checks for
"/opt/homebrew/lib/libpcre2-8.a" to also check for
"/opt/homebrew/lib/libpcre2-8.so" so the detection logic for libpcre2 in
build.sh mirrors other paths that test both .a and .so variants.

36-39: ⚡ Quick win

Consider supporting ARM64 Linux paths.

The hardcoded /usr/lib/x86_64-linux-gnu/ path won't find pcre2 on ARM64 Linux systems where the library would be at /usr/lib/aarch64-linux-gnu/. While /usr/local/lib/ provides a fallback, consider using a multiarch-aware approach or checking both architecture paths.

🔧 Suggested approach using dpkg-architecture
-    # Check for pcre2 library (static .a or shared .so; -lpcre2-8 finds either)
-    if [ -f "/usr/lib/x86_64-linux-gnu/libpcre2-8.a" ] \
-       || [ -f "/usr/lib/x86_64-linux-gnu/libpcre2-8.so" ] \
-       || [ -f "/usr/local/lib/libpcre2-8.a" ] \
+    # Check for pcre2 library (static .a or shared .so; -lpcre2-8 finds either)
+    MULTIARCH_TRIPLET=$(dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null || echo "x86_64-linux-gnu")
+    if [ -f "/usr/lib/${MULTIARCH_TRIPLET}/libpcre2-8.a" ] \
+       || [ -f "/usr/lib/${MULTIARCH_TRIPLET}/libpcre2-8.so" ] \
+       || [ -f "/usr/local/lib/libpcre2-8.a" ] \
        || [ -f "/usr/local/lib/libpcre2-8.so" ]; then
🤖 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 `@build.sh` around lines 36 - 39, The if-statement in build.sh that checks for
pcre2 only tests /usr/lib/x86_64-linux-gnu and /usr/local/lib; update the
conditional that checks for pcre2 library presence to also handle ARM64
multiarch paths by either (a) querying dpkg-architecture to get the DEB host
multiarch triplet (e.g., via dpkg-architecture -qDEB_HOST_MULTIARCH) and testing
/usr/lib/<triplet>/libpcre2-8.{a,so}, or (b) explicitly add checks for
/usr/lib/aarch64-linux-gnu/libpcre2-8.a and
/usr/lib/aarch64-linux-gnu/libpcre2-8.so alongside the existing checks in that
if-block so ARM64 systems find the library correctly.
🤖 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 `@build.sh`:
- Around line 99-105: The script currently auto-runs "sudo apt -y install
libpcre2-dev" when libpcre2-8 is missing; instead modify the missing-dependency
branch in build.sh to stop auto-installing and mirror check_cpp_deps() behavior:
print a clear warning or error that libpcre2-8 is not installed, provide
platform-agnostic guidance and example install commands (e.g., apt, dnf, pacman,
brew) and either exit with non-zero status (like the Darwin branch) or prompt
the user to install manually, ensuring no use of sudo/auto-elevation and keeping
the logic in the same conditional that currently contains the sudo command.

---

Nitpick comments:
In `@build.sh`:
- Around line 92-95: Update the PCRE2 existence check in build.sh to also handle
ARM64 multiarch paths: detect the machine arch (e.g. via uname -m or
dpkg-architecture -qDEB_HOST_MULTIARCH) and construct/check the appropriate
multiarch lib directory names (e.g. x86_64-linux-gnu and aarch64-linux-gnu) or
simply check both patterns (/usr/lib/*-linux-gnu/) instead of only the x86_64
path; modify the if condition that currently tests /usr/lib/x86_64-linux-gnu/...
and /usr/local/lib/... so it iterates/checks the computed arch-specific dirs (or
wildcard multiarch dir) for libpcre2-8.a/.so before proceeding.
- Line 96: Update the Homebrew libpcre2 check to also test the shared object
variant: extend the existing condition that checks for
"/opt/homebrew/lib/libpcre2-8.a" to also check for
"/opt/homebrew/lib/libpcre2-8.so" so the detection logic for libpcre2 in
build.sh mirrors other paths that test both .a and .so variants.
- Around line 36-39: The if-statement in build.sh that checks for pcre2 only
tests /usr/lib/x86_64-linux-gnu and /usr/local/lib; update the conditional that
checks for pcre2 library presence to also handle ARM64 multiarch paths by either
(a) querying dpkg-architecture to get the DEB host multiarch triplet (e.g., via
dpkg-architecture -qDEB_HOST_MULTIARCH) and testing
/usr/lib/<triplet>/libpcre2-8.{a,so}, or (b) explicitly add checks for
/usr/lib/aarch64-linux-gnu/libpcre2-8.a and
/usr/lib/aarch64-linux-gnu/libpcre2-8.so alongside the existing checks in that
if-block so ARM64 systems find the library correctly.
🪄 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

Run ID: a12c6e52-3e18-4fd3-89f3-d9a3e8c24ed4

📥 Commits

Reviewing files that changed from the base of the PR and between b2fb521 and 5fed4ad.

📒 Files selected for processing (1)
  • build.sh

Comment thread build.sh
Comment on lines 99 to 105
if [ "$(uname)" = "Darwin" ]; then
echo -e "${RED}Error: libpcre2-8.a not found. Install with: brew install pcre2${NC}"
echo -e "${RED}Error: libpcre2-8 not found. Install with: brew install pcre2${NC}"
exit 1
fi
echo -e "${YELLOW}Warning: libpcre2-8.a not found. You may need to install libpcre2-dev:${NC}"
echo -e "${YELLOW}Warning: libpcre2-8 not found. You may need to install libpcre2-dev:${NC}"
sudo apt -y install libpcre2-dev
fi

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Automatic privileged package installation is problematic.

Line 104 automatically runs sudo apt -y install libpcre2-dev on non-Darwin systems without user consent. This introduces several issues:

  1. Security concern: Automatically elevates privileges without warning
  2. Portability: Assumes apt package manager (breaks on Fedora, Arch, Alpine, etc.)
  3. Build failures: Could fail if sudo requires password/2FA or isn't available
  4. Inconsistency: check_cpp_deps() (lines 42-43) only warns and suggests the command but doesn't execute it

Build scripts should detect missing dependencies and provide clear instructions, but not automatically modify the system.

🛡️ Recommended fix: warn instead of auto-install
     else
         if [ "$(uname)" = "Darwin" ]; then
             echo -e "${RED}Error: libpcre2-8 not found. Install with: brew install pcre2${NC}"
             exit 1
         fi
         echo -e "${YELLOW}Warning: libpcre2-8 not found. You may need to install libpcre2-dev:${NC}"
-        sudo apt -y install libpcre2-dev
+        echo "  Debian/Ubuntu: sudo apt-get install libpcre2-dev"
+        echo "  Fedora/RHEL:   sudo dnf install pcre2-devel"
+        echo "  Arch:          sudo pacman -S pcre2"
     fi

If the library is truly required, consider exiting with an error like the Darwin case, rather than attempting auto-installation.

📝 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
if [ "$(uname)" = "Darwin" ]; then
echo -e "${RED}Error: libpcre2-8.a not found. Install with: brew install pcre2${NC}"
echo -e "${RED}Error: libpcre2-8 not found. Install with: brew install pcre2${NC}"
exit 1
fi
echo -e "${YELLOW}Warning: libpcre2-8.a not found. You may need to install libpcre2-dev:${NC}"
echo -e "${YELLOW}Warning: libpcre2-8 not found. You may need to install libpcre2-dev:${NC}"
sudo apt -y install libpcre2-dev
fi
if [ "$(uname)" = "Darwin" ]; then
echo -e "${RED}Error: libpcre2-8 not found. Install with: brew install pcre2${NC}"
exit 1
fi
echo -e "${YELLOW}Warning: libpcre2-8 not found. You may need to install libpcre2-dev:${NC}"
echo " Debian/Ubuntu: sudo apt-get install libpcre2-dev"
echo " Fedora/RHEL: sudo dnf install pcre2-devel"
echo " Arch: sudo pacman -S pcre2"
fi
🤖 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 `@build.sh` around lines 99 - 105, The script currently auto-runs "sudo apt -y
install libpcre2-dev" when libpcre2-8 is missing; instead modify the
missing-dependency branch in build.sh to stop auto-installing and mirror
check_cpp_deps() behavior: print a clear warning or error that libpcre2-8 is not
installed, provide platform-agnostic guidance and example install commands
(e.g., apt, dnf, pacman, brew) and either exit with non-zero status (like the
Darwin branch) or prompt the user to install manually, ensuring no use of
sudo/auto-elevation and keeping the logic in the same conditional that currently
contains the sudo command.

@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (ff59714) to head (078954e).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15577   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 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.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xugangqiang All tests are passed
LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 3, 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

🤖 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/document.go`:
- Around line 370-377: The code currently attempts to remove the storage blob
even when fileDAO.DeleteByIDs([]string{fileID}) returns an error; change
cleanupFileReferences so that if DeleteByIDs returns an error you immediately
bail (return or continue) and do not call storageImpl.Remove; only proceed to
call storage.GetStorageFactory().GetStorage() and
storageImpl.Remove(file.ParentID, *file.Location) after the DB delete has
succeeded. Use the existing symbols fileDAO.DeleteByIDs, fileID, file.Location,
storage.GetStorageFactory().GetStorage, storageImpl.Remove and the
cleanupFileReferences context to locate and update the control flow.
- Around line 315-320: The deleteDocRecordWithCounters helper currently calls
kbDAO.DecreaseDocumentNum even when documentDAO.Delete was a no-op; change it to
have documentDAO.Delete return rows affected (or an error) and perform the
delete + counter decrement inside a DB transaction only when rowsAffected > 0.
Update deleteDocRecordWithCounters to begin a transaction, call
documentDAO.Delete (which must expose rowsAffected), and if rowsAffected == 1
then call kbDAO.DecreaseDocumentNum and commit; if rowsAffected == 0
rollback/return nil without touching counters, and propagate errors
appropriately from documentDAO.Delete or kbDAO.DecreaseDocumentNum.
🪄 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

Run ID: 0d2eff17-c54d-410f-8b3c-f66a26717251

📥 Commits

Reviewing files that changed from the base of the PR and between 5fed4ad and e6bafe7.

📒 Files selected for processing (7)
  • internal/dao/task.go
  • internal/dao/task_test.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/document_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/router/router.go
  • internal/handler/document.go

Comment thread internal/service/document.go Resolved
Comment thread internal/service/document.go Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. size:L This PR changes 100-499 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 3, 2026
@xugangqiang
xugangqiang force-pushed the feat/go-delete-documents branch from 7197fc8 to e773d7f Compare June 3, 2026 11:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants