Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix duplicate key error for insert_documents [FOEPD-209] #5503

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

kaixi-wang
Copy link
Contributor

@kaixi-wang kaixi-wang commented Feb 20, 2025

What changes are proposed in this pull request?

  • Add _id first to new docs instead of letting the pymongo client doing it to avoid duplicate key errors if the internal batching doesn't align with the batching done in the db client

  • With static batcher batch size set to 100k, progress stalls at 100k and throws bulk write error:

image
BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': "E11000 duplicate key error collection: fiftyone.frames.samples.67b67de56a622f511f9e0d6c index: _id_ dup key: { _id: ObjectId('67a17e0d9835e98a8c2bcd2f') }", 'keyPattern': {'_id': 1}, 'keyValue': {'_id': ObjectId('67a17e0d9835e98a8c2bcd2f')}, 'op': {'_id': ObjectId('67a17e0d9835e98a8c2bcd2f'), 'frame_number': 1, '_sample_id': ObjectId('67a17dfbc3f95f4b26f4181c'), '_dataset_id': ObjectId('67b67de56a622f511f9e0d6c'), 'created_at': datetime.datetime(2025, 2, 20, 0, 57, 10, 744794), 'last_modified_at': datetime.datetime(2025, 2, 20, 0, 57, 10, 744794), 'gt': {'_cls': 'Detections', 'detections': [{'_id': ObjectId('67a17e1ac3f95f4b26f4190a'), '_cls': 'Detection', 'attributes': {}, 'tags': [], 'label': 'lobster', 'bounding_box': [0.47183098591549294, 0.475, 0.25, 0.42916666666666664], 'index': 1, 'visibility': 1.0, 'supercategory': 'crustacean'}]}}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Cell In[7], line 1
----> 1 ds=load_from_hub(
      2     "Voxel51/WebUOT-238-Test",
      3     name="webuot",
      4     overwrite=True,
      5     )

...

/fiftyone/utils/data/importers.py:2015, in FiftyOneDatasetImporter._import_samples(self, dataset, dataset_dict, tags, progress)
   2012         fd["_dataset_id"] = dataset_id
   2013         return fd
-> 2015     foo.insert_documents(
   2016         map(_parse_frame, frames),
   2017         dataset._frame_collection,
   2018         ordered=self.ordered,
   2019         progress=progress,
   2020         num_docs=num_frames,
   2021     )
   2023 #
   2024 # Import saved views
   2025 #
   2027 if (
   2028     empty_import
   2029     and self.import_saved_views
   2030     and self.max_samples is None
   2031 ):

fiftyone/core/odm/database.py:898, in insert_documents(docs, coll, ordered, progress, num_docs)
    896 except BulkWriteError as bwe:
    897     msg = bwe.details["writeErrors"][0]["errmsg"]
--> 898     raise ValueError(msg) from bwe
    899 except Exception as e:
    900     print("insert_documents non bwe exception", e)

How is this patch tested? If it is not, please explain why.

  • No longer getting bulk write error:
image

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

@kaixi-wang kaixi-wang self-assigned this Feb 20, 2025
Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Walkthrough

The changes update the insert_documents function in the database module to ensure every document has a valid _id before insertion into MongoDB. The updated code removes any pre-existing _id, generates a new ObjectId for each document, and appends it as the first field. Additionally, the process of collecting document IDs is streamlined by directly appending each new _id during the iteration. The overall function structure remains the same with improved identifier handling.

Changes

File Change Summary
fiftyone/core/odm/database.py Modified insert_documents: Removes existing _id, generates a new ObjectId for each document, prepends the new _id to documents, and streamlines ID collection.

Sequence Diagram(s)

sequenceDiagram
  participant U as User/Caller
  participant F as insert_documents
  participant G as ObjectId Generator
  participant M as MongoDB Collection

  U->>F: Call insert_documents(docs, coll, ...)
  loop Process each document
    F->>F: Remove existing _id if present
    F->>G: Generate new ObjectId
    G-->>F: Return new _id
    F->>F: Prepend new _id to document
  end
  F->>M: Insert modified documents batch
  M-->>F: Return inserted document IDs
  F->>U: Return list of new _id values
Loading

Possibly related PRs

Poem

I’m just a coding bunny, hopping through the night,
Transforming data fields with a twinkle so bright.
Each document adorned with a brand new ID,
A fresh start in Mongo, as happy as can be.
With every new ObjectId, my joy takes flight!
🐇💻 Hop along, let’s code it right!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
fiftyone/core/odm/database.py (1)

959-964: Well-structured solution for preventing duplicate key errors!

The changes follow the MongoDB specification for document insertion by ensuring that:

  1. Each document has a unique _id
  2. The _id field appears first in the document structure

This approach effectively prevents duplicate key errors that can occur during batch insertions.

Consider adding input validation.

To make the function more robust, consider adding validation for the input documents:

 for i, doc in enumerate(batch):
+    if not isinstance(doc, dict):
+        raise ValueError(f"Document at index {i} must be a dict, got {type(doc)}")
     _id = doc.pop("_id", ObjectId())
     ids.append(_id)
     batch[i] = {"_id": _id, **doc}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef8b74d and 9249a37.

📒 Files selected for processing (1)
  • fiftyone/core/odm/database.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.10)
  • GitHub Check: test / test-app
  • GitHub Check: e2e / test-e2e
  • GitHub Check: build / build
  • GitHub Check: lint / eslint
  • GitHub Check: build

@swheaton
Copy link
Contributor

if the internal batching doesn't align with the batching done in the db client

what does this mean?

batch = list(batch)
# Modify each document client-side and ensure _id exists and is first
# https://github.com/mongodb/specifications/blob/master/source/crud/bulk-write.md#insert
for i, doc in enumerate(batch):
Copy link
Contributor

@minhtuev minhtuev Feb 20, 2025

Choose a reason for hiding this comment

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

Can we parallelize this :P (jk haha!)

@minhtuev
Copy link
Contributor

Damn how do you figure this out

@swheaton
Copy link
Contributor

@kaixi-wang

  1. can you explain this a little bit more? Are you saying that if we leave ObjectID creation up to the driver, in some cases it can generate the same ObjectID for 2 separate documents? Or something else given this comment: if the internal batching doesn't align with the batching done in the db client

  2. this is on sample import, but do we think this will solve to_frames() issue also?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants