Repository navigation
fix: duplicate document ingest guard - #15638
Conversation
📝 WalkthroughWalkthroughThe 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 ( ChangesDocument ingest running-state validation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/db/services/common_service.py (1)
279-297: ⚡ Quick winAdd 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 numAs per coding guidelines, the pattern
**/*.pyrequires: "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
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pyapi/db/services/common_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/apps/restful_apis/document_api.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1417-1423: ⚡ Quick winAdd 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_idand requestedrunto 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
📒 Files selected for processing (1)
api/apps/restful_apis/document_api.py
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