Skip to content

Python: [Bug]: Azure DocumentDB injected clients do not take precedence over connection settings #9954

Closed

Description

Observed Behavior

AzureDocumentDBStore and AzureDocumentDBCollection reject connection strings, client options, and .env options when a PyMongo async client, database, or collection is injected. An injected account-level client also requires database_name explicitly instead of allowing the remaining selector to fall back to AZURE_DOCUMENTDB_DATABASE_NAME.

Affected file: python/packages/azure-documentdb/agent_framework_azure_documentdb/_vector_store.py.

Expected Behavior

The most specific injected SDK object should take precedence over all client-construction inputs. Connection strings, client options, and environment connection settings should not be read or validated when a suitable client/database/collection is present. Any unresolved database or collection selector should then use explicit argument > environment > focused error.

Injected clients remain caller-owned.

Steps to Reproduce

  1. Create a caller-owned AsyncMongoClient.
  2. Pass it to AzureDocumentDBStore with database_name and a connection or .env option.
  3. Observe the conflict error before the injected client is used.

Minimal Reproduction

from unittest.mock import MagicMock
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from agent_framework_azure_documentdb import AzureDocumentDBStore

client = MagicMock(spec=AsyncMongoClient)
AzureDocumentDBStore(
    client=client,
    database_name="vectors",
    connection_string="mongodb://ignored",
)

Error Messages and Stack Traces

ValueError: client cannot be combined with connection settings or client_options.

Package Versions

agent-framework-azure-documentdb: 1.0.0a261030; main at 93c346f

Python Version

Python 3.13.1

Operating System

macOS

Regression

Unknown

Additional Context

Compatibility impact: alpha constructors would stop raising for redundant connection settings. Database-name environment fallback could become available for an injected account client. Type and resource-name validation should remain.

Focused acceptance tests:

  • Injected collection/database/client paths ignore connection strings, client options, and .env values.
  • Remaining database and collection selectors use explicit values before environment values.
  • Invalid ambient connection settings cannot block an injected object.
  • No client factory is called and injected clients remain open.
  • No-injection initialization keeps current validation and ownership.

AI assistance: I used an AI coding assistant to audit and reproduce the behavior.

Acknowledgements

  • I searched existing issues and did not find a duplicate.
  • I personally verified this behavior and the reproduction details are authentic.

Activity

  1. he-yufeng commented on Nov 3, 2026

    @he-yufeng
    Contributor

    I’ll take this one. I’ll cover the injected collection, database, and account-client paths, including selector fallback, bypass of ambient connection settings, and caller-owned cleanup, while keeping the no-injection initialization contract unchanged.

  2. eavanvalkenburg commented on Nov 9, 2026

    @eavanvalkenburg
    MemberAuthor

    /plan Use the existing maintainer-defined injection scope and #9999 implementation rather than creating a parallel fix. Establish the compatibility contract across injected collection, database, and account-client paths: bypass client-construction settings while resolving only genuinely missing resource selectors. Preserve explicit selectors and registered model definitions ahead of environment fallback, multiple-injection/type/name-mismatch errors, caller ownership, and unchanged no-injection behavior. Check that invalid ambient connection settings cannot leak into selector-only resolution or redirect a resolved injected resource. Cover the full injection/selector/cleanup matrix and estimate the complete production-code scope before any new readiness or assignment decision. Planning only; this does not authorize a competing implementation.

  3. github-actions commented on Nov 9, 2026

    @github-actions
    Contributor

    Summary

    Today, passing an injected PyMongo client, database or collection to AzureDocumentDBStore or AzureDocumentDBCollection fails if you also pass a connection string, client options or .env options. An injected account client also requires database_name, and does not fall back to AZURE_DOCUMENTDB_DATABASE_NAME. The expected behavior is that the injected object wins, and only a missing database or collection name is resolved afterwards.

    I checked this against main in _vector_store.py. This is planning only. I did not run anything, and I did not look at #9999's diff. I only note that it is an open PR linked to this issue.

    What I confirmed

    • _create_client (around lines 155-210) raises "database cannot be combined..." or "client cannot be combined..." when settings are present with an injected object. For a client it raises "database_name is required with an injected client." before it reaches any environment lookup.
    • AzureDocumentDBCollection.__init__ (around lines 624-652) has a third, similar rejection for collection=. It also checks that collection_name matches the injected collection.
    • AzureDocumentDBStore.__init__ calls _create_client directly, so one fix there covers the store.
    • The only settings loader is load_settings(AzureDocumentDBSettings, ...). It is reached only on the no-injection path.
    • Existing tests in test_settings.py already check that injection bypasses settings loading and leaves the client open. test_injected_client_rejects_connection_settings pins the current rejection, so it must change.
    • The README says injected objects "bypass settings loading". After this change it should say that only the database selector may still be read.

    Recommendation

    Code change, plus a small README update. This is a real behavior inconsistency in an alpha package, and it is already labeled ready-for-implementation and assigned. I recommend that the change land in the existing #9999 work rather than in a second fix. No sample is needed. The workaround today is to omit the redundant settings and always pass database_name. That is easy to do, but it is inconsistent with the other settings paths.

    Compatibility: constructors that used to raise on redundant settings will stop raising. This is acceptable for alpha and is already stated in the issue. Unchanged: wrong-type errors, collection-name mismatch, no-injection validation and ownership.

    Proposed plan

    The production change is small and confined to the single file _vector_store.py, plus docs. I estimate about two functions, _create_client and the collection branch of AzureDocumentDBCollection.__init__, with no new public API.

    1. Precedence contract (most specific wins): collection > database > client > create from settings. For injected objects, ignore connection_string, client_options, env_file_path and env_file_encoding. Do not read or validate them, and do not call the client factory.

    2. Keep the existing errors:

      • Passing more than one of collection, database and client still raises. That is collection with database or client, and database with client. Today those combinations raise, and the plan should state explicitly that they keep raising.
      • Wrong types still raise TypeError.
      • collection_name that differs from the injected collection still raises.
      • Names are still validated.
    3. Selector-only resolution (client path):

      • Use an explicit database_name first, then AZURE_DOCUMENTDB_DATABASE_NAME (read from the selected .env/environment), then a focused error.
      • Do not read the connection string here. Resolve only the database name, for example with a settings type that has just that field. Otherwise a malformed ambient AZURE_DOCUMENTDB_CONNECTION_STRING could still interfere. Needs a decision: confirm that load_settings can load a subset, or read the one value separately.
      • env_file_path and env_file_encoding should apply only to this selector lookup. They should not be rejected.
    4. Injected database or collection: these are already resolved, so they need no environment lookup.

      • Decision for maintainers: an explicit database_name that conflicts with the injected database's name should raise a mismatch error, like collection_name. The alternative is to keep rejecting it. Either way, ambient environment values must never redirect an injected resource.
      • For AzureDocumentDBCollection, the collection_name and the registered model definition keep priority over environment fallback. Only an unresolved collection name on a client or database path uses the existing model-definition default.
    5. Ownership: injected objects keep owned=False and managed_client=False. aclose() and context exit never close them. Store-created child collections stay shared and never close the account client.

    6. Docs: update the README wording about bypassing settings and the constructor docstrings that say the client "requires database_name". I do not expect changes to the changelog or to the public consumer skills.

    Test matrix (offline, mocks)

    Rows are the injected object: none, client, database or collection. Columns are the settings supplied: none, connection string, client options, .env options, or invalid ambient connection string. Cases to cover:

    • Every injected object ignores a connection string, client options, .env options, and an invalid ambient connection string. AsyncMongoClient is never constructed and load_settings never fails because of those values.
    • The client path resolves the database name by explicit value, then .env/environment, then a clear error. An invalid ambient connection string does not interfere.
    • Injected database or collection with a mismatched database_name or collection_name: mismatch error (the policy chosen in step 4).
    • Multiple-injection errors, wrong types, and invalid names still raise.
    • Injected objects stay open after aclose() and after context exit, for both the store and the collection, including children created through store.get_collection.
    • No-injection paths are unchanged: validation, TLS and retry-write checks, and ownership/closing.
    • Replace test_injected_client_rejects_connection_settings with the new contract.

    Success means these tests pass with the issue's reproduction constructing without error. I have not run any of this.

    Open point

    I only need one maintainer answer: should an explicit database_name that conflicts with an injected database or collection be an error, or be silently ignored? I recommend an error, because it is consistent with the existing collection_name check.

    Generated by Issue Planning for #9954 · copilot · auto · ~24 AIC · ⌖ ~1 AIC · ⊞ 4.8K · ◷

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

pythonUsage: [Issues, PRs], Target: Pythonready-for-implementationMaintainers agree the problem and direction are ready for implementation.

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions