Metadata-Version: 2.5
Name: kover
Version: 3.4.3
Summary: experimental/modern async MongoDB driver with Pydantic-first API
Project-URL: Homepage, https://github.com/megawattka/kover
Project-URL: Repository, https://github.com/megawattka/kover
Project-URL: Issues, https://github.com/megawattka/kover/issues
Project-URL: Changelog, https://github.com/megawattka/kover/releases
Author-email: megawattka <gunter56741@gmail.com>
License-Expression: Apache-2.0 AND CC-BY-4.0
License-File: LICENSE
License-File: NOTICE
Keywords: async,async-mongodb,asynchronous-database,asyncio,bson,geojson,gridfs,mongodb,mongodb-driver,mongodb-odm,motor-alternative,pydantic-mongodb,python-mongodb
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: Pydantic
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Database :: Database Engines/Servers
Classifier: Topic :: Internet
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: dnspython>=2.7.0
Requires-Dist: elune>=0.5.0
Requires-Dist: pydantic>=2.14.3
Provides-Extra: snappy
Requires-Dist: python-snappy>=0.7.3; extra == 'snappy'
Provides-Extra: zstd
Requires-Dist: zstd>=1.5.7.2; extra == 'zstd'
Description-Content-Type: text/markdown

<h1 align="center">
  <img src="assets/kover-logo.svg" alt="Kover" width="560">
</h1>

<p align="center">
  <a href="https://github.com/megawattka/kover/actions/workflows/actions.yml"><img src="https://img.shields.io/github/actions/workflow/status/megawattka/kover/actions.yml?label=build" alt="Build status"></a>
  <a href="#test-coverage"><img src="https://img.shields.io/badge/coverage-90.9%25-brightgreen" alt="Line coverage snapshot: 90.9%"></a>
  <a href="LICENSE"><img src="https://img.shields.io/github/license/megawattka/kover" alt="License"></a>
  <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.12%2B-blue" alt="Python 3.12 or newer"></a>
  <a href="https://pypi.org/project/kover/"><img src="https://img.shields.io/pypi/v/kover" alt="PyPI version"></a>
  <a href="https://peps.python.org/pep-0561/"><img src="https://img.shields.io/badge/typing-py.typed-blue" alt="Typed package"></a>
</p>

<p align="center">
  <strong>Async MongoDB driver for Python with first-class Pydantic support.</strong><br>
  Save, validate, find, update, and delete data with typed models or dictionaries.
</p>

For example, define a `User` model, save a user to the database, and read it
back as a `User` object with validated fields and editor autocomplete.

Use it for async applications such as a FastAPI backend storing users,
products, or messages. It requires Python **3.12+** and Pydantic **v2**.

### Where does Kover fit?

```text
Your Python application (for example, a FastAPI backend)
    → Kover (validates models and sends database requests)
    → MongoDB (stores your data)
```

- **A MongoDB driver:** connects your application to MongoDB and runs database
  operations asynchronously with `await`. No PyMongo or Motor dependency.
- **Pydantic integration:** define the shape of your data with Python classes,
  validate it, and read database results back as model instances. Plain
  dictionaries work too.
- **Optional database-side validation:** generate MongoDB validation rules
  from your models so the database can reject invalid documents too.

Kover is a Python library, **not a database or a web framework**. You still
need a running MongoDB server, locally or hosted. It has its own API; it is
not a drop-in replacement for PyMongo or Motor.

Want to see it in an API? See the
[complete FastAPI CRUD application](https://github.com/megawattka/kover-fastapi-crud).

## Contents

- [Capabilities and requirements](#capabilities-and-requirements)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Connections and routing](#connections-and-routing)
- [SDAM and server monitoring](#sdam-and-server-monitoring)
- [Typed documents and BSON](#typed-documents-and-bson)
- [MongoDB schema validation](#mongodb-schema-validation)
- [CRUD and cursors](#crud-and-cursors)
- [Bulk writes](#bulk-writes)
- [Sessions and transactions](#sessions-and-transactions)
- [GridFS](#gridfs)
- [Errors](#errors)
- [Development](#development)
- [Documentation and examples](#documentation-and-examples)

## Capabilities and requirements

Kover talks directly to MongoDB using `asyncio` streams and MongoDB's
`OP_MSG` / `OP_COMPRESSED` wire protocol, without thread-pool wrappers.

- Native asynchronous clients, per-server connection pools, and lazy cursors.
- Live discovery and monitoring (SDAM) for standalone servers, replica sets,
  and sharded deployments.
- All five read preference modes, ordered tag sets, max staleness, and latency windows.
- Pydantic `Document` models and strict MongoDB `$jsonSchema` generation.
- CRUD, aggregation, indexes, database/user administration, and GridFS.
- Logical sessions and explicit multi-document transactions.
- SCRAM-SHA-256 / SCRAM-SHA-1 authentication, TLS, and negotiated compression.

Requires Python **3.12+** and a reachable MongoDB deployment. Transactions need
a replica set or sharded cluster; server-level `bulkWrite` needs MongoDB
**8.0+**. Check MongoDB's version requirements for other commands you use.

Runtime dependencies:

| Dependency | Minimum version |
| --- | --- |
| `elune` | `0.5.0` |
| `dnspython` | `2.7.0` |
| `pydantic` | `2.14.3` |

Kover uses [Elune](https://github.com/megawattka/elune) for BSON serialization.

## Installation

Install Kover using pip:

```bash
pip install kover
```

Or using uv:

```bash
uv add kover
# Optional Snappy and Zstandard compression:
uv add "kover[snappy,zstd]"
```

## Quick start

With MongoDB running at `127.0.0.1:27017`, save this as `main.py` and run
`python main.py`. This example defines a user, saves it, and reads it back:

```python
import asyncio

from pydantic import Field

from kover import Document, from_uri


class User(Document):
    name: str
    age: int = Field(ge=0)


async def main() -> None:
    async with await from_uri("mongodb://127.0.0.1:27017/") as client:
        # .get_database and .get_collection are also exists
        users = client.demo.users

        # Validate the data with Pydantic, then save it to MongoDB.
        user = User(name="Maksim", age=21)
        user_id = await users.insert_one(user)

        # Read it back as a User object rather than a dictionary.
        user = await users.find_one({"_id": user_id}, cls=User)
        if user is not None:
            print(user.name, user.age)  # Maksim 21


if __name__ == "__main__":
    asyncio.run(main())
```

`User(name="Maksim", age=-1)` raises a Pydantic validation error before any
database request. `cls=User` also validates documents when reading them back.
To enforce rules inside MongoDB itself, see
[MongoDB schema validation](#mongodb-schema-validation).

You can also pass dictionaries to `insert_one()` and omit `cls` when querying
to receive dictionaries instead. Each run of this example inserts a new user.

`from_uri()` and `make_client()` are **module-level factory functions** returning
a `Kover` client. They are not methods on the `Kover` class. Factories perform
initial server selection and start SDAM monitoring; application connections are
opened lazily in per-server pools.

The remaining asynchronous snippets belong inside an async function. Unless a
snippet creates its own client, it assumes an open `client` and reuses models
and collection handles introduced earlier. Close clients with `async with`
or `await client.close()` when finished.

## Connections and routing

### Explicit configuration

```python
from kover import AuthCredentials, make_client

credentials = AuthCredentials.from_environ()
client = await make_client(
    host="127.0.0.1",
    port=27017,
    credentials=credentials,
    tls=False,
    compression=["zlib"],
    max_pool_size=50,
)
async with client:
    await client.admin.ping()
```

`AuthCredentials.from_environ()` reads `MONGO_USER`, `MONGO_PASSWORD`, and
optional `MONGO_AUTH_DB` (default `admin`). It returns `None` if neither
credential is set and raises `CredentialsException` if only one is provided.
URI credentials use `authSource`, then the URI database, then `admin`.
Percent-encode reserved characters in URI usernames and passwords.

URI configuration supports TLS and compressor negotiation, for example
`mongodb://user:pass@host/demo?authSource=admin&tls=true&compressors=zlib`.
Do not hardcode production secrets. Authentication selects SCRAM-SHA-256 or
SCRAM-SHA-1 from the mechanisms advertised by `hello`.

### Discovery and timeouts

URI seeds are probed concurrently; discovery follows replica set members
advertised by `hello`. Use hostnames reachable as advertised in the replica
set configuration, not just reachable seed aliases.

| URI option | `make_client()` argument | Default |
| --- | --- | --- |
| `replicaSet` | `replica_set` | No expected set name |
| `directConnection` | `direct_connection` | `False` |
| `serverSelectionTimeoutMS` | `server_selection_timeout` | 30 seconds |
| `connectTimeoutMS` | `connect_timeout` | 10 seconds |
| `localThresholdMS` | `local_threshold` | 0.015 seconds |
| `heartbeatFrequencyMS` | `heartbeat_frequency` | 10 seconds; minimum 500 ms |
| `serverMonitoringMode` | `server_monitoring_mode` | `"auto"` (`"poll"` or `"stream"`) |
| `maxPoolSize` | `max_pool_size` | 100 connections per server |

URI durations in this table use milliseconds; Python arguments use seconds.
`connect_timeout` limits connection setup, including the handshake and
authentication. `connect_timeout=None` (`connectTimeoutMS=0`) disables the
per-connection setup limit for the application pool; monitors use a 10-second
base timeout. Server selection and explicit operation deadlines still apply.

`server_selection_timeout` limits selection, not command execution. Neither
setting is a socket timeout for commands on established connections.
`client.command()` and `Database.command()` accept an absolute `deadline`
measured by the event-loop clock.

### Read preferences

```python
from kover import ReadPreference, from_uri

client = await from_uri(
    "mongodb://seed1:27017,seed2:27017/shop?replicaSet=rs0"
    "&readPreference=secondaryPreferred"
    "&readPreferenceTags=region:east"
    "&readPreferenceTags="
    "&maxStalenessSeconds=120"
    "&localThresholdMS=15",
)
async with client:
    orders = client.shop.orders
    cursor = orders.find({}).read_preference(ReadPreference("nearest"))
    documents = await cursor.to_list()
    reply = await client.command(
        {"count": "orders"},
        db_name="shop",
        read_preference=ReadPreference("primary"),
    )
```

Modes are `primary` (default), `primaryPreferred`, `secondary`,
`secondaryPreferred`, and `nearest`. Ordered tag sets are tried after staleness
filtering; `{}` is a catch-all. Max staleness is `-1` (disabled) or an integer
of at least 90 seconds. `primary` rejects nonempty tags and enabled staleness.
Tags/staleness do not constrain a preferred mode's primary fallback.

Eligible reads use the effective read preference; writes, unknown/admin
commands, and aggregations containing `$out` / `$merge` use primary routing.
Configure cursor overrides before execution. `getMore` and `killCursors`
retain server affinity, not socket affinity. Transactions require primary
reads and pin a server address, never a connection.

`directConnection=true` requires one non-SRV seed and keeps operations on it,
even if it is a secondary. Writes are not redirected; direct mode does not
make secondary transactions valid.

## SDAM and server monitoring

Kover starts a background monitor for each seed during initial server selection
and follows replica-set membership changes reported by `hello`. Heartbeats use
dedicated connections, so they don't compete with application operations for
pool capacity. When a heartbeat fails, the server is marked `Unknown` and
monitored for recovery. Topology changes wake waiting selectors, so a later
operation can use a new primary without recreating the client.

The default mode, `"auto"`, prefers streaming `hello` when the server reports
`topologyVersion` and uses polling in detected FaaS environments. Use `"poll"`
to force polling or `"stream"` to prefer streaming explicitly:

```python
from kover import make_client


client = await make_client(
    host="db1",
    heartbeat_frequency=5.0,
    server_monitoring_mode="stream",
)
async with client:
    await client.admin.ping()
```

The equivalent URI options are:

```text
mongodb://db1:27017/?heartbeatFrequencyMS=5000&serverMonitoringMode=stream
```

`"stream"` falls back to polling if a server doesn't advertise
`topologyVersion`. Closing the client stops monitoring before closing the
application pools. See the [SDAM guide](docs/sdam.md) for timeout and pool
retirement details.

**What SDAM doesn't do:** Kover does not retry or replay failed commands. A
command can still fail during an election, and a transaction or cursor pinned
to an address does not move to another server. Load-balanced mode and custom
TLS certificate options are not supported.

## Typed documents and BSON

`Document` extends Pydantic's `BaseModel` with `extra="forbid"`,
`use_enum_values=True`, and `serialize_by_alias=True`. MongoDB's `_id` is a
regular model field named `object_id`, with alias `_id` and default `None`.
`model_dump()` uses field aliases and omits `_id` when its value is `None`.

```python
from uuid import UUID, uuid4

from pydantic import Field

from kover import Document


class User(Document):
    username: str = Field(min_length=3, max_length=32)
    age: int = Field(ge=18)
    external_id: UUID = Field(default_factory=uuid4, alias="externalId")
```

Native UUIDs require an explicit BSON representation. Use this client for the
`User` schema and CRUD examples below:

```python
from elune import CodecOptions, UuidRepresentation

from kover import from_uri

client = await from_uri(
    "mongodb://127.0.0.1:27017/",
    codec_options=CodecOptions(  # or via url parameter
        uuid_representation=UuidRepresentation.STANDARD,
    ),
)
users = client.demo.users
```

`make_client()` accepts the same `codec_options=` argument. `STANDARD` encodes
UUIDs as binary subtype 4 and decodes them back to `UUID`. The default
`UNSPECIFIED` representation rejects native UUID encoding. Keep this client
open for the following examples and close it when done.

| API | Purpose |
| --- | --- |
| `doc.model_dump()` | Python-mode dump using field aliases, including `_id` when set |
| `doc.model_dump(exclude={"object_id"})` | Dump without `_id`; exclusion uses the Python field name |
| `Model.model_validate(payload)` | Validate a MongoDB document, including its `_id` |
| `doc.object_id` / `doc.object_id = value` | Read or assign the document ID |
| `Model.model_mongodb_schema()` | Generate a `{"$jsonSchema": ...}` validator |

```python
from elune import ObjectId

user = User(username="alice", age=27)
assert user.object_id is None
assert "_id" not in user.model_dump()

identifier = ObjectId()
stored = User.model_validate({"_id": identifier, **user.model_dump()})
assert stored.object_id == identifier
assert stored.model_dump()["_id"] == identifier
```

Insert operations do not assign generated IDs back to the input model; assign
`user.object_id = await users.insert_one(user)` if needed. Field names are not
automatically converted to camelCase: declare aliases explicitly, as with
`externalId` above.
See [documents and serialization](docs/documents.md) for details.

Use Python-mode dumps for BSON, not `model_dump(mode="json")`. Elune's native
Pydantic integration preserves BSON instances in Python mode.
Kover does not globally patch Elune's classes or `uuid.UUID`.

### Decimal values

Schema generation is not value conversion. A `decimal.Decimal` annotation
produces a `decimal` schema, but `model_dump()` retains the Python `Decimal`;
it needs a codec or explicit conversion for BSON encoding.

For domain models using `Decimal`, prefer the `DecimalCodec` example in the
[Elune README](https://github.com/megawattka/elune#custom-codecs) over manual
conversion or model serializers. Define that codec in your application and
register it with `CodecOptions(type_registry=TypeRegistry([DecimalCodec()]))`
(`CodecOptions` and `TypeRegistry` are imported from `elune.codec_options`).
Pass these options as `codec_options=` to `from_uri()` or `make_client()`;
if you also use UUIDs, include their representation in the same options.
The codec converts `Decimal` to BSON `Decimal128` on writes and back to
`Decimal` on reads, including values in nested documents. Values must still
fit the precision and range of Decimal128. `DecimalCodec` is an example to
define, not a built-in class to import.

Alternatively, use `elune.Decimal128` directly for stored values:

```python
from decimal import Decimal

from elune import Decimal128

from kover import Document


class Product(Document):
    price: Decimal128


product = Product(price=Decimal128(Decimal("19.99")))
payload = product.model_dump()
```

## MongoDB schema validation

```python
from kover import ValidationLevel

users = await client.demo.users.create_if_not_exists()
await users.set_validator(
    User.model_mongodb_schema(),
    level=ValidationLevel.STRICT,
)
user = User(username="alice", age=27)
alice_id = await users.insert_one(user)
```

The generator resolves references, normalizes JSON Schema, maps BSON types,
and checks MongoDB compatibility without mutating the input schemas.
Unsupported constraints raise `SchemaGenerationException`; there is no
permissive mode that silently removes validation rules.

The root `_id` is required and has `bsonType: "objectId"`, without a `null`
branch. `None` is only an application-side placeholder for an unset ID and is
excluded from dumps. Nested `Document` models also declare `_id`, but it is
optional in their schemas; plain Pydantic models do not inherit this field.

Examples of unsupported constraints include recursive/external references,
email/IP `format`, discriminators, constrained binary lengths, UUID versions,
datetime bounds/timezone constraints, and decimal digit/scale limits.
Custom Python validators are not translated into server-side rules.
Defaults are applied by Pydantic, not MongoDB; `default` annotations are omitted
from the server validator. MongoDB cannot enforce binary subtypes or UUID
contents through these schemas.

## CRUD and cursors

```python
from kover import Delete, Update

await users.insert_many(
    [
        User(username="charlie", age=31),
        User(username="dana", age=24),
    ]
)
user: User | None = await users.find_one({"username": "charlie"}, cls=User)

cursor = (
    users.find({"age": {"$gte": 21}}, cls=User)
    .sort({"age": -1})
    .limit(50)
    .batch_size(25)
)
async with cursor:
    async for item in cursor:
        print(item.object_id, item.username)

all_users: list[User] = await users.find({}, cls=User).to_list()
await users.update(Update({"username": "charlie"}, {"$set": {"age": 32}}))
deleted = await users.delete(Delete({"username": "dana"}, limit=1))
```

Without `cls=`, queries return dictionaries. `insert_one()` returns an ID;
`insert_many()` returns a list of IDs. `update(*updates)` and `delete(*deletes)`
accept operation models as positional arguments. Use update operators such as
`$set` / `$inc`; deletion uses `limit=1` for one match or `limit=0` for all.

Cursors are lazy and support `sort`, `skip`, `limit`, `batch_size`, `projection`,
`hint`, `comment`, and `collation`. A projection used with `cls=Model` must retain
the fields required to validate that model. A cursor cannot be read concurrently
across tasks. Use `async with cursor:` when iteration may stop early to clean
up the server cursor. `to_list()` consumes remaining results; `first()` raises
`StopAsyncIteration` if empty. Close the cursor if you only consume its first item.

```python
group_by_age = [{"$group": {"_id": "$age", "count": {"$sum": 1}}}]
stats = await users.aggregate(group_by_age).to_list()

adults = [{"$match": {"age": {"$gte": 18}}}]
plan = await users.aggregate(adults, explain=True).command_result()
```

Aggregation returns a lazy cursor. For commands returning a document rather
than a cursor, such as aggregation explain, use `command_result()`.
Collection helpers also cover index management, collection options, and validators.

## Bulk writes

`BulkWriteBuilder` targets one or more `database.collection` namespaces using
MongoDB 8.0+'s server-level `bulkWrite` command. Execution and result fetching
are lazy; result cursors can require `getMore` round trips.

```python
from kover import BulkWriteBuilder, Delete, Update

builder = BulkWriteBuilder(ordered=True, errors_only=False)
builder.add_insert([{"sku": "A-1", "quantity": 5}], ns="demo.inventory")
builder.add_update(
    Update({"sku": "A-1"}, {"$set": {"quantity": 10}}),
    ns="demo.inventory",
)
builder.add_delete(Delete({"sku": "obsolete"}, limit=1), ns="demo.inventory")
results = await client.bulk_write(builder.build()).to_list()
```

## Sessions and transactions

Sessions and transactions are not context managers. Start transactions
synchronously; await commit/abort and explicitly end sessions.

```python
orders = await client.demo.orders.create_if_not_exists()
session = await client.start_session()
try:
    session.start_transaction()
    await orders.insert_one({"status": "created"}, session=session)
    await orders.insert_one({"status": "queued"}, session=session)
    await session.commit_transaction()
finally:
    try:
        await session.close()
    finally:
        await client.end_sessions([session])
```

- Pass the same session to every participating operation; it must belong to the same client.
- Reads require an effective `ReadPreference("primary")`. Override transaction read cursors if the client default is non-primary.
- `start_transaction(options=...)` stores options locally but does not apply them to commands.
- Empty transactions commit/abort locally without sending a transaction command.
- `session.close()` aborts an unfinished transaction and clears its server pin; it does not replace `end_sessions()`.
- There is no automatic transaction retry wrapper. Inspect `OperationFailure.is_transient_transaction_error` and `.is_unknown_commit_result` for application-controlled retries.
- An unknown commit result retains the transaction number and server pin for explicit commit retry. The cleanup example above does not implement retries.

See [Transactions](docs/transactions.md) before implementing production retry logic.

## GridFS

GridFS stores files as chunks, allowing files larger than MongoDB's 16 MiB
document limit. Uploads and downloads can both stream without assembling a
complete file in memory.

```python
from kover import GridFS

fs = await GridFS(client.get_database("files")).indexed()
async with fs.open_upload_stream("hello.txt") as upload:
    await upload.write(b"Hello from ")
    await upload.write(b"GridFS!")

file_doc, download = await fs.open_download_stream(
    upload.file_id, chunk_size=64 * 1024,
)
async with download:
    async for chunk in download:
        print(chunk)
```

`await fs.put(source)` accepts an async iterable of `bytes`, `pathlib.Path`,
binary or text file objects, and in-memory `bytes` or `str`. Local files are
read in bounded blocks in a worker thread. The driver writes bounded batches
and only publishes the file document after the last batch. Use small input
blocks when producing an async source to keep its own memory use bounded.

An upload stream publishes on successful exit from `async with` or `close()`.
Call `await upload.abort()` to discard it. Source errors and exceptions in the
upload context also abort the upload. Failed MongoDB writes can leave orphaned
chunks, as specified by GridFS.

`open_download_stream(chunk_size=...)` sets the output block size in bytes.
The last block may be shorter. Without it, the stream yields the chunks as
stored in MongoDB. Downloads check stored chunk order and sizes.
SHA-1 is stored in metadata by default
and checked at the end of a complete download when present. Leaving the
download context early closes the cursor without checking the full hash.
For small files, `get_by_file_id()` and `get_by_filename()` still return the
complete data as a `BytesIO` buffer.

## Errors

- `OperationFailure`: MongoDB command/write failure, with `.code`, `.message`, `.code_name`, `.details`, `.err_info`, and `.error_labels`. Server error codes map to subclasses such as `DuplicateKey`.
- `ServerSelectionError`: no suitable server before the selection deadline, with per-server diagnostics.
- `PoolTimeoutError`: checkout, connection setup, or selection-lock deadline exceeded. `PoolClosedError` / `PoolPausedError` describe unavailable pools.
- `NetworkError` / `ProtocolError`: failed socket exchange or invalid server wire reply. Initial connection setup may also propagate `OSError`.
- `CredentialsException`: incomplete environment credentials.
- `SchemaGenerationException`: unsupported schema or constraint. Invalid model data raises Pydantic `ValidationError`.
- `GridFSFileNotFound` / `IncorrectGridFSData`: missing file, unsupported upload payload, or invalid download chunk. A checksum mismatch raises `RuntimeError`.
- `ValueError` / `TypeError`: invalid configuration, session ownership, or operation use. BSON encoding errors are local errors, not MongoDB command failures.

For raw operations use `await client.command(document, db_name="demo")` or
`await client.demo.command(document)`. There is no `client.request()` API.

## Development

```bash
uv sync --dev
uv run pytest tests/unit tests/functional -q
KOVER_RUN_INTEGRATION=0 uv run pytest tests -q
uv run ruff check kover tests examples
uv run pyright kover tests examples
uv run python -m compileall -q kover tests examples
git diff --check
```

Unit tests include local TCP protocol tests but do not require MongoDB.
Integration tests are opt-in:

```bash
KOVER_RUN_INTEGRATION=1 \
  MONGO_HOST=127.0.0.1 \
  MONGO_PORT=27017 \
  uv run pytest tests/integration -v
```

Optional credentials use `MONGO_USER`, `MONGO_PASSWORD`, and `MONGO_AUTH_DB`.
The current test suite does not consume `MONGODB_URI`. Use a deployment
supporting the tested features, including transactions and MongoDB 8.0+ bulk writes.
To run against a sharded deployment, point `MONGO_HOST` and `MONGO_PORT`
at a `mongos` router on a disposable cluster.

### Test coverage

The badge is a snapshot of **90.9% line coverage** for `kover` at `e2c16b3`,
measured with the unit and functional suites and the GridFS integration tests.
With MongoDB running, reproduce the measurement with:

```bash
KOVER_RUN_INTEGRATION=1 uv run --with coverage python -m coverage run \
  --source=kover -m pytest tests/unit tests/functional \
  tests/integration/test_gridfs.py -q
uv run --with coverage python -m coverage report --precision=1
```

## Documentation and examples

- [Architecture](docs/architecture.md)
- [Documents, IDs, serialization, and schema validation](docs/documents.md)
- [GeoJSON models, geospatial indexes, and queries](docs/geo_json.md)
- [Connections, authentication, pools, and deadlines](docs/connections.md)
- [SDAM and server monitoring](docs/sdam.md)
- [Read preferences and routing limits](docs/read_preferences.md)
- [Transactions and session lifecycle](docs/transactions.md)
- [Development and integration configuration](docs/development.md)
- [Runnable examples](examples/): schemas, CRUD, bulk writes, transactions, read preferences, and GridFS.

Bug reports and contributions are welcome via [GitHub Issues](https://github.com/megawattka/kover/issues)
and pull requests. Please follow the [Code of Conduct](CODE_OF_CONDUCT.md).

## License

Kover is licensed under the [Apache License 2.0](LICENSE).
Copyright (c) 2024–present megawattka.

The [Code of Conduct](CODE_OF_CONDUCT.md) is separately licensed under
[Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/).