Skip to content

feat: migrate POST /api/v1/datasets/<dataset_id>/documents/stop to Go - #15597

Merged
yingfeng merged 10 commits into
infiniflow:mainfrom
xugangqiang:feat/go-stop-parse-documents
Jun 4, 2026
Merged

yingfeng merged 10 commits into
infiniflow:mainfrom
xugangqiang:feat/go-stop-parse-documents

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

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-1641

Changes

File Change
internal/dao/task.go Add GetByDocID method
internal/dao/task_test.go 3 DAO tests (new file)
internal/service/document.go Add StopParseDocuments + refactor shared helpers
internal/service/document_test.go 8 service tests
internal/handler/document.go Add handler + request struct + interface
internal/handler/document_test.go 5 handler tests
internal/router/router.go Add POST /:dataset_id/documents/stop route

How it works

  1. Validates all document IDs belong to the dataset
  2. For each document in RUNNING/CANCEL state (or with unfinished tasks):
    • Sets Redis cancel signal {task_id}-cancel for each associated task
    • Updates document.run to CANCEL ("2")
  3. Returns {"success_count": N, "errors": [...]}

Test strategy

  • DAO/Service: SQLite in-memory DB, zero mocks. Redis is nil-safe by design.
  • Handler: fakeDocumentService implementing documentServiceIface interface.

🤖 Generated with Claude Code

xugangqiang and others added 8 commits June 3, 2026 21:17
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.
@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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 354b975d-1200-4ae7-bb68-e88c83c722cd

📥 Commits

Reviewing files that changed from the base of the PR and between db59e98 and c2e00a8.

📒 Files selected for processing (3)
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/document_test.go
💤 Files with no reviewable changes (1)
  • internal/service/document_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/router/router.go
  • internal/service/document.go

📝 Walkthrough

Walkthrough

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

Changes

Build Script Maintenance

Layer / File(s) Summary
libpcre2-8 dependency detection broadening
build.sh
check_cpp_deps and build_go now detect both static (.a) and shared (.so) libpcre2-8 variants across Linux and macOS and adjust Homebrew/macos messaging.

Document Parse Stopping and Deletion Refactoring

Layer / File(s) Summary
DAO signature and task query
internal/dao/document.go, internal/dao/task.go
DocumentDAO.Delete now returns (int64, error); added TaskDAO.GetByDocID(docID) to fetch tasks by document id.
DAO tests and test DB setup
internal/dao/task_test.go
In-memory SQLite test DB and tests validating GetByDocID success, empty results, and empty-docID edge case.
Handler contract and endpoint
internal/handler/document.go
Add StopParseDocuments to service interface, StopParseDocumentRequest and DocumentHandler.StopParseDocuments with JSON binding, validation, dataset access check, and delegation to service.
Handler tests for stop endpoint
internal/handler/document_test.go
Fake service stop behavior and tests for empty IDs, malformed JSON, success, service errors, and authorization failures; in-memory DB seeding for access checks.
Router wiring
internal/router/router.go
Register POST /api/v1/datasets/:dataset_id/documents/stop to documentHandler.StopParseDocuments.
Service imports
internal/service/document.go
Import cache/Redis and gorm packages to support cancel signaling and transactional deletion logic.
Deletion refactor and helpers
internal/service/document.go
Refactor deleteDocumentFull into helpers (resolveDocAndKB, engine cleanup, deleteDocRecordWithCounters guarded by RowsAffected, cleanupFileReferences) and centralize dataset-id validation.
Stop-parse service implementation
internal/service/document.go
Implement StopParseDocuments with dedupe and dataset validation; cancelDocParse inspects tasks, sets per-task Redis cancel keys best-effort, and updates document run to CANCEL; validateDocsInDataset verifies dataset membership.
Service unit tests
internal/service/document_test.go
Tests for shared-file preservation, resolve/delete helper behavior, and comprehensive StopParseDocuments cases (success, cancel status, not-running, unfinished tasks, wrong dataset, not found, empty IDs, deduplication); test helpers for seeding runs/tasks.
File service DAO adaptation
internal/service/file.go
deleteSingleFile updated to accept the new DocumentDAO.Delete return signature (ignore row count, handle error).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • JinHai-CN
  • Haruko386
  • yingfeng

Poem

🐰 I nudge the parse and call it done,
Redis whispers cancel, one by one,
Files stay shared where friends remain,
Counters guarded, no double pain,
A hopping rabbit seals the run.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.62% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description provides a clear summary, identifies the source endpoint, details all changed files with a summary table, explains the implementation approach, and describes the test strategy. However, it does not follow the provided template structure with the required 'What problem does this PR solve?' and 'Type of change' sections. Restructure the description to follow the template: add a 'What problem does this PR solve?' section and use the checkbox-based 'Type of change' section (select 'New Feature' for this migration).
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: migrating a Python endpoint to Go. It is concise, specific, and clearly conveys the primary objective without unnecessary details.
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.

@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

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

574-616: ⚡ Quick win

Redis 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 value

Counter 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

📥 Commits

Reviewing files that changed from the base of the PR and between 67c3e73 and db59e98.

📒 Files selected for processing (10)
  • build.sh
  • internal/dao/document.go
  • 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
  • internal/service/file.go

Comment thread build.sh
Comment on lines +35 to 43
# 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"

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 | 🟡 Minor | ⚡ Quick win

🧩 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 -B2

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

Comment thread internal/router/router.go Resolved
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 4, 2026 02:58
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 02:58
@codecov

codecov Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (67c3e73) to head (e42fa70).
⚠️ Report is 8 commits behind head on main.

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

Single-line wrapper with no extra logic beyond the DAO call + log.
Task deletion is already covered by TestDeleteDocumentFull_Basic.
@xugangqiang
xugangqiang force-pushed the feat/go-stop-parse-documents branch from db59e98 to c2e00a8 Compare June 4, 2026 03:30
@yingfeng
yingfeng merged commit c6eee09 into infiniflow:main Jun 4, 2026
1 of 2 checks passed
@xugangqiang
xugangqiang deleted the feat/go-stop-parse-documents branch August 7, 2026 12:45
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.

2 participants