Repository navigation
feat: migrate POST /api/v1/datasets/<dataset_id>/documents/stop to Go - #15597
Conversation
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]>
A single file_id can be shared across multiple documents via file2document rows with different document_id. Before deleting the file record and its storage blob, check whether any other document still references the same file_id. Only delete file/blob when no other references remain. Add TestDeleteDocumentFull_SharedFilePreserved to verify shared file survives when one referencing document is deleted.
-lpcre2-8 linker flag finds either .a or .so automatically. Update the build-time library checks to match.
- Add GetByDocID to TaskDAO for querying tasks by document ID - Add StopParseDocuments to DocumentService with Redis cancel signal support - Add StopParseDocuments handler with request validation and access check - Add POST /:dataset_id/documents/stop route - Add unit tests: 3 DAO + 8 service + 5 handler tests Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extract five sub-methods from deleteDocumentFull: - resolveDocAndKB — load document + knowledgebase - deleteDocTasks — delete task rows - deleteDocEngineData — delete chunks + metadata from engine - deleteDocRecordWithCounters — hard-delete doc + decrement KB - cleanupFileReferences — delete f2d + file + blob (shared-safe) deleteDocumentFull is now a thin orchestrator. Add 10 targeted unit tests for the sub-methods.
validateDocsInDataset is shared between DeleteDocuments and StopParseDocuments, removing duplicate validation logic. cancelDocParse encapsulates per-document parse cancellation: Redis cancel signal + run status update. StopParseDocuments is now a thin orchestrator, same pattern as deleteDocumentFull.
…hCounters DocumentDAO.Delete now returns (int64, error). deleteDocRecordWithCounters wraps the delete + counter decrement in a transaction and only decrements KB counters when RowsAffected > 0, preventing permanent dataset stat skew on retries or concurrent deletes.
…ferences If DeleteByIDs returns an error the file row is still live; removing the blob anyway would leave a dangling file record. Bail out to keep the blob intact so the record remains usable on retry.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds StopParseDocuments endpoint/service with per-document cancellation (task inspection, Redis cancel keys, run->CANCEL), refactors document deletion into transactional helpers with guarded counter updates and file-reference cleanup, updates DAO signature, adds DAO/task tests, and broadens build.sh libpcre2-8 detection. ChangesBuild Script Maintenance
Document Parse Stopping and Deletion Refactoring
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
internal/service/document.go (2)
574-616: ⚡ Quick winRedis cancel signal keys accumulate without expiration.
Line 608 sets Redis keys with no expiration (
redisClient.Set(fmt.Sprintf("%s-cancel", t.ID), "x", 0)). Over time, these keys will accumulate in Redis, potentially consuming memory.Consider setting an expiration time (e.g., 24-48 hours) sufficient for typical task lifetimes, or implement a cleanup mechanism to remove keys once tasks complete.
🤖 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 574 - 616, In cancelDocParse, the Redis cancel keys are set with zero TTL causing accumulation; change the call that sets the key (the redisClient.Set(...) invocation for fmt.Sprintf("%s-cancel", t.ID) inside cancelDocParse) to set a nonzero expiration (e.g., 24h–48h) or call a corresponding SetEx/SetWithExpiry API or follow-up redisClient.Expire(...) so each cancel key automatically expires after a reasonable window; ensure the chosen TTL is applied consistently for every task key written.
296-322: 💤 Low valueCounter decrement failure handling leaves transaction uncommitted.
The transaction commits successfully even when the counter decrement fails (line 317-319). While this prevents document deletion from being rolled back due to counter issues, it can lead to KB counter drift over time if the decrement consistently fails.
Consider whether this tradeoff is acceptable for your use case. If counters are periodically reconciled elsewhere, this approach is reasonable. Otherwise, consider returning the decrement error to fail the transaction.
🤖 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 296 - 322, The current deleteDocRecordWithCounters function swallows decrement errors (in the tx.Model(...).Updates call) and returns nil, allowing the transaction to commit even if KB counters failed to update; change this by returning the decrement error (decErr) from within the transaction so the Transaction call fails and the delete is rolled back (i.e., replace the common.Logger.Warn(...) + return nil path with returning fmt.Errorf("failed to decrement KB %s: %w", kbID, decErr)); alternatively, if you intentionally want to commit the delete but record the failure, add a clear TODO and emit a structured error event to your reconciliation queue instead of silently warning.
🤖 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 35-43: The check in check_cpp_deps (build.sh) misses the Apple
Silicon Homebrew location so Homebrew-installed pcre2 under /opt/homebrew/lib
can produce a false missing warning; update the file-existence checks in the
pcre2 detection block inside check_cpp_deps to also test
/opt/homebrew/lib/libpcre2-8.a and /opt/homebrew/lib/libpcre2-8.so (matching how
build_go/CGO expects /opt/homebrew/lib/libpcre2-8.a) so the script correctly
detects pcre2 on Apple Silicon Homebrew installs.
In `@internal/router/router.go`:
- Line 237: Fix indentation for the route registration so it matches the
surrounding datasets route entries: locate the
datasets.POST("/:dataset_id/documents/stop",
r.documentHandler.StopParseDocuments) line and remove the extra leading
tabs/spaces so its indentation aligns with sibling datasets.* registrations,
then run gofmt/format to ensure CI will pass.
---
Nitpick comments:
In `@internal/service/document.go`:
- Around line 574-616: In cancelDocParse, the Redis cancel keys are set with
zero TTL causing accumulation; change the call that sets the key (the
redisClient.Set(...) invocation for fmt.Sprintf("%s-cancel", t.ID) inside
cancelDocParse) to set a nonzero expiration (e.g., 24h–48h) or call a
corresponding SetEx/SetWithExpiry API or follow-up redisClient.Expire(...) so
each cancel key automatically expires after a reasonable window; ensure the
chosen TTL is applied consistently for every task key written.
- Around line 296-322: The current deleteDocRecordWithCounters function swallows
decrement errors (in the tx.Model(...).Updates call) and returns nil, allowing
the transaction to commit even if KB counters failed to update; change this by
returning the decrement error (decErr) from within the transaction so the
Transaction call fails and the delete is rolled back (i.e., replace the
common.Logger.Warn(...) + return nil path with returning fmt.Errorf("failed to
decrement KB %s: %w", kbID, decErr)); alternatively, if you intentionally want
to commit the delete but record the failure, add a clear TODO and emit a
structured error event to your reconciliation queue instead of silently warning.
🪄 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: 77faac15-8460-45b2-8e42-1c904d10d011
📒 Files selected for processing (10)
build.shinternal/dao/document.gointernal/dao/task.gointernal/dao/task_test.gointernal/handler/document.gointernal/handler/document_test.gointernal/router/router.gointernal/service/document.gointernal/service/document_test.gointernal/service/file.go
| # 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" ] \ | ||
| || [ -f "/usr/local/lib/libpcre2-8.so" ]; then | ||
| echo "✓ pcre2 library found" | ||
| else | ||
| 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}" | ||
| echo " sudo apt-get install libpcre2-dev" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== check_cpp_deps probe paths =="
rg -n 'check_cpp_deps|libpcre2-8\.(a|so)|opt/homebrew' build.sh -A20 -B2
echo
echo "== build_go probe paths =="
rg -n 'build_go|libpcre2-8\.(a|so)|opt/homebrew' build.sh -A30 -B2Repository: infiniflow/ragflow
Length of output: 8473
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== pcre2 references in build.sh =="
rg -n "pcre2-8|libpcre2" build.sh -S
echo
echo "== pcre2 references in C++ build files =="
rg -n "pcre2-8|libpcre2|find_package\(PCRE2|PCRE2" -S . --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' --glob '!**/.git/**'Repository: infiniflow/ragflow
Length of output: 50374
Include Apple Silicon Homebrew pcre2 path in check_cpp_deps (build.sh)
check_cpp_deps (build.sh lines 35-43) doesn’t probe /opt/homebrew/lib/libpcre2-8.a, so --cpp/--all can show a false “libpcre2-8 not found” warning for Apple Silicon setups that do have libpcre2-8.a under Homebrew; build_go/CGO already expect /opt/homebrew/lib/libpcre2-8.a.
Suggested fix
- 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" ] \
- || [ -f "/usr/local/lib/libpcre2-8.so" ]; then
+ 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" ] \
+ || [ -f "/usr/local/lib/libpcre2-8.so" ] \
+ || [ -f "/opt/homebrew/lib/libpcre2-8.a" ]; then
echo "✓ pcre2 library found"
else
echo -e "${YELLOW}Warning: libpcre2-8 not found. You may need to install libpcre2-dev:${NC}"
echo " sudo apt-get install libpcre2-dev"🤖 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 35 - 43, The check in check_cpp_deps (build.sh) misses
the Apple Silicon Homebrew location so Homebrew-installed pcre2 under
/opt/homebrew/lib can produce a false missing warning; update the file-existence
checks in the pcre2 detection block inside check_cpp_deps to also test
/opt/homebrew/lib/libpcre2-8.a and /opt/homebrew/lib/libpcre2-8.so (matching how
build_go/CGO expects /opt/homebrew/lib/libpcre2-8.a) so the script correctly
detects pcre2 on Apple Silicon Homebrew installs.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15597 +/- ##
=======================================
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 Harness. 🚀 New features to boost your workflow:
|
Single-line wrapper with no extra logic beyond the DAO call + log. Task deletion is already covered by TestDeleteDocumentFull_Basic.
db59e98 to
c2e00a8
Compare
Summary
Migrate the stop parse documents endpoint from Python to Go.
Python endpoint
POST /api/v1/datasets/<dataset_id>/documents/stop—api/apps/restful_apis/document_api.py:1542-1641Changes
internal/dao/task.goGetByDocIDmethodinternal/dao/task_test.gointernal/service/document.goStopParseDocuments+ refactor shared helpersinternal/service/document_test.gointernal/handler/document.gointernal/handler/document_test.gointernal/router/router.goPOST /:dataset_id/documents/stoprouteHow it works
{task_id}-cancelfor each associated taskdocument.runto CANCEL ("2"){"success_count": N, "errors": [...]}Test strategy
fakeDocumentServiceimplementingdocumentServiceIfaceinterface.🤖 Generated with Claude Code