Skip to content

PYTHON-5212 - Do not hold Topology lock while resetting pool #2301

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

Merged
merged 10 commits into from
Apr 23, 2025

Conversation

NoahStapp
Copy link
Contributor

No description provided.

Copy link
Member

@ShaneHarvey ShaneHarvey left a comment

Choose a reason for hiding this comment

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

Is there any regression test we can add for this? Perhaps one that mocks a slow close and ensures other operations proceed unblocked?

for conn in sockets:
await conn.close_conn(ConnectionClosedReason.POOL_CLOSED)
if not _IS_SYNC:
await asyncio.gather(
Copy link
Member

Choose a reason for hiding this comment

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

We probably want to use return_exceptions=True here to ensure all tasks complete.

for conn in close_conns:
await conn.close_conn(ConnectionClosedReason.IDLE)
if not _IS_SYNC:
await asyncio.gather(
Copy link
Member

Choose a reason for hiding this comment

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

same here.

@@ -557,6 +551,11 @@ async def on_change(
# that didn't include this server.
if self._opened and self._description.has_server(server_description.address):
await self._process_change(server_description, reset_pool, interrupt_connections)
# Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on connection close.
if self._opened and self._description.has_server(server_description.address) and reset_pool:
server = self._servers.get(server_description.address)
Copy link
Member

Choose a reason for hiding this comment

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

The has_server -> _servers.get pattern is not safe to do here (https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use)

We also don't need to check for closed/opened because pool.reset is safe to call even after close().

Instead we can do:

if reset_pool:
    server = self._servers.get(server_description.address)
    if server:
        await server.pool.reset(interrupt_connections=interrupt_connections)

@NoahStapp
Copy link
Contributor Author

Is there any regression test we can add for this? Perhaps one that mocks a slow close and ensures other operations proceed unblocked?

That was my thought as well, working on adding such a test today.

@NoahStapp NoahStapp requested a review from ShaneHarvey April 23, 2025 13:41
elapsed = time.monotonic() - start_time
latencies.append(elapsed)
if elapsed >= close_delay:
break
Copy link
Member

Choose a reason for hiding this comment

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

If elapsed is always < close_delay, this loop will never exit?

Could we replace this with an exit condition like this?:

        latencies = []
        should_exit = []
        async def run_task():
        ...
                if should_exit:
                    break
        ...

            # Wait until all idle connections are closed to simulate real-world conditions
            await listener.async_wait_for_event(monitoring.ConnectionClosedEvent, 10)
            should_exit.append(True)
            await task.join()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The classic list-as-mutable-state technique!

# Wait until all idle connections are closed to simulate real-world conditions
await listener.async_wait_for_event(monitoring.ConnectionClosedEvent, 10)
# No operation latency should not significantly exceed close_delay
self.assertLessEqual(max(latencies), close_delay * 2.0)
Copy link
Member

Choose a reason for hiding this comment

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

I worry this test will be flaky. A single op can easily take >100 ms in our CI depending on the host (mac/windows). Could you increase the close_delay to 0.1 and increase this line to close_delay * 5? Since there are 10 connections to close, * 5 should still catch the regression right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I would expect close_delay * 5 to catch regressions consistently, yeah.

minPoolSize=10,
)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
Copy link
Member

Choose a reason for hiding this comment

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

readable_server_selector -> writeable_server_selector. The test is using primary read preference so we should wait for 10 connections to the primary node.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Because only the primary is writeable? Makes sense.

@NoahStapp NoahStapp requested a review from ShaneHarvey April 23, 2025 18:11
@@ -1864,6 +1864,7 @@ def test_direct_connection(self):
MongoClient(["host1", "host2"], directConnection=True)

@unittest.skipIf("PyPy" in sys.version, "PYTHON-2927 fails often on PyPy")
@skipIf(os.environ.get("DEBUG_LOG"), "Enabling debug logs breaks this test")
Copy link
Member

Choose a reason for hiding this comment

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

Was this intentionally added?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Whoops this was for testing purposes. Intended to be done in a separate ticket.

await listener.async_wait_for_event(monitoring.ServerHeartbeatFailedEvent, 1)
# Wait until all idle connections are closed to simulate real-world conditions
await listener.async_wait_for_event(monitoring.ConnectionClosedEvent, 10)
should_exit.append(True)
Copy link
Member

Choose a reason for hiding this comment

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

The test should join the task here after should_exit.append(True) otherwise we may miss a latency. Also one more thing:

            # Wait until all idle connections are closed to simulate real-world conditions
            await listener.async_wait_for_event(monitoring.ConnectionClosedEvent, 10)
            # Wait for one more find to complete, then shutdown the task.
            n = len(latencies)
            await async_wait_until(lambda: len(latencies) >= n + 1, "run one more find")
            should_exit.append(True)
            await task.join()
            

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I see, that way we ensure that the operations are still working after the pool reset completes.

@NoahStapp NoahStapp requested a review from ShaneHarvey April 23, 2025 18:45
@NoahStapp NoahStapp merged commit 09897b6 into mongodb:master Apr 23, 2025
30 of 32 checks passed
blink1073 pushed a commit to blink1073/mongo-python-driver that referenced this pull request Apr 23, 2025
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.

2 participants