=============== LIBRARY RULES =============== From library maintainers: - Use CacheManager for independent process-local caches; consider SharedCacheManager for repeated reads across trusted same-host workers. Measure latency, CPU and total memory on your workload; sharing adds owner and miss costs. - Import synchronous managers from client_query_cache for pymongo.MongoClient; import asyncio managers from client_query_cache.asynchronous for pymongo.AsyncMongoClient. - Create cached views with manager.get_cached_collection(collection) or manager[database][collection]. Supply collections from the manager's own client; retain views for repeated use. - Use cached views for find_one, find, aggregate, count_documents, estimated_document_count and distinct. Use the original PyMongo collection or .raw for writes, administration and other methods. - Treat find() and aggregate() results as native cursor subclasses, not lists. With asyncio, await single-result reads and aggregate(), but not find(); use async iteration or await cursor.to_list(). - Fully consume cursors successfully to permit cache admission; close abandoned cursors. Started hit cursors retain their snapshot through invalidation, eviction and manager closure; start a new execution for a new lookup. - Do not assume a cached read observes a completed write: change-stream invalidation is asynchronous, with no catch-up barrier or guaranteed delay. Eligible misses use primary, majority reads; this does not make hits current. - Use direct PyMongo reads with suitable sessions and concerns for read-after-write, current authorization or required server execution. Hits skip execution and fresh server errors; direct reads do not refresh cached entries. - Expect ineligible requests, including sessions, incompatible read options, unsafe queries and unavailable streams, to run through PyMongo. Oversized results are returned without caching. Do not treat a successful response as proof of caching. - Reuse a long-lived client and manager within each worker, never per request. Each CacheManager has independent data and streams. Close managers before their caller-owned clients; await asyncio close() or use async with. - Start one SharedCacheServer in the parent and pass only its connection to workers; each worker creates its own client and SharedCacheManager. Do not start a server in each worker lifespan. - Stop shared workers before closing their parent-owned server. Never reuse clients, managers or server handles inherited after fork; create worker clients and managers after process startup. - Construct and use asyncio SharedCacheManager in one running event loop. Enter it with async with or await SharedCacheManager.attach(client, connection) before reading; do not await its constructor. - Check shared-read eligibility: shared caching requires portable keys, standard dict documents, no custom codec registry and simple explicit/default collation; aggregates must stay within one collection. Other requests fall back to PyMongo. - Preserve all query and authorization predicates when using either manager. Never remove tenant filters or change query semantics to obtain cache hits; credential or role changes alone do not invalidate cached documents. - Keep SharedCacheConnection private: never log or persist it. Share only among trusted workers using the same MongoDB deployment, credentials and read visibility; holders can read all configured databases and submit cached values. - Use Linux x86-64 with glibc 2.28+; shared hosts also need Linux 5.1+, memfd sealing and /proc. For caching, use MongoDB 8.0+ replica sets or sharded clusters with collection reads, metadata and database-level changeStream access. - Size memory from measured peaks across workers and the shared owner; BSON budgets do not cap RSS or container memory. Distinguish capacity eviction from freshness: change streams invalidate data, while LRU eviction frees capacity. ### Install with pip Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/getting-started/installation.md Use pip to install the client-query-cache package. ```bash pip install client-query-cache ``` -------------------------------- ### Install client-query-cache via uv Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/README.md Use the uv package manager to add the library to your project. ```bash uv add client-query-cache ``` -------------------------------- ### Asyncio CacheManager implementation Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/getting-started/asyncio.md A complete example showing how to initialize the CacheManager, perform cached reads and writes, and inspect cache hits. ```python import asyncio from pymongo import AsyncMongoClient from client_query_cache.asynchronous import CacheManager async def main() -> None: async with ( AsyncMongoClient("mongodb://localhost:27017") as client, CacheManager(client) as cache_manager, ): collection = client["client_query_cache_tutorial"]["items"] cached_collection = cache_manager.get_cached_collection(collection) await collection.replace_one( {"_id": "example"}, {"_id": "example", "value": 42}, upsert=True ) first = await cached_collection.find_one({"_id": "example"}) repeated = await cached_collection.find_one({"_id": "example"}) print(first, repeated) print("Cache hits:", cache_manager.snapshot().hits) items = await cached_collection.find({"value": 42}).to_list() print(items) asyncio.run(main()) ``` -------------------------------- ### Start local MongoDB replica set Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/getting-started/installation.md Run the local MongoDB replica set using the repository's docker-compose.yaml file. ```console docker compose up -d mongo docker compose run --rm mongo_helper ``` -------------------------------- ### Example event document structure Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/shared-cache.md A sample JSON array showing how to store events from different days in a single collection to optimize namespace usage. ```json [ { "_id": "first-event", "day": "2026-10-17" }, { "_id": "second-event", "day": "2026-10-18" } ] ``` -------------------------------- ### SharedCacheServer constructor Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Starts an owner process for the shared cache. Requires a MongoDB URI and a nonempty tuple of distinct database names. Optional configuration and client options can be provided. ```APIDOC ## SharedCacheServer(mongodb_uri, databases, *, config=SharedCacheConfig(), client_options=None) ### Description Starts an owner process immediately for the shared cache. The databases parameter must be a nonempty tuple of distinct, nonempty database names. The client_options parameter configures the owner's own PyMongo client. ### Parameters - **mongodb_uri** (string) - Required - MongoDB connection URI. - **databases** (tuple of strings) - Required - Nonempty tuple of distinct, nonempty database names. - **config** (SharedCacheConfig) - Optional - Configuration object; defaults to SharedCacheConfig(). - **client_options** (dict) - Optional - Options for the owner's PyMongo client. ### Example ```python from client_query_cache import SharedCacheConfig, SharedCacheServer with SharedCacheServer( mongodb_uri, ("catalogue",), config=SharedCacheConfig(budget_bytes=128 * 1024 * 1024), client_options={"timeoutMS": 5000}, ) as cache_server: connection = cache_server.connection # Pass connection to workers and wait for them to finish within this block. ``` ``` -------------------------------- ### Setup restricted reader role and user in mongosh Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/permission-recovery.md Creates a dedicated database, a custom role 'cacheLabReader' without changeStream privileges, and a user assigned to that role. This setup is intended for a disposable, self-managed MongoDB replica set. ```javascript const lab = db.getSiblingDB("client_query_cache_permission_lab"); lab.products.insertOne({ _id: "book", description: "available directly" }); lab.createRole({ role: "cacheLabReader", privileges: [ { resource: { db: "client_query_cache_permission_lab", collection: "" }, actions: ["find", "listCollections", "listIndexes"], }, ], roles: [], }); lab.createUser({ user: "cacheLabReader", pwd: passwordPrompt(), roles: [{ role: "cacheLabReader", db: "client_query_cache_permission_lab" }], }); ``` -------------------------------- ### Implement SharedCacheServer with ProcessPoolExecutor Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/shared-cache.md Demonstrates the ownership pattern for background workers where the parent process starts the SharedCacheServer and passes the connection to workers. Workers use the SharedCacheManager to access cached data. ```python from concurrent.futures import ProcessPoolExecutor from multiprocessing import get_context from pymongo import MongoClient from client_query_cache import SharedCacheManager, SharedCacheServer def worker(connection): with ( MongoClient("mongodb://localhost:27017", timeoutMS=5000) as client, SharedCacheManager(client, connection) as manager, ): return manager["catalogue"]["products"].find_one({"_id": "book"}) if __name__ == "__main__": with SharedCacheServer( "mongodb://localhost:27017", ("catalogue",), client_options={"timeoutMS": 5000}, ) as cache_server: with ProcessPoolExecutor( max_workers=4, mp_context=get_context("spawn") ) as pool: print(list(pool.map(worker, (cache_server.connection,) * 4))) ``` -------------------------------- ### Synchronous CacheManager implementation Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/getting-started/synchronous.md Initializes a CacheManager with a MongoClient to perform cached reads on a MongoDB collection. The example writes a document, performs repeated reads, and prints the cache hit count. ```python from pymongo import MongoClient from client_query_cache import CacheManager with ( MongoClient("mongodb://localhost:27017") as client, CacheManager(client) as cache_manager, ): collection = client["client_query_cache_tutorial"]["items"] cached_collection = cache_manager.get_cached_collection(collection) collection.replace_one( {"_id": "example"}, {"_id": "example", "value": 42}, upsert=True ) first = cached_collection.find_one({"_id": "example"}) repeated = cached_collection.find_one({"_id": "example"}) print(first, repeated) print("Cache hits:", cache_manager.snapshot().hits) items = list(cached_collection.find({"value": 42})) print(items) ``` -------------------------------- ### find Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a Cursor subclass (synchronous) or AsyncCursor subclass (asyncio). Cache lookup occurs when consumption starts. Construction validates arguments locally and performs no database read or cache lookup. ```APIDOC ## find ### Description Returns a Cursor subclass (synchronous) or AsyncCursor subclass (asyncio). Cache lookup occurs when consumption starts. Construction validates arguments locally and performs no database read or cache lookup. ### Method find ### Parameters No parameters documented. ### Request Example ```python with cached_collection.find({"status": "active"}).sort("name").limit(10) as cursor: for product in cursor: print(product) items = cached_collection.find({"status": "active"}).to_list() ``` ### Response Cursor subclass (synchronous) or AsyncCursor subclass (asyncio) ``` -------------------------------- ### manager.stream_health_snapshot(database_name) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/monitoring.md Reports the health state of the stream for the given database name. Inspection is synchronous and never starts a stream. ```APIDOC ## manager.stream_health_snapshot(database_name) ### Description Reports the health state of the stream for the given database name. Inspection is synchronous for sync and asyncio CacheManager and never starts a stream. ### Method N/A (method call) ### Endpoint N/A (in-memory method) ### Parameters #### Path Parameters - **database_name** (string) - Required - The name of the database to check. ### Response #### Success Response - **health_state** (string) - One of: `not_started`, `connecting`, `healthy`, `reconnecting`, `startup_failed`, or `closed`. - **requested_database_name** (string) - Echoes the name you passed without checking it against MongoDB. #### Response Example ``` { "health_state": "healthy", "requested_database_name": "mydb" } ``` ``` -------------------------------- ### Cache deterministic single-document queries with find_one() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md Deterministic single-document queries, including those with compound filters and collation, can be cached. This example selects the latest active product using explicit string matching and sorting. ```python product = cached_products.find_one( {"status": "active"}, sort=[("updated_at", -1), ("_id", 1)], collation={"locale": "en", "strength": 2}, ) ``` -------------------------------- ### register_cache_metrics Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/monitoring.md Bridges cache statistics into an OpenTelemetry Meter. This function registers instruments against the provided Meter and requires the 'otel' extra to be installed. ```APIDOC ## register_cache_metrics ### Description Registers OpenTelemetry instruments for cache and stream metrics on the provided Meter. This function is part of the client_query_cache.otel module and requires the 'otel' extra to be installed. ### Parameters - **meter** (Meter) - Required - The OpenTelemetry Meter to register instruments with. - **cache_manager** (CacheManager) - Required - The CacheManager instance to monitor. ### Request Example ```python from opentelemetry.sdk.metrics import MeterProvider from client_query_cache.otel import register_cache_metrics provider = MeterProvider() meter = provider.get_meter("your-application") register_cache_metrics(meter, cache_manager) ``` ### Response No return value. Instruments are registered on the provided Meter. ### Notes - Requires the 'otel' extra: pip install client-query-cache[otel] - Only importing client_query_cache.otel requires opentelemetry-api; the base install has no OpenTelemetry dependency. - Configuring MeterProvider, exporters, and collection intervals is the application's responsibility. ``` -------------------------------- ### Run stream cost benchmarks Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/benchmarks/stream-cost.md Execute the stream cost benchmark suite against the runner's disposable replica set. Ensure development prerequisites are met before running. ```console uv run -- python -m benchmarks.stream_cost.run --output-dir benchmark-reports ``` -------------------------------- ### Initialize CacheManager with PyMongo Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/README.md Demonstrates how to wrap a PyMongo collection with CacheManager to enable caching for find operations. ```python from pymongo import MongoClient from client_query_cache import CacheManager with ( MongoClient("mongodb://localhost:27017") as client, CacheManager(client) as cache_manager, ): collection = client["client_query_cache_tutorial"]["items"] cached_collection = cache_manager.get_cached_collection(collection) collection.replace_one( {"_id": "example"}, {"_id": "example", "value": 42}, upsert=True ) cached_collection.find_one({"_id": "example"}) cached_collection.find_one({"_id": "example"}) # Repeated reads can hit the cache. ``` -------------------------------- ### Inspect Cache and Stream State Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Demonstrates how to retrieve snapshots for cache, stream costs, and stream health, as well as active stream cost databases. ```python from client_query_cache import CacheSnapshot, StreamCostSnapshot, StreamHealthSnapshot snapshot: CacheSnapshot = manager.snapshot() stream_cost: StreamCostSnapshot = manager.stream_cost_snapshot("shop") stream_health: StreamHealthSnapshot = manager.stream_health_snapshot("shop") measured_databases = manager.active_stream_cost_databases() ``` -------------------------------- ### Initialize SharedCacheServer Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Initializes the SharedCacheServer with a MongoDB URI, database list, and configuration. The connection object is then available for distribution to workers within the context block. ```python from client_query_cache import SharedCacheConfig, SharedCacheServer with SharedCacheServer( mongodb_uri, ("catalogue",), config=SharedCacheConfig(budget_bytes=128 * 1024 * 1024), client_options={"timeoutMS": 5000}, ) as cache_server: connection = cache_server.connection # Pass connection to workers and wait for them to finish within this block. ``` -------------------------------- ### Clean up exercise resources Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/permission-recovery.md Use these commands in the administrator shell to remove the user, role, and database created during the exercise. ```javascript lab.dropUser("cacheLabReader"); lab.dropRole("cacheLabReader"); lab.dropDatabase(); ``` -------------------------------- ### Run shared cache benchmark with uv Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/benchmarks/shared-cache.md Executes the benchmark workload using a specific wheel artifact and required dependencies. Requires a Docker-compatible runtime and writes results to the specified JSON output path. ```bash uv run --isolated --no-project \ --python 3.14.7 \ --with dist/client_query_cache-0.8.1-cp314-abi3-manylinux_2_28_x86_64.whl \ --with psutil --with testcontainers --with requests --with pyyaml \ python -m benchmarks.public_shared_cache \ --output /tmp/agents/shared-cache-performance.json ``` -------------------------------- ### Constructing a CacheManager Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Initializes a CacheManager by wrapping an existing MongoClient or AsyncMongoClient instance. The manager does not own or close the provided client. ```python from client_query_cache import CacheManager cache_manager = CacheManager(client) ``` -------------------------------- ### Synchronous CachedCollection find usage Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Demonstrates using find with sort and limit in a synchronous context, as well as retrieving results as a list. ```python with cached_collection.find({"status": "active"}).sort("name").limit(10) as cursor: for product in cursor: print(product) items = cached_collection.find({"status": "active"}).to_list() summary = cached_collection.aggregate([{"$match": {"status": "active"}}]).to_list() ``` -------------------------------- ### Observe cache denial and restoration in Python Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/permission-recovery.md This program monitors the cache health and hit status while waiting for the user to grant the necessary 'changeStream' privilege in the database. ```python import os from time import monotonic, sleep from pymongo import MongoClient from client_query_cache import CacheManager, StreamHealthStatus database_name = "client_query_cache_permission_lab" with MongoClient(os.environ["MONGODB_URI"]) as client, CacheManager(client) as manager: cached = manager.get_cached_collection(client[database_name].products) print(cached.find_one({"_id": "book"})) print(manager.stream_health_snapshot(database_name).status) print(manager.snapshot()) input("Grant changeStream in the administrator shell, then press Enter: ") baseline_hits = manager.snapshot().hits deadline = monotonic() + 60 while monotonic() < deadline: document = cached.find_one({"_id": "book"}) health = manager.stream_health_snapshot(database_name).status snapshot = manager.snapshot() if health == StreamHealthStatus.HEALTHY and snapshot.hits > baseline_hits: print(document) print(health) print(snapshot) break sleep(0.1) else: raise SystemExit("No healthy cache hit observed within the exercise deadline") ``` -------------------------------- ### manager.snapshot().bypass_reasons Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/monitoring.md Returns a snapshot of the cache manager's bypass reasons, explaining ordinary bypass events using a fixed vocabulary. ```APIDOC ## manager.snapshot().bypass_reasons ### Description Returns a snapshot of the cache manager's bypass reasons, explaining ordinary bypass events using a fixed vocabulary. ### Method N/A (property access) ### Endpoint N/A (in-memory method) ### Parameters None ### Response #### Success Response - **bypass_reasons** (object) - A mapping of bypass reasons to their meanings. #### Response Example ``` { "session": "The read uses a session.", "read_profile": "The collection's read preference or concern is incompatible with caching.", "unsupported_options": "The read supplies options that cannot be cached.", "unsafe_filter": "The request contains a construct unsafe to cache.", "unsafe_projection": "The request contains a construct unsafe to cache.", "unsafe_pipeline": "The request contains a construct unsafe to cache.", "uncanonicalizable_key": "The request cannot form a stable cache key.", "missing_collection": "The collection does not exist.", "view_collection": "The collection type does not support caching.", "time_series_collection": "The collection type does not support caching.", "metadata_unavailable": "Collection metadata could not be established.", "stream_unavailable": "The database stream is unavailable.", "admission_invalidated": "Stream continuity changed during admission, although the stream is currently available.", "unspecified": "An advanced caller recorded a bypass without a reason." } ``` ``` -------------------------------- ### Register OpenTelemetry metrics Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/monitoring.md Bridge cache statistics into an OpenTelemetry Meter by calling register_cache_metrics. This requires the otel extra and an existing MeterProvider configuration. ```python from opentelemetry.sdk.metrics import MeterProvider from client_query_cache.otel import register_cache_metrics # Configure your application's readers/exporters here. provider = MeterProvider() meter = provider.get_meter("your-application") register_cache_metrics(meter, cache_manager) ``` -------------------------------- ### Initialize SharedCacheManager synchronously Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Use the SharedCacheManager as a context manager to retrieve cached collections and perform queries. ```python from client_query_cache import SharedCacheManager with SharedCacheManager(client, connection) as manager: products = manager.get_cached_collection(client["catalogue"]["products"]) product = products.find_one({"_id": "book"}) ``` -------------------------------- ### Importing cache exceptions Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Import the specific cache exceptions from the client_query_cache package to handle errors during cache operations. ```python from client_query_cache import ( CacheClosedError, CacheConfigurationError, CacheError, UnsupportedCacheRequestError, ) ``` -------------------------------- ### Configure CacheManager with CacheCoreConfig Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Pass a CacheCoreConfig to size a manager's cache. shared_budget_bytes is set to 128 MiB. All numeric fields must be exact built-in integers; invalid values raise CacheConfigurationError at construction. ```python from client_query_cache import CacheCoreConfig, CacheManager cache_manager = CacheManager( client, cache_config=CacheCoreConfig(shared_budget_bytes=128 * 1024 * 1024) ) ``` -------------------------------- ### Import Cache Exceptions Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Import the cache exceptions from the client_query_cache package. These exceptions inherit from CacheError and can be caught together. ```APIDOC ## Import Cache Exceptions ### Description Import the cache exceptions from the `client_query_cache` package. These exceptions inherit from `CacheError` and can be caught together. ### Code ```python from client_query_cache import ( CacheClosedError, CacheConfigurationError, CacheError, UnsupportedCacheRequestError, ) ``` ``` -------------------------------- ### Iterate and materialize cached cursors Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md Use find() and aggregate() to return native cursor subclasses. Iterate them or materialize results explicitly. ```python with cached_products.find({"status": "active"}).sort("name").limit(10) as cursor: for product in cursor: print(product) items = cached_products.find({"status": "active"}).to_list() ``` -------------------------------- ### CacheManager(client, cache_config=CacheCoreConfig(...)) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Constructs a CacheManager with a custom cache configuration. The CacheCoreConfig controls the total cache budget, maximum entry size, namespace tracking, and lag capture windows. ```APIDOC ## CacheManager(client, cache_config=CacheCoreConfig(...)) ### Description Constructs a CacheManager with a custom cache configuration. The CacheCoreConfig controls the total cache budget, maximum entry size, namespace tracking, and lag capture windows. ### Method Constructor ### Parameters #### Constructor Parameters - **client** (MongoClient) - Required - The MongoDB client to cache. - **cache_config** (CacheCoreConfig) - Optional - Configuration for the cache. Defaults to a CacheCoreConfig with default values. ### CacheCoreConfig Fields - **shared_budget_bytes** (int) - Optional - Total BSON-encoded size the manager's cache may hold at once, shared across all databases and collections. Default: 64 MiB. Must be positive. - **max_entry_bytes** (int) - Optional - Largest single cached value (one document, or one find/aggregate/distinct result) the cache accepts. Default: 1 MiB. Must be positive and not exceed shared_budget_bytes. - **max_namespaces** (int) - Optional - Maximum number of database/collection pairs whose cache state the manager tracks at once. Default: 1,024. Must be positive. - **lag_capture_window_config** (LagCaptureWindowConfig) - Optional - Sizes the invalidation-lag sample windows used by stream-cost telemetry. Default: 10 windows of 100 events. Has fields window_count, events_per_window, and min_separation_events. ### Validation - All six numeric fields require exact built-in integers. Booleans, integer subclasses, floats (including NaN and infinities), strings, None, and other types raise CacheConfigurationError at configuration construction, naming the invalid field. - Values are not converted. - Invalid ranges or budget relationships also raise CacheConfigurationError at construction. - shared_budget_bytes and max_entry_bytes must be positive, and max_entry_bytes must not exceed shared_budget_bytes. - max_namespaces must be positive. - Equal budgets are allowed. - lag_capture_window_config: window_count and events_per_window must be positive; min_separation_events must be nonnegative. Default separation is zero. ### Request Example ```python from client_query_cache import CacheCoreConfig, CacheManager cache_manager = CacheManager( client, cache_config=CacheCoreConfig(shared_budget_bytes=128 * 1024 * 1024) ) ``` ### Response No return value. Raises CacheConfigurationError on invalid configuration. ``` -------------------------------- ### aggregate Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a CommandCursor (synchronous) or AsyncCommandCursor (asyncio). Cache lookup and execution occur during the call; a miss or bypass runs the initial command before returning. ```APIDOC ## aggregate ### Description Returns a CommandCursor (synchronous) or AsyncCommandCursor (asyncio). Cache lookup and execution occur during the call; a miss or bypass runs the initial command before returning. ### Method aggregate ### Parameters No parameters documented. ### Request Example ```python summary = cached_collection.aggregate([{"$match": {"status": "active"}}]).to_list() ``` ### Response CommandCursor (synchronous) or AsyncCommandCursor (asyncio) ``` -------------------------------- ### Perform consistent read-after-write with PyMongo Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/consistency.md Use a session with causal consistency enabled and majority read/write concerns to ensure a read observes a preceding write on a replica set. ```python from pymongo.read_concern import ReadConcern from pymongo.write_concern import WriteConcern consistent_products = collection.with_options( read_concern=ReadConcern("majority"), write_concern=WriteConcern(w="majority") ) with client.start_session(causal_consistency=True) as session: consistent_products.update_one( {"_id": "book"}, {"$set": {"price": 12}}, session=session ) current_product = consistent_products.find_one({"_id": "book"}, session=session) ``` -------------------------------- ### Perform asynchronous cached reads Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md With asyncio, await writes and single-result reads. Cursors from find() and aggregate() must be awaited. ```python async with cached_products.find({"status": "active"}) as cursor: async for product in cursor: print(product) items = await cached_products.find({"status": "active"}).to_list() cursor = await cached_products.aggregate([{"$match": {"status": "active"}}]) first_page = await cursor.to_list(length=10) remaining = await cursor.to_list() ``` -------------------------------- ### CachedDatabase and CachedCollection access shorthands Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Shorthand access patterns for obtaining cached views: cache_manager[name] returns a CachedDatabase, database[name] returns a CachedCollection, and attribute access returns cached views. Index access always works, including for collections named like PyMongo methods. ```APIDOC ## CachedDatabase and CachedCollection access shorthands ### Description Shorthand access patterns for obtaining cached views: cache_manager[name] returns a CachedDatabase, database[name] returns a CachedCollection, and attribute access returns cached views. Index access always works, including for collections named like PyMongo methods. ### Usage - **cache_manager[name]** - Returns a CachedDatabase. - **database[name]** - Returns a CachedCollection. - **database.users** - Returns a cached view of the 'users' collection. - **cached_collection.chunks** - Returns a cached view of the 'chunks' sub-collection. - **database["create_collection"]** - Index access works even for collection names that conflict with PyMongo methods. ``` -------------------------------- ### Initialize cached collection and perform read Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md Keep a PyMongo handle for writes and a cached view for repeated reads. Note that cached reads do not wait for write invalidation. ```python collection = client["shop"]["products"] cached_products = cache_manager.get_cached_collection(collection) collection.update_one({"_id": "book"}, {"$set": {"price": 12}}, upsert=True) product = cached_products.find_one({"_id": "book"}) ``` -------------------------------- ### find() with reordered scalar equality predicates Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md Demonstrates that find() can reuse a cached result when ordinary scalar equality predicates appear in a different top-level order. ```APIDOC ## find() with reordered scalar equality predicates ### Description Shows that find() can reuse a cached result when ordinary scalar equality predicates appear in a different top-level order. ### Method find() ### Endpoint cached_products.find(filter, sort) ### Parameters #### Query Parameters - **filter** (dict) - Required - A plain dictionary with exact built-in string field names not starting with '$' and values of None or built-in bool, int, float, or str types. - **sort** (list) - Optional - Sort specification, e.g., [("_id", 1)] ### Request Example ```python products = ( cached_products.find({"status": "active", "region": "eu"}).sort("_id").to_list() ) same_products = ( cached_products.find({"region": "eu", "status": "active"}).sort("_id").to_list() ) ``` ### Response #### Success Response Returns a list of documents matching the filter. #### Response Example ```python # Both calls return the same cached result ``` ``` -------------------------------- ### SharedCacheServer context manager Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Supports synchronous with statement, including for asyncio applications whose workers use async managers. ```APIDOC ## SharedCacheServer as context manager ### Description Supports synchronous with statement, including for asyncio applications whose workers use async managers. ### Example ```python with SharedCacheServer(mongodb_uri, ("catalogue",)) as cache_server: connection = cache_server.connection # Pass connection to workers and wait for them to finish within this block. ``` ``` -------------------------------- ### Retrieve shared cache statistics Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/monitoring.md Use the manager.snapshot() method to obtain cumulative hit, miss, and bypass counts. These statistics are process-local and synchronous. ```python counts = manager.snapshot() # SharedCacheStatistics; synchronous in both APIs. print(counts.hits, counts.misses, counts.bypasses) ``` -------------------------------- ### Asynchronous cached collection usage Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Demonstrates the asynchronous version of cached collection operations, where both write and read calls must be awaited. ```python collection = client["my_database"]["my_collection"] cached_collection = cache_manager.get_cached_collection(collection) await collection.insert_one({"_id": "example", "value": 42}) await cached_collection.find_one({"_id": "example"}) ``` -------------------------------- ### Reuse cached query prefixes Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md A positive find() limit can reuse the prefix of a complete cached result with a larger limit. ```python products = cached_products.find({"status": "active"}).sort("_id").limit(100).to_list() first_page = cached_products.find({"status": "active"}).sort("_id").limit(10).to_list() ``` -------------------------------- ### cache_manager.client Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Property that returns the wrapped PyMongo client, unchanged. ```APIDOC ## cache_manager.client ### Description Returns the wrapped PyMongo client, unchanged. ### Returns - The wrapped PyMongo client. ``` -------------------------------- ### find_one() with sort and collation Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md Demonstrates a deterministic single-document query using find_one() with explicit string matching, sort, and collation. ```APIDOC ## find_one() with sort and collation ### Description Shows a deterministic single-document query using find_one() with explicit string matching, sort, and collation. ### Method find_one() ### Endpoint cached_products.find_one(filter, sort, collation) ### Parameters #### Query Parameters - **filter** (dict) - Required - Filter criteria, e.g., {"status": "active"} - **sort** (list) - Optional - Sort specification, e.g., [("updated_at", -1), ("_id", 1)] - **collation** (dict) - Optional - Collation specification, e.g., {"locale": "en", "strength": 2} ### Request Example ```python product = cached_products.find_one( {"status": "active"}, sort=[("updated_at", -1), ("_id", 1)], collation={"locale": "en", "strength": 2}, ) ``` ### Response #### Success Response Returns a single document matching the filter, or None if no match. #### Response Example ```python # Returns the latest active product ``` ``` -------------------------------- ### manager.active_stream_cost_databases() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a list of measured databases for active stream costs. This method is synchronous and read-only. ```APIDOC ## manager.active_stream_cost_databases() ### Description Returns a list of measured databases for active stream costs. This method is synchronous and read-only. ### Method active_stream_cost_databases() ### Parameters None ### Returns List of database identifiers - The databases with active stream cost measurements. ### Example ```python measured_databases = manager.active_stream_cost_databases() ``` ``` -------------------------------- ### SharedCacheManager (synchronous) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Synchronous context manager for creating a shared cache manager. Provides client, get_cached_collection, manager[database][collection], and close methods. ```APIDOC ## SharedCacheManager (synchronous) ### Description Creates a shared cache manager for caching read operations on collections. Use as a context manager. ### Usage ```python from client_query_cache import SharedCacheManager with SharedCacheManager(client, connection) as manager: products = manager.get_cached_collection(client["catalogue"]["products"]) product = products.find_one({"_id": "book"}) ``` ### Methods - **client** - The client associated with the manager. - **get_cached_collection(collection)** - Returns a SharedCachedCollection view for the given collection. - **manager[database][collection]** - Alternative access to a cached collection view. - **close()** - Closes the manager and its attachments, leaving the client and other workers alive. Repeated closes are safe. ### Notes - The supplied collection must belong to the worker's client; foreign-client collections raise ValueError. - Creating several views is safe; retain one for repeated use. - Closing a manager closes its attachments, leaving the client, other workers and server alive. ``` -------------------------------- ### Synchronous cached collection usage Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Demonstrates creating a cached view of a PyMongo collection and performing both standard writes and cached reads. ```python collection = client["my_database"]["my_collection"] cached_collection = cache_manager.get_cached_collection(collection) collection.insert_one({"_id": "example", "value": 42}) cached_collection.find_one({"_id": "example"}) ``` -------------------------------- ### CacheManager(client, *, cache_config=None, max_await_time_ms=1000) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Constructs a CacheManager that wraps a caller-constructed and caller-owned MongoClient or AsyncMongoClient. The manager never closes or mutates the wrapped client. ```APIDOC ## CacheManager(client, *, cache_config=None, max_await_time_ms=1000) ### Description Constructs a CacheManager that wraps a caller-constructed and caller-owned MongoClient or AsyncMongoClient. The manager never closes or mutates the wrapped client. ### Parameters - **client** (MongoClient or AsyncMongoClient) - Required - The PyMongo client to wrap. - **cache_config** (optional) - Optional - Cache configuration. - **max_await_time_ms** (int) - Optional - Maximum await time in milliseconds. Default is 1000. ### Example ```python from client_query_cache import CacheManager cache_manager = CacheManager(client) ``` ``` -------------------------------- ### SharedCacheServer.restart() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Replaces the shared cache owner process with an empty cache at the same endpoint. Attached workers reconnect lazily and warm again. ```APIDOC ## SharedCacheServer.restart() ### Description Replaces the shared cache owner process with an empty cache at the same endpoint. Attached workers reconnect lazily and warm again. ### Notes - Must be called in the creating parent process. ``` -------------------------------- ### SharedCacheServer.connection Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Provides a picklable SharedCacheConnection carrying private attachment credentials. This connection is passed to workers for shared cache access. ```APIDOC ## SharedCacheServer.connection ### Description Returns a picklable SharedCacheConnection that carries private attachment credentials. Distribute it according to the connection security requirements. ### Returns - **SharedCacheConnection** - A picklable connection object for workers. ``` -------------------------------- ### CacheManager(client, max_await_time_ms=...) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Sets the maximum idle server wait for a change-stream batch on a CacheManager instance. This parameter is available on both synchronous and asyncio CacheManager constructors. ```APIDOC ## CacheManager(client, max_await_time_ms=...) ### Description Sets the maximum idle server wait for a change-stream batch on a CacheManager instance. This parameter is available on both synchronous and asyncio CacheManager constructors. ### Method Constructor ### Parameters #### Constructor Parameters - **client** (MongoClient) - Required - The MongoDB client to cache. - **max_await_time_ms** (int) - Optional - Maximum idle server wait for a change-stream batch in milliseconds. Default: 1,000 ms. Must be an integer from 1 through 2,147,483,647. Booleans and other invalid values raise CacheConfigurationError at construction. ### Request Example ```python cache_manager = CacheManager(client, max_await_time_ms=5_000) ``` ### Response No return value. Raises CacheConfigurationError on invalid value. ### Notes - Each manager keeps its own setting across its databases and reconnects. - This bounds an idle getMore wait. Event delivery and failure detection also depend on the server, network, and client timeouts. - If you set a nonzero PyMongo timeoutMS, it must be greater than max_await_time_ms, as required by the driver's change-stream timeout rules. - Consider socketTimeoutMS and network infrastructure idle timeouts when choosing a value; the manager leaves your client's timeout settings unchanged. ``` -------------------------------- ### SharedCacheManager (asynchronous) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Asynchronous variant of SharedCacheManager for use with asyncio. Enter with async with or use attach, and close with await manager.close(). ```APIDOC ## SharedCacheManager (asynchronous) ### Description Asynchronous shared cache manager for asyncio applications. Must be constructed and used in one running event loop. ### Usage ```python from client_query_cache.asynchronous import SharedCacheManager async with SharedCacheManager(client, connection) as manager: products = manager.get_cached_collection(client["catalogue"]["products"]) product = await products.find_one({"_id": "book"}) ``` Or use attach: ```python manager = await SharedCacheManager.attach(client, connection) ``` ### Methods - **client** - The client associated with the manager. - **get_cached_collection(collection)** - Returns a SharedCachedCollection view for the given collection. - **manager[database][collection]** - Alternative access to a cached collection view. - **close()** - Asynchronously closes the manager. Call before closing its client. Cancellation is propagated after cleanup finishes. ### Notes - Must be constructed and used in one running event loop. - Call await manager.close() before closing its client. - Cancellation is propagated after cleanup finishes. ``` -------------------------------- ### Stop local services Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/getting-started/installation.md Shut down the local Docker Compose services. ```console docker compose down ``` -------------------------------- ### manager.snapshot() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a CacheSnapshot containing cumulative cache counters and capacity observations without document contents or queries. This method is synchronous and read-only. ```APIDOC ## manager.snapshot() ### Description Returns a CacheSnapshot containing cumulative cache counters and capacity observations without document contents or queries. This method is synchronous and read-only. ### Method snapshot() ### Parameters None ### Returns CacheSnapshot - A snapshot of cache counters and capacity observations. ### Example ```python from client_query_cache import CacheSnapshot snapshot: CacheSnapshot = manager.snapshot() ``` ``` -------------------------------- ### manager.snapshot() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Returns an immutable SharedCacheStatistics object synchronously. Use this to retrieve diagnostics about the shared cache. ```APIDOC ## manager.snapshot() ### Description Returns an immutable SharedCacheStatistics object synchronously, providing diagnostics about the shared cache. ### Method snapshot ### Endpoint manager.snapshot() ### Parameters None ### Response #### Success Response - **SharedCacheStatistics** (object) - Immutable statistics object. See shared-manager diagnostics for fields, scope, and telemetry limitations. #### Response Example ``` SharedCacheStatistics ``` ### Errors - **CacheConfigurationError** - Raised for invalid server configuration or failed owner startup. - **CacheClosedError** - Raised for use after close, inherited manager/server use, or incorrect asyncio loop. - **PyMongo errors** - Retained for reads, including driver errors and timeouts. ``` -------------------------------- ### find_one Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a single document or None. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ```APIDOC ## find_one ### Description Returns a single document or None. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ### Method find_one ### Parameters No parameters documented. ### Response Document or None ``` -------------------------------- ### CacheManager context manager Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md CacheManager can be used as a context manager (with / async with), calling close() on exit. ```APIDOC ## CacheManager context manager ### Description CacheManager can be used as a context manager (with / async with), calling close() on exit. ``` -------------------------------- ### distinct Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a list of distinct values. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ```APIDOC ## distinct ### Description Returns a list of distinct values. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ### Method distinct ### Parameters No parameters documented. ### Response list ``` -------------------------------- ### cache_manager.cache_core Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Property that returns the manager's cache storage and bookkeeping object. ```APIDOC ## cache_manager.cache_core ### Description Returns the manager's cache storage and bookkeeping object. ### Returns - The cache storage and bookkeeping object. ``` -------------------------------- ### Set max_await_time_ms on CacheManager Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Set max_await_time_ms on the synchronous or asyncio CacheManager to choose the maximum idle server wait for a change-stream batch. Default is 1,000 ms. Values must be integers from 1 through 2,147,483,647; invalid values raise CacheConfigurationError. ```python cache_manager = CacheManager(client, max_await_time_ms=5_000) ``` -------------------------------- ### Reuse cached results with find() order independence Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/usage/cached-reads.md The find() method can reuse cached results when scalar equality predicates appear in a different top-level order. This applies to plain dictionaries with exact built-in string field names and scalar values. ```python products = ( cached_products.find({"status": "active", "region": "eu"}).sort("_id").to_list() ) same_products = ( cached_products.find({"region": "eu", "status": "active"}).sort("_id").to_list() ) ``` -------------------------------- ### count_documents Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns an integer count. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ```APIDOC ## count_documents ### Description Returns an integer count. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ### Method count_documents ### Parameters No parameters documented. ### Response int ``` -------------------------------- ### estimated_document_count Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns an integer count. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ```APIDOC ## estimated_document_count ### Description Returns an integer count. Cache lookup and execution occur during the call. In asyncio, the call is awaited. ### Method estimated_document_count ### Parameters No parameters documented. ### Response int ``` -------------------------------- ### SharedCacheServer.close() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/shared-cache.md Stops and reaps the shared cache owner process. The close operation is repeat-safe. ```APIDOC ## SharedCacheServer.close() ### Description Stops and reaps the shared cache owner process. The close operation is repeat-safe. ### Notes - Must be called in the creating parent process. - The parent must stop workers before closing the server. ``` -------------------------------- ### manager.stream_cost_snapshot(stream_name) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a StreamCostSnapshot for the specified stream, containing cumulative cost counters and capacity observations. This method is synchronous and read-only. ```APIDOC ## manager.stream_cost_snapshot(stream_name) ### Description Returns a StreamCostSnapshot for the specified stream, containing cumulative cost counters and capacity observations. This method is synchronous and read-only. ### Method stream_cost_snapshot(stream_name) ### Parameters - **stream_name** (string) - Required - The name of the stream to inspect. ### Returns StreamCostSnapshot - A snapshot of stream cost counters and capacity observations. ### Example ```python from client_query_cache import StreamCostSnapshot stream_cost: StreamCostSnapshot = manager.stream_cost_snapshot("shop") ``` ``` -------------------------------- ### Perform a cached find_one read Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Executes a cached find_one operation with specific filters, projections, sorting, and collation settings. ```python cached_collection.find_one( {"status": "active", "region": "Europe"}, {"name": 1, "_id": 0}, sort=[("priority", -1), ("name", 1)], collation={"locale": "en", "strength": 2}, ) ``` -------------------------------- ### find_one Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Performs a single-document read on a cached collection view. Returns a document or None. Supports deterministic filters, projections, sorts, collations, and sessions. ```APIDOC ## find_one ### Description Performs a single-document read on a cached collection view. Returns a document or None. Supports deterministic filters, projections, sorts, collations, and sessions. ### Method READ ### Endpoint cached_collection.find_one(filter=None, projection=None, *, sort=None, collation=None, session=None, **kwargs) ### Parameters #### Query Parameters - **filter** (dict) - Optional - MongoDB query filter. Deterministic filters, including compound predicates, regular expressions, and match-all reads, can be cached. - **projection** (dict) - Optional - Fields to include or exclude in the returned document. - **sort** (sequence) - Optional - Sequence of field/direction pairs, with directions 1 or -1. - **collation** (PyMongo Collation or dict) - Optional - Collation for the query. Omitting uses the collection default. - **session** (PyMongo session) - Optional - Session for the read. - **kwargs** - Optional - Additional keyword options passed directly to PyMongo. ### Request Example ```python cached_collection.find_one( {"status": "active", "region": "Europe"}, {"name": 1, "_id": 0}, sort=[("priority", -1), ("name", 1)], collation={"locale": "en", "strength": 2}, ) ``` ### Response #### Success Response - **document** (dict or None) - The matched document, or None if no match. ### Notes - Use `await` with the same arguments on an asyncio view. - Different filters, projections, sorts, collations, and decoding options retain their own results. - Cache invalidation is eventual; use the PyMongo collection or a session-bound read for immediate observation of preceding writes. - Malformed arguments preserve the driver's errors. ``` -------------------------------- ### cache_manager.close() Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Stops every change stream the manager opened and releases cached data. Does not close the wrapped client. ```APIDOC ## cache_manager.close() ### Description Stops every change stream the manager opened and releases cached data. Does not close the wrapped client. ### Notes - For asyncio, use `await cache_manager.close()`. ``` -------------------------------- ### get_cached_collection(collection) Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/reference/api.md Returns a CachedCollection view for the given PyMongo collection. The view shares the manager's cache and change stream, and its .raw property is the original collection. Raises ValueError if the collection is not from the manager's own client. ```APIDOC ## get_cached_collection(collection) ### Description Returns a CachedCollection view for the given PyMongo collection. The view shares the manager's cache and change stream, and its .raw property is the original collection. Raises ValueError if the collection is not from the manager's own client. ### Method cache_manager.get_cached_collection(collection) ### Parameters - **collection** (PyMongo Collection) - Required - The PyMongo collection to wrap. ### Returns - **CachedCollection** - A cached view of the collection. ### Exceptions - **ValueError** - If the collection is not from the manager's own client. ### Example ```python collection = client["my_database"]["my_collection"] cached_collection = cache_manager.get_cached_collection(collection) ``` ``` -------------------------------- ### Grant changeStream privilege in MongoDB Source: https://github.com/alessio-locatelli/client-query-cache/blob/main/docs/user/operations/permission-recovery.md Use this command in the MongoDB administrator shell to grant the required 'changeStream' action to the 'cacheLabReader' role. ```javascript lab.grantPrivilegesToRole("cacheLabReader", [ { resource: { db: "client_query_cache_permission_lab", collection: "" }, actions: ["changeStream"], }, ]); ```