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(NODE-6878): ensure documents are cleared correctly to handle emptyGe… #4488

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

Conversation

italojs
Copy link

@italojs italojs commented Mar 26, 2025

Jira issue: https://jira.mongodb.org/browse/NODE-6878

MongoDB Driver: documents?.clear() is not a function error in AbstractCursor.rewind()

Issue Description

When using the MongoDB Node.js driver, there's an issue in the rewind() method of AbstractCursor. The method attempts to call this.documents?.clear() without checking if the clear() method exists on the documents object.

In certain scenarios, particularly when the MongoDB driver uses an optimization called emptyGetMore to avoid unnecessary server calls, this.documents is set to a simplified object literal that lacks the clear() method:

CursorResponse.emptyGetMore = {
    id: new bson_1.Long(0),
    length: 0,
    shift: () => null
    // Note: no clear() method defined
};

This causes an error when rewind() is called on cursors that have this optimization applied:

rewind() {
    if (!this.initialized) {
        return;
    }
    this.cursorId = null;
    this.documents?.clear(); // <-- This line causes the error
    this.isClosed = false;
    this.isKilled = false;
    this.initialized = false;
    // ...
}

Impact

This issue can cause applications to crash when:

  1. Using cursor operations that internally call rewind()
  2. Working with cursors that have been optimized using emptyGetMore
  3. Attempting to reset or reuse cursors after they've been exhausted

Reproduction Details

In this repository, the reproduction.js script demonstrates this issue by:

  1. Creating a MongoDB cursor with a small batch size
  2. Consuming all documents to exhaust the cursor
  3. Simulating the emptyGetMore optimization by replacing the documents object with one that lacks a clear() method
  4. Attempting to rewind the cursor, which triggers the error
  5. Trying to reuse the cursor, which would normally work if rewind() succeeded

Running the Reproduction

# Install dependencies
npm i

# Run the reproduction script
node reproduction.js

Expected output will show the error:

Rewind error: this.documents?.clear is not a function
Error name: TypeError

Proposed Solution

The issue can be fixed by modifying the rewind() method to safely handle cases where documents doesn't have a clear() method. Here's the proposed fix:

rewind() {
    if (!this.initialized) {
        return;
    }
    this.cursorId = null;
    
    // Check if documents exists and has a clear method before calling it
    if (this.documents && typeof this.documents.clear === 'function') {
        this.documents.clear();
    } else {
        // If documents is the emptyGetMore object or doesn't have the clear() method
        // Simply set it to null to force reinitialization
        this.documents = null;
    }
    
    this.isClosed = false;
    this.isKilled = false;
    this.initialized = false;
    // ... rest of the method
}

Why This Solution Works

  1. Safety: The solution checks if clear() exists before calling it
  2. Functionality: Setting documents to null achieves the same goal as clear() - it resets the cursor's document buffer
  3. Compatibility: The solution maintains compatibility with both regular cursors and optimized emptyGetMore cursors
  4. Performance: The solution doesn't introduce any significant overhead

References

@italojs italojs requested a review from a team as a code owner March 26, 2025 00:45
@baileympearson baileympearson added the External Submission PR submitted from outside the team label Mar 26, 2025
@dariakp dariakp added the tracked-in-jira Ticket filed in MongoDB's Jira system label Mar 26, 2025
@dariakp dariakp changed the title fix(cursor): ensure documents are cleared correctly to handle emptyGe… fix(NODE-6878): ensure documents are cleared correctly to handle emptyGe… Mar 26, 2025
@baileympearson baileympearson self-assigned this Mar 26, 2025
@baileympearson baileympearson added the Primary Review In Review with primary reviewer, not yet ready for team's eyes label Mar 26, 2025
@baileympearson
Copy link
Contributor

Hey @italojs ,

Thanks for the submission and good catch! We can reproduce this issue as well. The culprit behind this issue seems to be a Typescript cast as unknown as CursorResponse:

} as unknown as CursorResponse;
. Your solution seems to make the error go away but we're concerned that other errors might arise in the future and be squashed by the same Typescript cast.

We think that a more future-proof approach might be to directly instantiate a CursorResponse:

static get emptyGetMore(): CursorResponse {
  return new CursorResponse(
    serialize({ ok: 1, cursor: { id: 0, nextBatch: [] } })
  )
}

Would you be willing to make this change? The static getter is important here to avoid serialization at the module-level and only serialize when needed.

Also, we'll need a test for this scenario to confirm that the behavior has been fixed. Would you be willing to add a regression test? I believe find.test.js is a good place for a test, and we can trigger the error by:

  1. testing on sharded clusters
  2. insert a few documents into a collection
  3. create a cursor with a limit and batch size, where limit is a multiple of the batch size and also less than the number of documents inserted
  4. iterate the cursor limit + 1 times
  5. rewind the cursor

Without the changes in this PR, the above throws an error. I'm also happy to make these changes if you'd prefer, just let me know.

Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
External Submission PR submitted from outside the team Primary Review In Review with primary reviewer, not yet ready for team's eyes tracked-in-jira Ticket filed in MongoDB's Jira system
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants