Skip to content

fix: duplicate document ingest guard - #15638

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b063
Jun 4, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b063

Conversation

@buua436

@buua436 buua436 commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

When a document is rerun or updated concurrently, the previous unconditional update could overwrite a newer task state.
This change adds an update_time-based optimistic lock so the update only succeeds if the record has not been modified by another flow in the meantime.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR prevents duplicate document ingestion by detecting unfinished, non-canceled tasks per document and rejecting new RUNNING ingests; it also adds an optimistic-locking update (update_by_id_if_update_time) and rejects the request if the update affects no rows.

Changes

Document ingest running-state validation

Layer / File(s) Summary
Active task detection and rejection
api/apps/restful_apis/document_api.py
Import updated to include has_canceled. When req["run"] == TaskStatus.RUNNING, the endpoint queries the document's tasks and blocks ingest with RetCode.DATA_ERROR / "Document is already running" if the document is RUNNING/SCHEDULE or an active unfinished (progress < 1) non-canceled task exists.
Optimistic document update
api/db/services/common_service.py, api/apps/restful_apis/document_api.py
Adds CommonService.update_by_id_if_update_time which updates a record only if the persisted update_time matches the provided value; document_api uses it to set the document status and rejects the ingest when affected_rows == 0 indicating a concurrent update/active run.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14351: Both PRs modify api/apps/restful_apis/document_api.py around the ingest _run_sync orchestration; this PR tightens the "already running"/active-task checks and adds optimistic updates.

Suggested labels

size:L, lgtm

Suggested reviewers

  • wangq8

Poem

🐰 I hop where tasks are lined in rows,
I sniff for runs that nobody knows,
If progress lingers and isn't cleared,
I stop the feed — no duplicates feared.
A gentle thump: the DB stays slow.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: duplicate document ingest guard' clearly summarizes the main change: adding protection against duplicate/concurrent document ingestion.
Description check ✅ Passed The description includes both required sections from the template: a clear problem statement explaining the race condition and concurrent update issue, and the 'Bug Fix' type is properly selected.
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.

@buua436
buua436 marked this pull request as ready for review June 4, 2026 06:58
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 4, 2026
@buua436 buua436 added the ci Continue Integration label Jun 4, 2026
@buua436
buua436 marked this pull request as draft June 4, 2026 07:00
@buua436
buua436 marked this pull request as ready for review June 4, 2026 07:01
@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 (7b7099e).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15638   +/-   ##
=======================================
  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.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 4, 2026
@buua436
buua436 requested a review from wangq8 June 4, 2026 07:44

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

🧹 Nitpick comments (1)
api/db/services/common_service.py (1)

279-297: ⚡ Quick win

Add logging for this new optimistic locking flow.

The optimistic locking logic is correct and follows the expected pattern. However, this new concurrency control mechanism should include logging to aid debugging when concurrent document ingestion attempts occur.

Consider logging when the optimistic lock fails (0 rows affected), as this indicates a concurrent update was detected:

📊 Suggested logging addition
     `@classmethod`
     `@DB.connection_context`()
     `@retry_db_operation`
     def update_by_id_if_update_time(cls, pid, update_time, data):
         # Update a single record by ID only if update_time matches the expected value.
         # Args:
         #     pid: Record ID
         #     update_time: Expected update_time value for optimistic locking
         #     data: Updated field values
         # Returns:
         #     Number of records updated
         data["update_time"] = current_timestamp()
         data["update_date"] = datetime_format(datetime.now())
         num = (
             cls.model.update(data)
             .where(cls.model.id == pid, cls.model.update_time == update_time)
             .execute()
         )
+        if num == 0:
+            logging.warning(
+                "Optimistic lock failed for %s id=%s (expected update_time=%s). "
+                "Document may have been concurrently updated.",
+                cls.model.__name__, pid, update_time
+            )
+        else:
+            logging.debug("Optimistically updated %s id=%s", cls.model.__name__, pid)
         return num

As per coding guidelines, the pattern **/*.py requires: "Add logging for new flows". This optimistic locking flow is critical for preventing duplicate document ingestion, so visibility into lock failures will help diagnose concurrent access issues.

🤖 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 `@api/db/services/common_service.py` around lines 279 - 297, Add logging to the
optimistic-locking path in update_by_id_if_update_time: after executing
cls.model.update(...).execute() check if num == 0 and log a warning (via a
module logger) including the function name update_by_id_if_update_time, the pid,
the expected update_time, and minimal identifying fields from data to aid
debugging; ensure a logger is defined (e.g., logging.getLogger(__name__)) if not
already present and keep the log message concise and structured so
concurrent-update failures are visible.
🤖 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.

Nitpick comments:
In `@api/db/services/common_service.py`:
- Around line 279-297: Add logging to the optimistic-locking path in
update_by_id_if_update_time: after executing cls.model.update(...).execute()
check if num == 0 and log a warning (via a module logger) including the function
name update_by_id_if_update_time, the pid, the expected update_time, and minimal
identifying fields from data to aid debugging; ensure a logger is defined (e.g.,
logging.getLogger(__name__)) if not already present and keep the log message
concise and structured so concurrent-update failures are visible.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9e052c49-cbf6-40af-b154-e927e6811a71

📥 Commits

Reviewing files that changed from the base of the PR and between f4aba22 and 35f8348.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • api/db/services/common_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/document_api.py

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

🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)

1417-1423: ⚡ Quick win

Add explicit logs for optimistic-lock miss and deferred cancel dispatch.

Line 1419 and Line 1422 are key concurrency outcomes but currently silent. Add structured logs with doc_id and requested run to improve incident triage.

Proposed patch
         affected_rows = DocumentService.update_by_id_if_update_time(doc_id, doc.update_time, info)
         if not affected_rows:
+            logging.warning(
+                "ingest skipped by optimistic lock: doc_id=%s requested_run=%s",
+                doc_id,
+                req["run"],
+            )
             return RetCode.DATA_ERROR, "Document is already running"
 
         if str(req["run"]) == TaskStatus.CANCEL.value and should_cancel:
+            logging.info("ingest cancel signal dispatched: doc_id=%s", doc_id)
             cancel_all_task_of(doc_id)

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1417 - 1423, When the
optimistic-lock check in DocumentService.update_by_id_if_update_time returns no
affected_rows and when the deferred cancel is dispatched before
cancel_all_task_of, add structured logs including doc_id and the requested run
value (req["run"]). Specifically, insert a processLogger.error or
processLogger.warn (consistent with project logging) right after the
affected_rows check to log that the optimistic-lock missed with doc_id and run,
and insert a processLogger.info/debug before calling cancel_all_task_of to
record that a deferred cancel is being issued with doc_id and run; reference
DocumentService.update_by_id_if_update_time, cancel_all_task_of, doc_id,
req["run"], and TaskStatus.CANCEL when locating the code to change.
🤖 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.

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1417-1423: When the optimistic-lock check in
DocumentService.update_by_id_if_update_time returns no affected_rows and when
the deferred cancel is dispatched before cancel_all_task_of, add structured logs
including doc_id and the requested run value (req["run"]). Specifically, insert
a processLogger.error or processLogger.warn (consistent with project logging)
right after the affected_rows check to log that the optimistic-lock missed with
doc_id and run, and insert a processLogger.info/debug before calling
cancel_all_task_of to record that a deferred cancel is being issued with doc_id
and run; reference DocumentService.update_by_id_if_update_time,
cancel_all_task_of, doc_id, req["run"], and TaskStatus.CANCEL when locating the
code to change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9be62780-7a5d-4c70-9f99-0a7815e0bdb6

📥 Commits

Reviewing files that changed from the base of the PR and between 35f8348 and 7b7099e.

📒 Files selected for processing (1)
  • api/apps/restful_apis/document_api.py

@wangq8
wangq8 merged commit 423fb6f into infiniflow:main Jun 4, 2026
1 check passed
wangq8 added a commit that referenced this pull request Jun 5, 2026
geversite pushed a commit to geversite/ragflow that referenced this pull request Jul 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants