Skip to content

Python 4542 - Improved sessions API#2712

Open
NoahStapp wants to merge 12 commits intomongodb:masterfrom
NoahStapp:PYTHON-4542
Open

Python 4542 - Improved sessions API#2712
NoahStapp wants to merge 12 commits intomongodb:masterfrom
NoahStapp:PYTHON-4542

Conversation

@NoahStapp
Copy link
Contributor

@NoahStapp NoahStapp commented Feb 23, 2026

[PYTHON-4542]

Changes in this PR

Add ClientSession.bind() (and its async counterpart AsyncClientSession.bind()) for a better user experience when using explicit sessions.

Test Plan

Modified TestSession._test_ops() to include explicit bound sessions. Added a new test to verify correct nested behavior of multiple ClientSession.bind() calls and a new test to verify correctness of the end_session parameter of bind().

Checklist

Checklist for Author

  • Did you update the changelog (if necessary)?
  • Is there test coverage?
  • Is any followup work tracked in a JIRA ticket? If so, add link(s).

Checklist for Reviewer

  • Does the title of the PR reference a JIRA Ticket?
  • Do you fully understand the implementation? (Would you be comfortable explaining how this code works to someone else?)
  • Is all relevant documentation (README or docstring) updated?

if session is not None:
session._process_response(reply)

def _get_bound_session(self) -> Optional[AsyncClientSession]:
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is encapsulated in a separate utility function because cursor operations call _ensure_session directly, while most other database operations call _tmp_session instead. Separating out this check keeps the clarity of the current behavioral differences with minimal code duplication.

@NoahStapp NoahStapp marked this pull request as ready for review February 23, 2026 20:33
@NoahStapp NoahStapp requested a review from a team as a code owner February 23, 2026 20:33
@NoahStapp NoahStapp requested review from ShaneHarvey, aclark4life and caseyclements and removed request for caseyclements February 23, 2026 20:33
@codecov-commenter
Copy link

codecov-commenter commented Feb 23, 2026

Codecov Report

❌ Patch coverage is 96.77419% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.59%. Comparing base (84814b2) to head (e00ac18).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
pymongo/asynchronous/client_session.py 94.44% 0 Missing and 1 partial ⚠️
pymongo/synchronous/client_session.py 94.44% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2712      +/-   ##
==========================================
+ Coverage   87.54%   87.59%   +0.05%     
==========================================
  Files         141      141              
  Lines       24098    24152      +54     
  Branches     4118     4126       +8     
==========================================
+ Hits        21097    21157      +60     
+ Misses       2110     2105       -5     
+ Partials      891      890       -1     
Flag Coverage Δ
auth-aws-rhel8-test-auth-aws-rapid-web-identity-python3.14-cov 35.08% <37.09%> (+<0.01%) ⬆️
auth-aws-win64-test-auth-aws-rapid-web-identity-python3.14-cov 35.08% <37.09%> (+<0.01%) ⬆️
auth-enterprise-macos-test-standard-auth-latest-python3.11-auth-ssl-sharded-cluster-cov 43.73% <45.16%> (+<0.01%) ⬆️
auth-enterprise-rhel8-test-standard-auth-latest-python3.11-auth-ssl-sharded-cluster-cov 43.72% <45.16%> (+<0.01%) ⬆️
auth-enterprise-win64-test-standard-auth-latest-python3.11-auth-ssl-sharded-cluster-cov 43.74% <45.16%> (-0.01%) ⬇️
auth-oidc-local-ubuntu-22-test-auth-oidc-default 48.71% <45.16%> (+0.05%) ⬆️
compression-snappy-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.21% <62.90%> (+0.03%) ⬆️
compression-snappy-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.12% <62.90%> (+0.02%) ⬆️
compression-snappy-rhel8-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.53% <62.90%> (+0.02%) ⬆️
compression-snappy-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.84% <62.90%> (+0.02%) ⬆️
compression-zlib-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.20% <62.90%> (+0.02%) ⬆️
compression-zlib-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.12% <62.90%> (+0.02%) ⬆️
compression-zlib-rhel8-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.53% <62.90%> (+0.02%) ⬆️
compression-zlib-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.84% <62.90%> (+0.02%) ⬆️
compression-zstd-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.20% <62.90%> (+0.03%) ⬆️
compression-zstd-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.12% <62.90%> (+0.02%) ⬆️
compression-zstd-rhel8-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.54% <62.90%> (+0.02%) ⬆️
compression-zstd-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.85% <62.90%> (+0.03%) ⬆️
compression-zstd-ubuntu-22-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.83% <62.90%> (+0.03%) ⬆️
coverage-report-coverage-report 87.56% <96.77%> (+0.38%) ⬆️
disable-test-commands-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.20% <62.90%> (+0.03%) ⬆️
disable-test-commands-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.12% <62.90%> (+0.02%) ⬆️
disable-test-commands-rhel8-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.53% <62.90%> (+0.02%) ⬆️
disable-test-commands-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.85% <62.90%> (+0.01%) ⬆️
encryption-crypt_shared-macos-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.82% <45.16%> (-0.01%) ⬇️
encryption-crypt_shared-macos-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 54.73% <45.16%> (-0.01%) ⬇️
encryption-crypt_shared-macos-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.56% <45.16%> (+0.01%) ⬆️
encryption-crypt_shared-rhel8-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.81% <45.16%> (-0.02%) ⬇️
encryption-crypt_shared-rhel8-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 54.58% <45.16%> (-0.06%) ⬇️
encryption-crypt_shared-rhel8-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.52% <45.16%> (-0.02%) ⬇️
encryption-crypt_shared-win64-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.68% <45.16%> (-0.03%) ⬇️
encryption-crypt_shared-win64-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 54.65% <45.16%> (-0.02%) ⬇️
encryption-crypt_shared-win64-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.60% <45.16%> (-0.02%) ⬇️
encryption-macos-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.80% <45.16%> (-0.03%) ⬇️
encryption-macos-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov ?
encryption-macos-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.56% <45.16%> (-0.01%) ⬇️
encryption-pyopenssl-rhel8-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 53.49% <45.16%> (-0.03%) ⬇️
encryption-pyopenssl-rhel8-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 55.28% <45.16%> (-0.03%) ⬇️
encryption-pyopenssl-rhel8-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 55.22% <45.16%> (-0.01%) ⬇️
encryption-rhel8-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.81% <45.16%> (-0.02%) ⬇️
encryption-rhel8-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 54.60% <45.16%> (-0.02%) ⬇️
encryption-rhel8-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.55% <45.16%> (+<0.01%) ⬆️
encryption-win64-test-non-standard-latest-python3.13-noauth-nossl-standalone-cov 52.74% <45.16%> (+0.02%) ⬆️
encryption-win64-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 54.72% <45.16%> (-0.02%) ⬇️
encryption-win64-test-non-standard-latest-python3.14t-noauth-ssl-replica-set-cov 54.62% <45.16%> (-0.01%) ⬇️
load-balancer-test-non-standard-latest-python3.14-auth-ssl-sharded-cluster-cov 48.31% <45.16%> (-0.01%) ⬇️
mongodb-latest-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 56.92% <62.90%> (+0.02%) ⬆️
mongodb-latest-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 55.22% <62.90%> (+0.02%) ⬆️
mongodb-latest-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 59.11% <62.90%> (+0.01%) ⬆️
mongodb-latest-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 59.26% <62.90%> (+0.01%) ⬆️
mongodb-latest-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 57.05% <62.90%> (+0.02%) ⬆️
mongodb-rapid-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 56.92% <62.90%> (+0.02%) ⬆️
mongodb-rapid-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 55.22% <62.90%> (+0.02%) ⬆️
mongodb-rapid-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 59.11% <62.90%> (+0.01%) ⬆️
mongodb-rapid-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 59.26% <62.90%> (+0.01%) ⬆️
mongodb-rapid-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 57.05% <62.90%> (+<0.01%) ⬆️
mongodb-v4.2-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 54.63% <62.90%> (+0.01%) ⬆️
mongodb-v4.2-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 53.20% <62.90%> (+0.05%) ⬆️
mongodb-v4.2-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 56.81% <62.90%> (+0.02%) ⬆️
mongodb-v4.2-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 56.93% <62.90%> (+0.02%) ⬆️
mongodb-v4.2-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 54.77% <62.90%> (+0.01%) ⬆️
mongodb-v4.4-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 55.02% <62.90%> (+0.03%) ⬆️
mongodb-v4.4-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 53.47% <62.90%> (+0.04%) ⬆️
mongodb-v4.4-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 57.22% <62.90%> (+0.02%) ⬆️
mongodb-v4.4-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 57.30% <62.90%> (+0.02%) ⬆️
mongodb-v4.4-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 55.09% <62.90%> (+0.01%) ⬆️
mongodb-v5.0-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 55.20% <62.90%> (+<0.01%) ⬆️
mongodb-v5.0-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 53.62% <62.90%> (+0.04%) ⬆️
mongodb-v5.0-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 57.41% <62.90%> (+0.02%) ⬆️
mongodb-v5.0-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 57.54% <62.90%> (+0.02%) ⬆️
mongodb-v5.0-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 55.33% <62.90%> (+0.03%) ⬆️
mongodb-v6.0-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 55.23% <62.90%> (+0.02%) ⬆️
mongodb-v6.0-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 53.64% <62.90%> (+0.04%) ⬆️
mongodb-v6.0-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 57.43% <62.90%> (+0.02%) ⬆️
mongodb-v6.0-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 57.58% <62.90%> (+0.02%) ⬆️
mongodb-v6.0-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 55.37% <62.90%> (+0.02%) ⬆️
mongodb-v7.0-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 55.23% <62.90%> (+0.02%) ⬆️
mongodb-v7.0-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 53.62% <62.90%> (+0.02%) ⬆️
mongodb-v7.0-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 57.44% <62.90%> (+0.02%) ⬆️
mongodb-v7.0-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 57.58% <62.90%> (+0.02%) ⬆️
mongodb-v7.0-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 55.36% <62.90%> (+0.02%) ⬆️
mongodb-v8.0-test-server-version-python3.10-async-auth-ssl-sharded-cluster-min-deps-cov 56.95% <62.90%> (+0.03%) ⬆️
mongodb-v8.0-test-server-version-python3.10-async-noauth-nossl-standalone-min-deps-cov 55.22% <62.90%> (+0.03%) ⬆️
mongodb-v8.0-test-server-version-python3.10-sync-auth-ssl-sharded-cluster-min-deps-cov 59.11% <62.90%> (+0.01%) ⬆️
mongodb-v8.0-test-server-version-python3.10-sync-noauth-nossl-replica-set-min-deps-cov 59.26% <62.90%> (+0.01%) ⬆️
mongodb-v8.0-test-server-version-python3.11-async-noauth-nossl-replica-set-cov 57.05% <62.90%> (+0.01%) ⬆️
no-c-ext-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 56.43% <62.90%> (+0.03%) ⬆️
no-c-ext-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 58.34% <62.90%> (+0.01%) ⬆️
no-c-ext-rhel8-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 57.75% <62.90%> (+0.02%) ⬆️
no-c-ext-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 56.06% <62.90%> (+0.02%) ⬆️
ocsp-rhel8-test-ocsp-ecdsa-valid-cert-server-staples-latest-python3.14-cov 34.08% <35.48%> (+0.01%) ⬆️
ocsp-rhel8-test-ocsp-rsa-valid-cert-server-staples-latest-python3.14-cov 34.08% <35.48%> (+0.02%) ⬆️
pyopenssl-macos-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.03% <62.90%> (+0.02%) ⬆️
pyopenssl-rhel8-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.03% <62.90%> (+0.02%) ⬆️
pyopenssl-win64-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 56.97% <62.90%> (+0.02%) ⬆️
stable-api-accept-v2-rhel8-auth-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.20% <62.90%> (+0.03%) ⬆️
stable-api-accept-v2-rhel8-auth-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.85% <62.90%> (+0.03%) ⬆️
stable-api-require-v1-rhel8-auth-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.19% <62.90%> (+0.04%) ⬆️
stable-api-require-v1-rhel8-auth-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.41% <62.90%> (+0.02%) ⬆️
stable-api-require-v1-rhel8-auth-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.83% <62.90%> (+0.02%) ⬆️
storage-inmemory-rhel8-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.20% <62.90%> (+0.03%) ⬆️
storage-inmemory-rhel8-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.84% <62.90%> (+0.02%) ⬆️
test-macos-arm64-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.19% <62.90%> (+0.05%) ⬆️
test-macos-arm64-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.11% <62.90%> (+0.01%) ⬆️
test-macos-arm64-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.54% <62.90%> (+0.02%) ⬆️
test-macos-arm64-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.81% <62.90%> (+0.03%) ⬆️
test-macos-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.19% <62.90%> (+0.03%) ⬆️
test-macos-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.12% <62.90%> (+0.02%) ⬆️
test-macos-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.53% <62.90%> (+0.02%) ⬆️
test-macos-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.81% <62.90%> (+0.03%) ⬆️
test-numpy-macos-arm64-test-numpy-python3.14-python3.14-cov 32.26% <29.03%> (-0.02%) ⬇️
test-numpy-macos-test-numpy-python3.14-python3.14-cov 32.26% <29.03%> (-0.01%) ⬇️
test-numpy-rhel8-test-numpy-python3.14-python3.14-cov 32.26% <29.03%> (-0.02%) ⬇️
test-numpy-win32-test-numpy-python3.14-python3.14-cov 32.22% <29.03%> (-0.01%) ⬇️
test-numpy-win64-test-numpy-python3.14-python3.14-cov 32.24% <29.03%> (+<0.01%) ⬆️
test-win32-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.05% <62.90%> (+0.03%) ⬆️
test-win32-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.06% <62.90%> (+0.02%) ⬆️
test-win32-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.47% <62.90%> (+0.02%) ⬆️
test-win32-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.68% <62.90%> (+0.02%) ⬆️
test-win64-test-standard-latest-python3.11-async-noauth-nossl-standalone-cov 55.06% <62.90%> (+0.03%) ⬆️
test-win64-test-standard-latest-python3.12-async-noauth-ssl-replica-set-cov 57.06% <62.90%> (+0.02%) ⬆️
test-win64-test-standard-latest-python3.13-async-auth-ssl-sharded-cluster-cov 56.47% <62.90%> (+0.02%) ⬆️
test-win64-test-standard-latest-python3.14-async-noauth-nossl-standalone-cov 54.68% <62.90%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


- Added the :meth:`~pymongo.asynchronous.client_session.AsyncClientSession.bind` and :meth:`~pymongo.client_session.ClientSession.bind` methods
that allow users to bind a session to all database operations within the scope of a context manager instead of having to explicitly pass the session to each individual operation.
See <PLACEHOLDER> for examples and more information.
Copy link
Contributor

Choose a reason for hiding this comment

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

<PLACEHOLDER> should be the MongoDB docs ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah once we have examples and such added to a page I'll update these spots.

self._attached_to_cursor = False
# Should we leave the session alive when the cursor is closed?
self._leave_alive = False
# Is this session bound to a scope?
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: I had to look up what "scope" means in this context so maybe "# Is this session bound to a context manager scope?"

return bound_session.session
else:
raise InvalidOperation(
"Only the client that created the bound session can perform operations within its context block. See <PLACEHOLDER> for more information."
Copy link
Contributor

Choose a reason for hiding this comment

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

Another <PLACEHOLDER> here … assuming that maybe these come out after merge?

def _ensure_session(self, session: Optional[ClientSession] = None) -> Optional[ClientSession]:
"""If provided session is None, lend a temporary session."""
"""If provided session and bound session are None, lend a temporary session."""
session = session or self._get_bound_session()
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't understand what's going on here before the changes. How does:

if session:
    return session

lend a temporary session?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We call _ensure_session(session) in a bunch of places where session is an actual explicit session if the user passed one to the operation. The former if session: return session check is to return that explicit session if it exists instead of lending a temporary one.

return bound_session.session
else:
raise InvalidOperation(
"Only the client that created the bound session can perform operations within its context block. See <PLACEHOLDER> for more information."
Copy link
Contributor

Choose a reason for hiding this comment

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

Third <PLACEHOLDER> maybe synchro'd

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds a “bound session” mechanism to PyMongo’s explicit sessions so users can scope a ClientSession/AsyncClientSession to all operations within a context block (without passing session=... to every call).

Changes:

  • Introduces ClientSession.bind() / AsyncClientSession.bind() backed by a ContextVar, and updates MongoClient/AsyncMongoClient to use a bound session when no session is explicitly provided.
  • Expands sync/async session tests to cover bound-session behavior and nested binding.
  • Updates changelog and synchro/unasync replacement mapping for the new internal bound-session helper type.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
tools/synchro.py Adds unasync replacement mapping for the new bound-session helper type.
pymongo/synchronous/client_session.py Adds ContextVar-based bound-session support and ClientSession.bind().
pymongo/synchronous/mongo_client.py Uses bound session in _ensure_session/_tmp_session and adds _get_bound_session().
pymongo/asynchronous/client_session.py Adds ContextVar-based bound-session support and AsyncClientSession.bind().
pymongo/asynchronous/mongo_client.py Uses bound session in _ensure_session/_tmp_session and adds _get_bound_session().
test/test_session.py Adds coverage for bound sessions and nested binding (sync).
test/asynchronous/test_session.py Adds coverage for bound sessions and nested binding (async).
doc/changelog.rst Documents the new API in the changelog (currently with placeholders).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +563 to +566
def bind(self) -> ClientSession:
self._bound = True
return self

Copy link

Copilot AI Feb 26, 2026

Choose a reason for hiding this comment

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

bind() mutates session state (self._bound = True) and returns self, which changes the meaning of using the session itself as a context manager. In particular, with client.start_session().bind() as s: (or calling s.bind() earlier and later doing with s:) will no longer end the session on exit, leaking server sessions and breaking the long-standing contract documented in this module. Consider making bind() return a dedicated context manager (separate object) that only sets/resets the bound-session ContextVar, while keeping ClientSession.__enter__/__exit__ semantics unchanged (always ending the session).

Suggested change
def bind(self) -> ClientSession:
self._bound = True
return self
class _BindContext(ContextManager["ClientSession"]):
"""Context manager used by ClientSession.bind().
Temporarily marks the session as bound so that __enter__/__exit__
manage the bound-session ContextVar, and then restores the previous
bound state on exit.
"""
def __init__(self, session: "ClientSession") -> None:
self._session = session
self._prev_bound = session._bound
def __enter__(self) -> "ClientSession":
# Mark the session as bound for the duration of this context and
# reuse ClientSession.__enter__ to set the ContextVar.
self._session._bound = True
return self._session.__enter__()
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional["TracebackType"],
) -> None:
try:
# Delegate to ClientSession.__exit__ to reset the ContextVar
# without ending the session when bound.
self._session.__exit__(exc_type, exc_val, exc_tb)
finally:
# Restore the previous bound state.
self._session._bound = self._prev_bound
def bind(self) -> ContextManager["ClientSession"]:
"""Return a context manager that binds this session to the current context.
Using ``with session.bind():`` will temporarily bind the session to the
bound-session ContextVar without permanently changing the session's
behavior when used as a context manager itself.
"""
return self._BindContext(self)

Copilot uses AI. Check for mistakes.
aclark4life
aclark4life previously approved these changes Mar 2, 2026
Copy link
Contributor

@aclark4life aclark4life left a comment

Choose a reason for hiding this comment

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

LGTM!

self.client_id = client_id


class AsyncBoundSessionContext:
Copy link
Member

Choose a reason for hiding this comment

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

Should this class be private?

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you explain how the changes in 5edd9a0 address this concern (assuming they do) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

AsyncBoundSessionContext is now private since users aren't intended to use it outside of a context manager.

def _get_bound_session(self) -> Optional[AsyncClientSession]:
bound_session = _SESSION.get()
if bound_session:
if bound_session.client_id == id(self):
Copy link
Member

Choose a reason for hiding this comment

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

Could we replace this with session.client is self? Then we can get rid of the _AsyncBoundClientSession class altogether.

Copy link
Contributor

Choose a reason for hiding this comment

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

Same question about 5edd9a0, this issue is addressed in that commit correct (and if so how) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Shane's suggestion was implemented and the _AsyncBoundClientSession removed.

@NoahStapp NoahStapp requested a review from aclark4life March 3, 2026 19:37
@NoahStapp
Copy link
Contributor Author

Added the new end_session=False parameter to ClientSession.bind() to handle each of the following usage patterns:

# Create session outside of a context manager and use bind() multiple times
session = client.start_session()

with session.bind():
    ...

with session.bind():
    ...

# User must explicitly end session
session.end_session()

# Create session and bind it in a single context manager
# Does NOT end the session when s goes out of scope, user needs to call s.end_session() explicitly
with client.start_session().bind() as s:
    ...

s.end_session()

# Create session and bind it in a single context manager
# Ends the session when s goes out of scope
with client.start_session().bind(end_session=True) as s:
    ...

# Create session in a context manager and call bind() multiple times
# Ends the session when s goes out of scope
with client.start_session() as s:
    with s.bind():
        ...
    ...
    with s.bind():
        ...

@ShaneHarvey
Copy link
Member

Is with client.start_session().bind(end_session=True) as s: any better than with client.start_session() as s, s.bind():? I would say no because now there's two ways to do it.

@aclark4life
Copy link
Contributor

Is with client.start_session().bind(end_session=True) as s: any better than with client.start_session() as s, s.bind():? I would say no because now there's two ways to do it.

It may be better since, if they do the same thing, I prefer the former to the latter. It would also never occur to me to do: with client.start_session() as s, s.bind(): and I don't mind if this 2nd way exists to do the same thing.

aclark4life
aclark4life previously approved these changes Mar 3, 2026
@ShaneHarvey
Copy link
Member

Chaining doesn't work because bind() doesn't return a session object. It returns a private context manager. So with client.start_session().bind() as s: is broken.

_SESSION: ContextVar[Optional[ClientSession]] = ContextVar("SESSION", default=None)


class BoundSessionContext:
Copy link
Member

Choose a reason for hiding this comment

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

This should be private too.

@NoahStapp
Copy link
Contributor Author

Chaining doesn't work because bind() doesn't return a session object. It returns a private context manager. So with client.start_session().bind() as s: is broken.

_BoundSessionContext.__enter__ returns a ClientSession, so all approaches work:

with client.start_session().bind() as s:
    ...

with client.start_session() as s:
    with s.bind():
        ...

with client.start_session() as s, s.bind():
    ...

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ShaneHarvey
Copy link
Member

Here's what I mean:

with client.start_session().bind() as s:
    client.t.t.insert_one({}, session=s)  # This will fail because "s" is not a session 

Another problem is that if bind().__exit__ doesn't called end_session() then the session will be leaked:

with client.start_session().bind():
    # ...
# session is leaked here.

This is problematic because it can lead to hitting the session cache size limit on the server.

It also points to a design issue. New APIs should be easy to use correctly and arguably more importantly hard to use incorrectly. So far we've added an api with the first property but not the second. Noah and I discussed in person and decided to make bind().__exit__ default to closing the session. Then at least users need to opt-in to the problematic code and we can warn about it in the docs for that argument:

with client.start_session().bind(end_session=False):  # This mistakenly leaks the session
    # ...
with client.start_session().bind():  # This is correct.
    # ...
with client.start_session() as s, s.bind():  # This is correct.
    # ...
with client.start_session() as s, s.bind(end_session=False):  # This is correct.
    # ...

# This is correct.
with client.start_session() as s:
    with s.bind(end_session=False):
        # ...
    with s.bind(end_session=False):
        # ...

ShaneHarvey
ShaneHarvey previously approved these changes Mar 4, 2026
raise InvalidOperation("Cannot use ended session")

def bind(self, end_session: bool = True) -> _AsyncBoundSessionContext:
"""Bind this session so it is implicitly passed to all database operations within the returned context.
Copy link
Member

Choose a reason for hiding this comment

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

Could you add a short docs explain here? We still do that 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.

What do you mean?

Copy link
Member

Choose a reason for hiding this comment

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

Like a .. code-block:: python example

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.

5 participants