diff -pruN 1.30.4-1/.clang-format 2.0.2-1/.clang-format
--- 1.30.4-1/.clang-format	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.clang-format	2025-06-19 15:42:22.000000000 +0000
@@ -53,6 +53,9 @@ AlwaysBreakBeforeMultilineStrings: false
 AlwaysBreakTemplateDeclarations: MultiLine
 AttributeMacros:
   - __capability
+  - BSON_GNUC_WARN_UNUSED_RESULT
+  - BSON_DEPRECATED
+  - BSON_DEPRECATED_FOR
 BinPackArguments: false
 BinPackParameters: false
 BitFieldColonSpacing: Both
@@ -102,7 +105,12 @@ ForEachMacros:
   - foreach
   - Q_FOREACH
   - BOOST_FOREACH
+  - mlib_foreach_irange
+  - mlib_foreach_urange
+  - mlib_foreach
+  - mlib_foreach_arr
 IfMacros:
+  - mlib_assert_aborts
   - KJ_IF_MAYBE
 IncludeBlocks:   Preserve
 IncludeCategories:
diff -pruN 1.30.4-1/.evergreen/benchmark.yml 2.0.2-1/.evergreen/benchmark.yml
--- 1.30.4-1/.evergreen/benchmark.yml	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/benchmark.yml	2025-06-19 15:42:22.000000000 +0000
@@ -35,7 +35,7 @@ variables:
           set -o errexit
           set -o verbose
 
-          cmake -DENABLE_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=mongoc -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF . && make -j8 && make install
+          cmake -DENABLE_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=mongoc . && make -j8 && make install
           git clone https://github.com/mongodb/mongo-c-driver-performance.git
           cd mongo-c-driver-performance
           cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=../mongoc . && make -j8
diff -pruN 1.30.4-1/.evergreen/config_generator/components/abi_compliance_check.py 2.0.2-1/.evergreen/config_generator/components/abi_compliance_check.py
--- 1.30.4-1/.evergreen/config_generator/components/abi_compliance_check.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/abi_compliance_check.py	2025-06-19 15:42:22.000000000 +0000
@@ -30,8 +30,8 @@ class CheckABICompliance(Function):
             aws_secret='${aws_secret}',
             bucket='mciuploads',
             content_type='text/html',
-            display_name='ABI Report:',
-            local_files_include_filter='mongoc/abi-compliance/compat_reports/**/*.html',
+            display_name='ABI Compliance Check: ',
+            local_files_include_filter='abi-compliance/compat_reports/**/compat_report.html',
             permissions='public-read',
             remote_file='mongo-c-driver/${branch_name}/${revision}/${version_id}/${build_id}/${task_id}/${execution}/abi-compliance-check/',
         ),
diff -pruN 1.30.4-1/.evergreen/config_generator/components/c_std_compile.py 2.0.2-1/.evergreen/config_generator/components/c_std_compile.py
--- 1.30.4-1/.evergreen/config_generator/components/c_std_compile.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/c_std_compile.py	2025-06-19 15:42:22.000000000 +0000
@@ -6,7 +6,7 @@ from config_generator.components.funcs.f
 
 from config_generator.etc.distros import find_large_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 from config_generator.etc.function import Function
 from config_generator.etc.utils import bash_exec
 
@@ -17,14 +17,31 @@ TAG = 'std-matrix'
 # pylint: disable=line-too-long
 # fmt: off
 MATRIX = [
-    ('debian92',          'clang',     None,   [11,   ]),
-    ('debian10',          'clang',     None,   [11,   ]),
-    ('debian10',          'gcc',       None,   [11, 17]),
-    ('debian11',          'clang',     None,   [11,   ]),
-    ('debian11',          'gcc',       None,   [11, 17]),
-    ('ubuntu2004',        'clang',     None,   [11,   ]),
-    ('ubuntu2004',        'gcc',       None,   [11,   ]),
-    ('windows-vsCurrent', 'vs2017x64', None,   [11, 17]),
+    ('rhel80',     'clang',    None, [99, 11, 17,   ]), # Clang 7.0
+    ('ubuntu2004', 'clang-10', None, [99, 11, 17, 23]), # Clang 10.0 (max: C2x)
+    ('rhel84',     'clang',    None, [99, 11, 17, 23]), # Clang 11.0 (max: C2x)
+    ('ubuntu2204', 'clang-12', None, [99, 11, 17, 23]), # Clang 12.0 (max: C2x)
+    ('rhel90',     'clang',    None, [99, 11, 17, 23]), # Clang 13.0 (max: C2x)
+    ('rhel91',     'clang',    None, [99, 11, 17, 23]), # Clang 14.0 (max: C2x)
+    ('rhel92',     'clang',    None, [99, 11, 17, 23]), # Clang 15.0 (max: C2x)
+    ('rhel93',     'clang',    None, [99, 11, 17, 23]), # Clang 16.0 (max: C2x)
+    ('rhel94',     'clang',    None, [99, 11, 17, 23]), # Clang 17.0 (max: C2x)
+    ('rhel95',     'clang',    None, [99, 11, 17, 23]), # Clang 18.0 (max: C23)
+
+    ('rhel76',     'gcc',    None, [99, 11,       ]), # GCC 4.8 (max: C11)
+    ('rhel80',     'gcc',    None, [99, 11, 17,   ]), # GCC 8.2 (max: C17)
+    ('debian10',   'gcc-8',  None, [99, 11, 17,   ]), # GCC 8.3 (max: C17)
+    ('rhel84',     'gcc',    None, [99, 11, 17,   ]), # GCC 8.4 (max: C17)
+    ('ubuntu2004', 'gcc-9',  None, [99, 11, 17, 23]), # GCC 9.4 (max: C2x)
+    ('debian11',   'gcc-10', None, [99, 11, 17, 23]), # GCC 10.2 (max: C2x)
+    ('rhel90',     'gcc',    None, [99, 11, 17, 23]), # GCC 11.2 (max: C2x)
+    ('rhel92',     'gcc',    None, [99, 11, 17, 23]), # GCC 11.3 (max: C2x)
+    ('rhel94',     'gcc',    None, [99, 11, 17, 23]), # GCC 11.4 (max: C2x)
+    ('rhel95',     'gcc',    None, [99, 11, 17, 23]), # GCC 11.5 (max: C2x)
+
+    ('windows-vsCurrent', 'vs2017x64', None, [99, 11, 17, 'latest']), # Max: C17, clatest (C2x)
+    ('windows-vsCurrent', 'vs2019x64', None, [99, 11, 17, 'latest']), # Max: C17, clatest (C2x)
+    ('windows-vsCurrent', 'vs2022x64', None, [99, 11, 17, 'latest']), # Max: C17, clatest (C2x)
 ]
 # fmt: on
 # pylint: enable=line-too-long
@@ -54,18 +71,20 @@ def tasks():
     res = []
 
     for distro_name, compiler, arch, stds in MATRIX:
-        tags = [TAG, distro_name, compiler, 'compile']
+        compiler_type = compiler.split('-')[0]
+
+        tags = [TAG, distro_name, compiler_type, 'compile']
 
         distro = find_large_distro(distro_name)
 
         compile_vars = None
-        compile_vars = {'CC': to_cc(compiler)}
+        compile_vars = compiler_to_vars(compiler)
 
         if arch:
             tags.append(arch)
             compile_vars.update({'MARCH': arch})
 
-        distro_str = make_distro_str(distro_name, compiler, arch)
+        distro_str = make_distro_str(distro_name, compiler_type, arch)
 
         for std in stds:
             with_std = {'C_STD_VERSION': std}
diff -pruN 1.30.4-1/.evergreen/config_generator/components/earthly.py 2.0.2-1/.evergreen/config_generator/components/earthly.py
--- 1.30.4-1/.evergreen/config_generator/components/earthly.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/earthly.py	2025-06-19 15:42:22.000000000 +0000
@@ -27,7 +27,7 @@ EnvKey = Literal[
     "alpine3.18",
     "alpine3.19",
     "archlinux",
-    "centos7"
+    "centos7",
 ]
 "Identifiers for environments. These correspond to special 'env.*' targets in the Earthfile."
 CompilerName = Literal["gcc", "clang"]
@@ -36,13 +36,13 @@ CompilerName = Literal["gcc", "clang"]
 # Other options: SSPI (Windows only), AUTO (not reliably test-able without more environments)
 SASLOption = Literal["Cyrus", "off"]
 "Valid options for the SASL configuration parameter"
-TLSOption = Literal["LibreSSL", "OpenSSL", "off"]
+TLSOption = Literal["OpenSSL", "off"]
 "Options for the TLS backend configuration parameter (AKA 'ENABLE_SSL')"
-CxxVersion = Literal["r3.8.0", "r3.9.0", "none"]
+CxxVersion = Literal["none"] # TODO: Once CXX-3103 is released, add latest C++ release tag.
 "C++ driver refs that are under CI test"
 
 # A separator character, since we cannot use whitespace
-_SEPARATOR = "\N{no-break space}\N{bullet}\N{no-break space}"
+_SEPARATOR = "\N{NO-BREAK SPACE}\N{BULLET}\N{NO-BREAK SPACE}"
 
 
 def os_split(env: EnvKey) -> tuple[str, None | str]:
@@ -59,9 +59,7 @@ def os_split(env: EnvKey) -> tuple[str,
         case "centos7":
             return "CentOS", "7.0"
         case _:
-            raise ValueError(
-                f"Failed to split OS env key {env=} into a name+version pair (unrecognized)"
-            )
+            raise ValueError(f"Failed to split OS env key {env=} into a name+version pair (unrecognized)")
 
 
 class EarthlyVariant(NamedTuple):
@@ -135,7 +133,7 @@ class Configuration(NamedTuple):
 
     @property
     def suffix(self) -> str:
-        return f"{_SEPARATOR}".join(f"{k}={v}" for k, v in self._asdict().items())
+        return _SEPARATOR.join(f"{k}={v}" for k, v in self._asdict().items())
 
 
 def task_filter(env: EarthlyVariant, conf: Configuration) -> bool:
@@ -144,27 +142,10 @@ def task_filter(env: EarthlyVariant, con
     configuration values.
     """
     match env, conf:
-        # We only need one task with "sasl=off"
-        case ["u22", "gcc"], ("off", "OpenSSL", "r3.8.0"):
-            return True
-        # The Ubuntu 18.04 GCC has a bug that fails to build the 3.8.0 C++ driver
-        case ["u18", "gcc"], [_, _, "r3.8.0"]:
-            return False
-        # Other sasl=off tasks we'll just ignore:
-        case _, ("off", _tls, _cxx):
-            return False
-        # Ubuntu and CentOS do not ship with a LibreSSL package:
-        case e, (_sasl, "LibreSSL", _cxx) if e.display_name.startswith("Ubuntu") or e.display_name.startswith("CentOS"):
-            return False
-        # u16 is not capable of building mongocxx
-        case e, (_, _, "none") if e.display_name.startswith("Ubuntu 16") or e.display_name.startswith("CentOS 7"):
-            return True
-         # Exclude u16 for all other configurations
-        case e, _ if e.display_name.startswith("Ubuntu 16") or e.display_name.startswith("CentOS 7"):
-            return False
-        # Exclude all other envs
-        case _, (_, _, "none"):
-            return False
+        # u16/centos7 are not capable of building mongocxx
+        case e, (_sasl, _tls, cxx) if re.match(r"^Ubuntu 16|^CentOS 7", e.display_name):
+            # Only build if C++ driver is test is disabled
+            return cxx == "none"
         # Anything else: Allow it to run:
         case _:
             return True
@@ -230,11 +211,11 @@ def earthly_task(
         commands=[
             # Ensure subsequent Docker commands are authenticated.
             subprocess_exec(
-                binary='bash',
-                command_type="setup",
+                binary="bash",
+                command_type=EvgCommandType.SETUP,
                 args=[
                     "-c",
-                    'docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"'
+                    r'docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"',
                 ],
             ),
             # First, just build the "env-warmup" which will prepare the build environment.
@@ -253,8 +234,8 @@ def earthly_task(
                 # The "targets" arg is for +run to specify which targets to run
                 args={"targets": " ".join(targets)} | earthly_args,
             ),
-        ],
-        tags=[f"earthly", "pr-merge-gate", *env_tags],
+        ],  # type: ignore (The type annots on `commands` is wrong)
+        tags=["earthly", "pr-merge-gate", *env_tags],
         run_on=CONTAINER_RUN_DISTROS,
     )
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/funcs/fetch_build.py 2.0.2-1/.evergreen/config_generator/components/funcs/fetch_build.py
--- 1.30.4-1/.evergreen/config_generator/components/funcs/fetch_build.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/funcs/fetch_build.py	2025-06-19 15:42:22.000000000 +0000
@@ -17,7 +17,7 @@ class FetchBuild(Function):
             aws_secret='${aws_secret}',
             bucket='mciuploads',
             local_file='build.tar.gz',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${BUILD_NAME}/${build_id}.tar.gz',
+            remote_file='${project}/${build_variant}/${revision}/${BUILD_NAME}/${build_id}.tar.gz',
         ),
         archive_targz_extract(path='build.tar.gz', destination='mongoc'),
         # Scripts may not be executable on Windows.
diff -pruN 1.30.4-1/.evergreen/config_generator/components/funcs/upload_build.py 2.0.2-1/.evergreen/config_generator/components/funcs/upload_build.py
--- 1.30.4-1/.evergreen/config_generator/components/funcs/upload_build.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/funcs/upload_build.py	2025-06-19 15:42:22.000000000 +0000
@@ -14,7 +14,7 @@ class UploadBuild(Function):
         s3_put(
             aws_key='${aws_key}',
             aws_secret='${aws_secret}',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${task_name}/${build_id}.tar.gz',
+            remote_file='${project}/${build_variant}/${revision}/${task_name}/${build_id}.tar.gz',
             bucket='mciuploads',
             permissions='public-read',
             local_file='${build_id}.tar.gz',
diff -pruN 1.30.4-1/.evergreen/config_generator/components/funcs/upload_mo_artifacts.py 2.0.2-1/.evergreen/config_generator/components/funcs/upload_mo_artifacts.py
--- 1.30.4-1/.evergreen/config_generator/components/funcs/upload_mo_artifacts.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/funcs/upload_mo_artifacts.py	2025-06-19 15:42:22.000000000 +0000
@@ -30,7 +30,7 @@ class UploadMOArtifacts(Function):
             local_file='mongoc/mongodb-logs.tar.gz',
             optional=True,
             permissions='public-read',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-mongodb-logs.tar.gz',
+            remote_file='${project}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-mongodb-logs.tar.gz',
         ),
         s3_put(
             aws_key='${aws_key}',
@@ -41,7 +41,7 @@ class UploadMOArtifacts(Function):
             local_file='mongoc/MO/server.log',
             optional=True,
             permissions='public-read',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-orchestration.log',
+            remote_file='${project}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-orchestration.log',
         ),
         bash_exec(
             working_dir='mongoc',
@@ -83,7 +83,7 @@ class UploadMOArtifacts(Function):
             local_file='mongo-coredumps.tgz',
             optional=True,
             permissions='public-read',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/coredumps/${task_id}-${execution}-coredumps.log',
+            remote_file='${project}/${build_variant}/${revision}/${version_id}/${build_id}/coredumps/${task_id}-${execution}-coredumps.log',
         ),
     ]
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/loadbalanced.py 2.0.2-1/.evergreen/config_generator/components/loadbalanced.py
--- 1.30.4-1/.evergreen/config_generator/components/loadbalanced.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/loadbalanced.py	2025-06-19 15:42:22.000000000 +0000
@@ -83,7 +83,6 @@ def tasks():
                 env={
                     'CC': _COMPILER,
                     'CFLAGS': '-fno-omit-frame-pointer',
-                    'EXTRA_CONFIGURE_FLAGS': '-DENABLE_EXTRA_ALIGNMENT=OFF',
                     'SSL': 'OPENSSL'
                 },
                 working_dir='mongoc',
diff -pruN 1.30.4-1/.evergreen/config_generator/components/make_docs.py 2.0.2-1/.evergreen/config_generator/components/make_docs.py
--- 1.30.4-1/.evergreen/config_generator/components/make_docs.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/make_docs.py	2025-06-19 15:42:22.000000000 +0000
@@ -39,7 +39,7 @@ class UploadDocs(Function):
                 "AWS_ACCESS_KEY_ID": "${aws_key}",
                 "AWS_SECRET_ACCESS_KEY": "${aws_secret}",
             },
-            script="aws s3 cp doc/html s3://mciuploads/mongo-c-driver/docs/libbson/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1",
+            script="aws s3 cp doc/html s3://mciuploads/${project}/docs/libbson/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1",
         ),
         s3_put(
             aws_key="${aws_key}",
@@ -49,7 +49,7 @@ class UploadDocs(Function):
             display_name="libbson docs",
             local_file="mongoc/_build/for-docs/src/libbson/doc/html/index.html",
             permissions="public-read",
-            remote_file="mongo-c-driver/docs/libbson/${CURRENT_VERSION}/index.html",
+            remote_file="${project}/docs/libbson/${CURRENT_VERSION}/index.html",
         ),
         bash_exec(
             working_dir="mongoc/_build/for-docs/src/libmongoc",
@@ -57,7 +57,7 @@ class UploadDocs(Function):
                 "AWS_ACCESS_KEY_ID": "${aws_key}",
                 "AWS_SECRET_ACCESS_KEY": "${aws_secret}",
             },
-            script="aws s3 cp doc/html s3://mciuploads/mongo-c-driver/docs/libmongoc/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1",
+            script="aws s3 cp doc/html s3://mciuploads/${project}/docs/libmongoc/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1",
         ),
         s3_put(
             aws_key="${aws_key}",
@@ -67,7 +67,7 @@ class UploadDocs(Function):
             display_name="libmongoc docs",
             local_file="mongoc/_build/for-docs/src/libmongoc/doc/html/index.html",
             permissions="public-read",
-            remote_file="mongo-c-driver/docs/libmongoc/${CURRENT_VERSION}/index.html",
+            remote_file="${project}/docs/libmongoc/${CURRENT_VERSION}/index.html",
         ),
     ]
 
@@ -102,7 +102,7 @@ class UploadManPages(Function):
             display_name="libbson man pages",
             local_file="mongoc/bson-man-pages.html",
             permissions="public-read",
-            remote_file="mongo-c-driver/man-pages/libbson/${CURRENT_VERSION}/index.html",
+            remote_file="${project}/man-pages/libbson/${CURRENT_VERSION}/index.html",
         ),
         s3_put(
             aws_key="${aws_key}",
@@ -112,7 +112,7 @@ class UploadManPages(Function):
             display_name="libmongoc man pages",
             local_file="mongoc/mongoc-man-pages.html",
             permissions="public-read",
-            remote_file="mongo-c-driver/man-pages/libmongoc/${CURRENT_VERSION}/index.html",
+            remote_file="${project}/man-pages/libmongoc/${CURRENT_VERSION}/index.html",
         ),
     ]
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/mock_server.py 2.0.2-1/.evergreen/config_generator/components/mock_server.py
--- 1.30.4-1/.evergreen/config_generator/components/mock_server.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/mock_server.py	2025-06-19 15:42:22.000000000 +0000
@@ -42,7 +42,6 @@ def variants():
                 'CC': 'gcc',
                 'ASAN': 'on',
                 'CFLAGS': '-fno-omit-frame-pointer',
-                'EXTRA_CONFIGURE_FLAGS': '-DENABLE_EXTRA_ALIGNMENT=OFF',
                 'SANITIZE': 'address,undefined',
             }
         ),
diff -pruN 1.30.4-1/.evergreen/config_generator/components/openssl_static_compile.py 2.0.2-1/.evergreen/config_generator/components/openssl_static_compile.py
--- 1.30.4-1/.evergreen/config_generator/components/openssl_static_compile.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/openssl_static_compile.py	2025-06-19 15:42:22.000000000 +0000
@@ -6,7 +6,7 @@ from config_generator.components.funcs.f
 
 from config_generator.etc.distros import find_large_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 from config_generator.etc.function import Function
 from config_generator.etc.utils import bash_exec
 
@@ -55,7 +55,7 @@ def tasks():
         distro = find_large_distro(distro_name)
 
         compile_vars = None
-        compile_vars = {'CC': to_cc(compiler)}
+        compile_vars = compiler_to_vars(compiler)
 
         if arch:
             tags.append(arch)
@@ -72,7 +72,7 @@ def tasks():
                 tags=tags,
                 commands=[
                     FindCMakeLatest.call(),
-                    StaticOpenSSLCompile.call(vars=compile_vars),
+                    StaticOpenSSLCompile.call(vars=compile_vars if compile_vars else None),
                 ],
             )
         )
diff -pruN 1.30.4-1/.evergreen/config_generator/components/sanitizers/asan.py 2.0.2-1/.evergreen/config_generator/components/sanitizers/asan.py
--- 1.30.4-1/.evergreen/config_generator/components/sanitizers/asan.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/sanitizers/asan.py	2025-06-19 15:42:22.000000000 +0000
@@ -10,7 +10,6 @@ def variants():
         'ASAN': 'on',
         'CFLAGS': '-fno-omit-frame-pointer',
         'CHECK_LOG': 'ON',
-        'EXTRA_CONFIGURE_FLAGS': '-DENABLE_EXTRA_ALIGNMENT=OFF',
         'SANITIZE': 'address,undefined',
     }
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/sanitizers/tsan.py 2.0.2-1/.evergreen/config_generator/components/sanitizers/tsan.py
--- 1.30.4-1/.evergreen/config_generator/components/sanitizers/tsan.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/sanitizers/tsan.py	2025-06-19 15:42:22.000000000 +0000
@@ -9,7 +9,7 @@ def variants():
     expansions = {
         'CFLAGS': '-fno-omit-frame-pointer',
         'CHECK_LOG': 'ON',
-        'EXTRA_CONFIGURE_FLAGS': '-DENABLE_EXTRA_ALIGNMENT=OFF -DENABLE_SHM_COUNTERS=OFF',
+        'EXTRA_CONFIGURE_FLAGS': '-DENABLE_SHM_COUNTERS=OFF',
         'SANITIZE': 'thread',
     }
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/sasl/openssl.py 2.0.2-1/.evergreen/config_generator/components/sasl/openssl.py
--- 1.30.4-1/.evergreen/config_generator/components/sasl/openssl.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/sasl/openssl.py	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,3 @@
-from typing import List
-
 from shrub.v3.evg_build_variant import BuildVariant
 
 from config_generator.etc.utils import TaskRef
@@ -28,6 +26,7 @@ COMPILE_MATRIX = [
     ('ubuntu2004-arm64',  'gcc',        None, ['cyrus']),
     ('ubuntu2004',        'gcc',        None, ['cyrus']),
     ('windows-vsCurrent', 'vs2017x64',  None, ['cyrus']),
+    ('amazon2023-arm64-latest-large-m8g', 'gcc', None, ['cyrus']),
 ]
 
 TEST_MATRIX = [
@@ -40,6 +39,9 @@ TEST_MATRIX = [
 
     # Test 4.2 with Debian 10 since 4.2 does not ship on Ubuntu 20.04+.
     ('debian10',          'gcc',       None, 'cyrus', ['auth'], ['server', 'replica'], ['4.2']), 
+
+    # Test with Graviton processor:
+    ('amazon2023-arm64-latest-large-m8g', 'gcc',  None, 'cyrus', ['auth'], ['server', 'replica', 'sharded'], ['latest']),
 ]
 # fmt: on
 # pylint: enable=line-too-long
diff -pruN 1.30.4-1/.evergreen/config_generator/components/sasl/winssl.py 2.0.2-1/.evergreen/config_generator/components/sasl/winssl.py
--- 1.30.4-1/.evergreen/config_generator/components/sasl/winssl.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/sasl/winssl.py	2025-06-19 15:42:22.000000000 +0000
@@ -15,16 +15,15 @@ TAG = f'sasl-matrix-{SSL}'
 # pylint: disable=line-too-long
 # fmt: off
 COMPILE_MATRIX = [
-    ('windows-vsCurrent', 'mingw',     None, [                'sspi']),
-    ('windows-vsCurrent', 'vs2017x64', None, ['off', 'cyrus', 'sspi']),
-    ('windows-vsCurrent', 'vs2017x86', None, ['off',          'sspi']),
+    ('windows-vsCurrent', 'mingw',     None, [       'sspi']),
+    ('windows-vsCurrent', 'vs2017x64', None, ['off', 'sspi']),
+    ('windows-vsCurrent', 'vs2017x86', None, ['off', 'sspi']),
 ]
 
 TEST_MATRIX = [
-    ('windows-vsCurrent', 'vs2017x64', None, 'cyrus', ['auth'], ['server'], ['4.0', '4.2', '4.4', '5.0', '6.0', '7.0', '8.0', 'latest']),
+    ('windows-vsCurrent', 'vs2017x64', None, 'sspi', ['auth'], ['server'], ['4.0', '4.2', '4.4', '5.0', '6.0', '7.0', '8.0', 'latest']),
 
     ('windows-vsCurrent', 'mingw',     None, 'sspi',  ['auth'], ['server'], ['8.0', 'latest']),
-    ('windows-vsCurrent', 'vs2017x64', None, 'sspi',  ['auth'], ['server'], ['8.0', 'latest']),
     ('windows-vsCurrent', 'vs2017x86', None, 'sspi',  ['auth'], ['server'], ['8.0', 'latest']),
 ]
 # fmt: on
@@ -40,11 +39,6 @@ class SaslOffWinSSLCompile(WinSSLCompile
     commands = WinSSLCompileCommon.compile_commands(sasl='OFF')
 
 
-class SaslCyrusWinSSLCompile(WinSSLCompileCommon):
-    name = 'sasl-cyrus-winssl-compile'
-    commands = WinSSLCompileCommon.compile_commands(sasl='CYRUS')
-
-
 class SaslSspiWinSSLCompile(WinSSLCompileCommon):
     name = 'sasl-sspi-winssl-compile'
     commands = WinSSLCompileCommon.compile_commands(sasl='SSPI')
@@ -53,7 +47,6 @@ class SaslSspiWinSSLCompile(WinSSLCompil
 def functions():
     return merge_defns(
         SaslOffWinSSLCompile.defn(),
-        SaslCyrusWinSSLCompile.defn(),
         SaslSspiWinSSLCompile.defn(),
     )
 
@@ -63,7 +56,6 @@ def tasks():
 
     SASL_TO_FUNC = {
         'off': SaslOffWinSSLCompile,
-        'cyrus': SaslCyrusWinSSLCompile,
         'sspi': SaslSspiWinSSLCompile,
     }
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/sbom.py 2.0.2-1/.evergreen/config_generator/components/sbom.py
--- 1.30.4-1/.evergreen/config_generator/components/sbom.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/sbom.py	2025-06-19 15:42:22.000000000 +0000
@@ -80,7 +80,7 @@ class SBOM(Function):
             display_name='Augmented SBOM',
             local_file='mongoc/augmented-sbom.json',
             permissions='public-read',
-            remote_file='mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/sbom/augmented-sbom.json',
+            remote_file='${project}/${build_variant}/${revision}/${version_id}/${build_id}/sbom/augmented-sbom.json',
         ),
     ]
 
diff -pruN 1.30.4-1/.evergreen/config_generator/components/scan_build.py 2.0.2-1/.evergreen/config_generator/components/scan_build.py
--- 1.30.4-1/.evergreen/config_generator/components/scan_build.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/components/scan_build.py	2025-06-19 15:42:22.000000000 +0000
@@ -7,7 +7,7 @@ from config_generator.components.funcs.f
 
 from config_generator.etc.distros import find_large_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 from config_generator.etc.function import Function
 from config_generator.etc.utils import bash_exec
 
@@ -56,7 +56,7 @@ def tasks():
         distro = find_large_distro(distro_name)
 
         compile_vars = None
-        compile_vars = {'CC': to_cc(compiler)}
+        compile_vars = compiler_to_vars(compiler)
 
         if arch:
             tags.append(arch)
@@ -73,7 +73,7 @@ def tasks():
                 tags=tags,
                 commands=[
                     FindCMakeLatest.call(),
-                    ScanBuild.call(vars=compile_vars),
+                    ScanBuild.call(vars=compile_vars if compile_vars else None),
                     FunctionCall(func='upload scan artifacts'),
                 ],
             )
diff -pruN 1.30.4-1/.evergreen/config_generator/etc/compile.py 2.0.2-1/.evergreen/config_generator/etc/compile.py
--- 1.30.4-1/.evergreen/config_generator/etc/compile.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/etc/compile.py	2025-06-19 15:42:22.000000000 +0000
@@ -2,7 +2,7 @@ from shrub.v3.evg_task import EvgTask
 
 from config_generator.etc.distros import find_large_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 
 from config_generator.components.funcs.find_cmake_latest import FindCMakeLatest
 from config_generator.components.funcs.upload_build import UploadBuild
@@ -20,7 +20,7 @@ def generate_compile_tasks(SSL, TAG, SAS
         distro = find_large_distro(distro_name)
 
         compile_vars = None
-        compile_vars = {'CC': to_cc(compiler)}
+        compile_vars = compiler_to_vars(compiler)
 
         if arch:
             tags.append(arch)
@@ -38,7 +38,7 @@ def generate_compile_tasks(SSL, TAG, SAS
 
             commands = []
             commands.append(FindCMakeLatest.call())
-            commands.append(SASL_TO_FUNC[sasl].call(vars=compile_vars))
+            commands.append(SASL_TO_FUNC[sasl].call(vars=compile_vars if compile_vars else None))
             commands.append(UploadBuild.call())
 
             res.append(
diff -pruN 1.30.4-1/.evergreen/config_generator/etc/cse/test.py 2.0.2-1/.evergreen/config_generator/etc/cse/test.py
--- 1.30.4-1/.evergreen/config_generator/etc/cse/test.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/etc/cse/test.py	2025-06-19 15:42:22.000000000 +0000
@@ -6,7 +6,7 @@ from shrub.v3.evg_task import EvgTask, E
 
 from config_generator.etc.distros import find_small_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 
 from config_generator.components.funcs.bootstrap_mongo_orchestration import BootstrapMongoOrchestration
 from config_generator.components.funcs.fetch_build import FetchBuild
@@ -29,7 +29,7 @@ def generate_test_tasks(SSL, TAG, MATRIX
         test_distro = find_small_distro(distro_name)
 
         compile_vars = []
-        compile_vars.append(KeyValueParam(key='CC', value=to_cc(compiler)))
+        compile_vars = [KeyValueParam(key=key, value=value) for key, value in compiler_to_vars(compiler).items()]
 
         if arch:
             tags.append(arch)
diff -pruN 1.30.4-1/.evergreen/config_generator/etc/distros.py 2.0.2-1/.evergreen/config_generator/etc/distros.py
--- 1.30.4-1/.evergreen/config_generator/etc/distros.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/etc/distros.py	2025-06-19 15:42:22.000000000 +0000
@@ -39,18 +39,18 @@ class Distro(BaseModel):
     def validate_os_ver(cls, value):
         return Version(value)
 
-# See: https://evergreen.mongodb.com/distros
-# pylint: disable=line-too-long
-#fmt: off
+
+def ls_distro(name, **kwargs):
+    return [
+        Distro(name=f'{name}-large', size='large', **kwargs),
+        Distro(name=f'{name}-small', size='small', **kwargs),
+    ]
+
+
 DEBIAN_DISTROS = [
-    Distro(name='debian92-large', os='debian', os_type='linux', os_ver='9.2', size='large'), # CDRIVER-5873
-    Distro(name='debian92-small', os='debian', os_type='linux', os_ver='9.2', size='small'), # CDRIVER-5873
-    Distro(name='debian10-large', os='debian', os_type='linux', os_ver='10', size='large'), # CDRIVER-5874
-    Distro(name='debian10-small', os='debian', os_type='linux', os_ver='10', size='small'), # CDRIVER-5874
-    Distro(name='debian11-large', os='debian', os_type='linux', os_ver='11', size='large'),
-    Distro(name='debian11-small', os='debian', os_type='linux', os_ver='11', size='small'),
-    Distro(name='debian92-large', os='debian', os_type='linux', os_ver='9.2', size='large'),
-    Distro(name='debian92-small', os='debian', os_type='linux', os_ver='9.2', size='small'),
+    *ls_distro(name='debian92', os='debian', os_type='linux', os_ver='9.2'),  # CDRIVER-5873
+    *ls_distro(name='debian10', os='debian', os_type='linux', os_ver='10'),  # CDRIVER-5874
+    *ls_distro(name='debian11', os='debian', os_type='linux', os_ver='11'),
 ]
 
 MACOS_DISTROS = [
@@ -63,70 +63,62 @@ MACOS_ARM64_DISTROS = [
 ]
 
 RHEL_DISTROS = [
-    Distro(name='rhel80-large', os='rhel', os_type='linux', os_ver='8.0', size='large'),
-    Distro(name='rhel80-small', os='rhel', os_type='linux', os_ver='8.0', size='small'),
-    Distro(name='rhel84-large', os='rhel', os_type='linux', os_ver='8.4', size='large'),
-    Distro(name='rhel84-small', os='rhel', os_type='linux', os_ver='8.4', size='small'),
-    Distro(name='rhel8.9-large', os='rhel', os_type='linux', os_ver='8.7', size='large'),
-    Distro(name='rhel8.9-small', os='rhel', os_type='linux', os_ver='8.7', size='small'),
-    Distro(name='rhel92-large', os='rhel', os_type='linux', os_ver='9.0', size='large'),
-    Distro(name='rhel92-small', os='rhel', os_type='linux', os_ver='9.0', size='small'),
-]
-
-RHEL_ARM64_DISTROS = [
-    Distro(name='rhel82-arm64-large', os='rhel', os_type='linux', os_ver='8.2', size='large', arch='arm64'),
-    Distro(name='rhel82-arm64-small', os='rhel', os_type='linux', os_ver='8.2', size='small', arch='arm64'),
-    Distro(name='rhel92-arm64-large', os='rhel', os_type='linux', os_ver='9.0', size='large', arch='arm64'),
-    Distro(name='rhel92-arm64-small', os='rhel', os_type='linux', os_ver='9.0', size='small', arch='arm64'),
+    *ls_distro(name='rhel76', os='rhel', os_type='linux', os_ver='7.6'),
+    *ls_distro(name='rhel80', os='rhel', os_type='linux', os_ver='8.0'),
+    *ls_distro(name='rhel84', os='rhel', os_type='linux', os_ver='8.4'),
+    *ls_distro(name='rhel90', os='rhel', os_type='linux', os_ver='9.0'),
+    *ls_distro(name='rhel91', os='rhel', os_type='linux', os_ver='9.1'),
+    *ls_distro(name='rhel92', os='rhel', os_type='linux', os_ver='9.2'),
+    *ls_distro(name='rhel93', os='rhel', os_type='linux', os_ver='9.3'),
+    *ls_distro(name='rhel94', os='rhel', os_type='linux', os_ver='9.4'),
+    *ls_distro(name='rhel95', os='rhel', os_type='linux', os_ver='9.5'),
+    *ls_distro(name='rhel8.9', os='rhel', os_type='linux', os_ver='8.7'),
+    *ls_distro(name='rhel92', os='rhel', os_type='linux', os_ver='9.0'),
 ]
 
 RHEL_POWER_DISTROS = [
-    Distro(name='rhel8-power-large', os='rhel', os_type='linux', os_ver='8', size='large', arch='power'),
-    Distro(name='rhel8-power-small', os='rhel', os_type='linux', os_ver='8', size='small', arch='power'),
-    Distro(name='rhel9-power-large', os='rhel', os_type='linux', os_ver='9', size='large', arch='power'),
-    Distro(name='rhel9-power-small', os='rhel', os_type='linux', os_ver='9', size='small', arch='power'),
+    *ls_distro(name='rhel8-power', os='rhel', os_type='linux', os_ver='8', arch='power'),
 ]
 
 RHEL_ZSERIES_DISTROS = [
-    Distro(name='rhel8-zseries-large', os='rhel', os_type='linux', os_ver='8', size='large', arch='zseries'),
-    Distro(name='rhel8-zseries-small', os='rhel', os_type='linux', os_ver='8', size='small', arch='zseries'),
-    Distro(name='rhel9-zseries-large', os='rhel', os_type='linux', os_ver='9', size='large', arch='zseries'),
-    Distro(name='rhel9-zseries-small', os='rhel', os_type='linux', os_ver='9', size='small', arch='zseries'),
+    *ls_distro(name='rhel8-zseries', os='rhel', os_type='linux', os_ver='8', arch='zseries'),
 ]
 
 UBUNTU_DISTROS = [
-    Distro(name='ubuntu2004-large', os='ubuntu', os_type='linux', os_ver='20.04', size='large'),
-    Distro(name='ubuntu2004-small', os='ubuntu', os_type='linux', os_ver='20.04', size='small'),
-    Distro(name='ubuntu2204-large', os='ubuntu', os_type='linux', os_ver='22.04', size='large'),
-    Distro(name='ubuntu2204-small', os='ubuntu', os_type='linux', os_ver='22.04', size='small'),
+    *ls_distro(name='ubuntu2004', os='ubuntu', os_type='linux', os_ver='20.04'),
+    *ls_distro(name='ubuntu2204', os='ubuntu', os_type='linux', os_ver='22.04'),
 ]
 
 UBUNTU_ARM64_DISTROS = [
-    Distro(name='ubuntu2004-arm64-large', os='ubuntu', os_type='linux', os_ver='20.04', size='large', arch='arm64'),
-    Distro(name='ubuntu2004-arm64-small', os='ubuntu', os_type='linux', os_ver='20.04', size='small', arch='arm64'),
-    Distro(name='ubuntu2204-arm64-large', os='ubuntu', os_type='linux', os_ver='22.04', size='large', arch='arm64'),
-    Distro(name='ubuntu2204-arm64-small', os='ubuntu', os_type='linux', os_ver='22.04', size='small', arch='arm64'),
+    *ls_distro(name='ubuntu2004-arm64', os='ubuntu', os_type='linux', os_ver='20.04', arch='arm64'),
 ]
 
 WINDOWS_DISTROS = [
-    Distro(name='windows-vsCurrent-large', os='windows', os_type='windows', vs_ver='vsCurrent', size='large'), # Windows Server 2019
-    Distro(name='windows-vsCurrent-small', os='windows', os_type='windows', vs_ver='vsCurrent', size='small'), # Windows Server 2019
+    *ls_distro(name='windows-64-vs2017', os='windows', os_type='windows', vs_ver='2017'),
+    *ls_distro(name='windows-64-vs2019', os='windows', os_type='windows', vs_ver='2019'),
+
+    *ls_distro(name='windows-vsCurrent', os='windows', os_type='windows', vs_ver='vsCurrent'),  # Windows Server 2019
+]
+
+GRAVITON_DISTROS = [
+    Distro(name='amazon2023-arm64-latest-large-m8g', os='amazon2023', os_type='linux', os_ver='2023', arch='arm64'),
+    Distro(name='amazon2-arm64-latest-large-m8g', os='amazon2', os_type='linux', os_ver='2', arch='arm64'),
 ]
-#fmt: on
-# pylint: enable=line-too-long
 
+# See: https://evergreen.mongodb.com/distros
 # Ensure no-arch distros are ordered before arch-specific distros.
-ALL_DISTROS = [] + \
-    DEBIAN_DISTROS + \
-    MACOS_DISTROS + \
-    MACOS_ARM64_DISTROS + \
-    RHEL_DISTROS + \
-    RHEL_ARM64_DISTROS + \
-    RHEL_POWER_DISTROS + \
-    RHEL_ZSERIES_DISTROS + \
-    UBUNTU_DISTROS + \
-    UBUNTU_ARM64_DISTROS + \
-    WINDOWS_DISTROS
+ALL_DISTROS = [
+    *DEBIAN_DISTROS,
+    *MACOS_DISTROS,
+    *MACOS_ARM64_DISTROS,
+    *RHEL_DISTROS,
+    *RHEL_POWER_DISTROS,
+    *RHEL_ZSERIES_DISTROS,
+    *UBUNTU_DISTROS,
+    *UBUNTU_ARM64_DISTROS,
+    *WINDOWS_DISTROS,
+    *GRAVITON_DISTROS
+]
 
 
 def find_distro(name) -> Distro:
@@ -180,12 +172,12 @@ def make_distro_str(distro_name, compile
         #     ('windows-64-vs2017', 'vs2017x64', None) -> vs2017-x64
         #     ('windows-64-vs2017', 'mingw',     None) -> vs2017-mingw
         distro_str = distro_name[len('windows-64-'):] + {
-            'vs2013x64': '-x64',
-            'vs2013x86': '-x86',
-            'vs2015x64': '-x64',
-            'vs2015x86': '-x86',
             'vs2017x64': '-x64',
             'vs2017x86': '-x86',
+            'vs2019x64': '-x64',
+            'vs2019x86': '-x86',
+            'vs2022x64': '-x64',
+            'vs2022x86': '-x86',
         }.get(compiler, f'-{compiler}')
     else:
         distro_str = distro_name
@@ -200,10 +192,48 @@ def make_distro_str(distro_name, compile
 
 def to_cc(compiler):
     return {
-        'vs2013x64': 'Visual Studio 12 2013 Win64',
-        'vs2013x86': 'Visual Studio 12 2013',
-        'vs2015x64': 'Visual Studio 14 2015 Win64',
-        'vs2015x86': 'Visual Studio 14 2015',
-        'vs2017x64': 'Visual Studio 15 2017 Win64',
+        'vs2017x64': 'Visual Studio 15 2017',
         'vs2017x86': 'Visual Studio 15 2017',
+        'vs2019x64': 'Visual Studio 16 2019',
+        'vs2019x86': 'Visual Studio 16 2019',
+        'vs2022x64': 'Visual Studio 17 2022',
+        'vs2022x86': 'Visual Studio 17 2022',
+    }.get(compiler, compiler)
+
+
+def to_platform(compiler):
+    return {
+        'vs2017x64': 'x64',
+        'vs2017x86': 'Win32',
+        'vs2019x64': 'x64',
+        'vs2019x86': 'Win32',
+        'vs2022x64': 'x64',
+        'vs2022x86': 'Win32',
     }.get(compiler, compiler)
+
+
+def compiler_to_vars(compiler):
+    match compiler, compiler.split('-'):
+        case _, ['gcc', *rest]:
+            return {
+                'CC': '-'.join(['gcc'] + rest),
+                'CXX': '-'.join(['g++'] + rest),
+            }
+
+        case _, ['clang', *rest]:
+            return {
+                'CC': '-'.join(['clang'] + rest),
+                'CXX': '-'.join(['clang++'] + rest),
+            }
+
+        case str(vs), _ if 'vs' in vs:
+            return {
+                'CMAKE_GENERATOR': to_cc(vs),
+                'CMAKE_GENERATOR_PLATFORM': to_platform(vs),
+            }
+
+        case compiler, _:
+            return {
+                'CC': compiler,
+                'CXX': compiler,
+            }
diff -pruN 1.30.4-1/.evergreen/config_generator/etc/sanitizers/test.py 2.0.2-1/.evergreen/config_generator/etc/sanitizers/test.py
--- 1.30.4-1/.evergreen/config_generator/etc/sanitizers/test.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/etc/sanitizers/test.py	2025-06-19 15:42:22.000000000 +0000
@@ -6,7 +6,7 @@ from shrub.v3.evg_task import EvgTask, E
 
 from config_generator.etc.distros import find_small_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 
 from config_generator.components.funcs.bootstrap_mongo_orchestration import BootstrapMongoOrchestration
 from config_generator.components.funcs.fetch_build import FetchBuild
@@ -37,7 +37,7 @@ def generate_test_tasks(SSL, TAG, MATRIX
         test_distro = find_small_distro(distro_name)
 
         compile_vars = []
-        compile_vars.append(KeyValueParam(key='CC', value=to_cc(compiler)))
+        compile_vars = [KeyValueParam(key=key, value=value) for key, value in compiler_to_vars(compiler).items()]
 
         if arch:
             tags.append(arch)
diff -pruN 1.30.4-1/.evergreen/config_generator/etc/sasl/test.py 2.0.2-1/.evergreen/config_generator/etc/sasl/test.py
--- 1.30.4-1/.evergreen/config_generator/etc/sasl/test.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/config_generator/etc/sasl/test.py	2025-06-19 15:42:22.000000000 +0000
@@ -6,7 +6,7 @@ from shrub.v3.evg_task import EvgTask, E
 
 from config_generator.etc.distros import find_small_distro
 from config_generator.etc.distros import make_distro_str
-from config_generator.etc.distros import to_cc
+from config_generator.etc.distros import compiler_to_vars
 
 from config_generator.components.funcs.bootstrap_mongo_orchestration import BootstrapMongoOrchestration
 from config_generator.components.funcs.fetch_build import FetchBuild
@@ -29,7 +29,7 @@ def generate_test_tasks(SSL, TAG, MATRIX
         test_distro = find_small_distro(distro_name)
 
         compile_vars = []
-        compile_vars.append(KeyValueParam(key='CC', value=to_cc(compiler)))
+        compile_vars = [KeyValueParam(key=key, value=value) for key, value in compiler_to_vars(compiler).items()]
 
         if arch:
             tags.append(arch)
diff -pruN 1.30.4-1/.evergreen/etc/spec.patch 2.0.2-1/.evergreen/etc/spec.patch
--- 1.30.4-1/.evergreen/etc/spec.patch	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/etc/spec.patch	2025-06-19 15:42:22.000000000 +0000
@@ -1,11 +1,11 @@
 --- mongo-c-driver.spec.orig	2025-02-28 17:04:19.401176260 -0500
-+++ mongo-c-driver.spec	2025-02-28 17:11:06.028378742 -0500
++++ mongo-c-driver.spec	2025-02-28 17:05:52.190076172 -0500
 @@ -10,7 +10,7 @@
  %global gh_project   mongo-c-driver
  %global libname      libmongoc
  %global libver       1.0
 -%global up_version   1.30.2
-+%global up_version   1.30.3
++%global up_version   1.31.0
  #global up_prever    rc0
  # disabled as require a MongoDB server
  %bcond_with          tests
diff -pruN 1.30.4-1/.evergreen/generated_configs/functions.yml 2.0.2-1/.evergreen/generated_configs/functions.yml
--- 1.30.4-1/.evergreen/generated_configs/functions.yml	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/generated_configs/functions.yml	2025-06-19 15:42:22.000000000 +0000
@@ -55,12 +55,12 @@ functions:
     - command: s3.put
       type: system
       params:
-        display_name: "ABI Report:"
+        display_name: "ABI Compliance Check: "
         aws_key: ${aws_key}
         aws_secret: ${aws_secret}
         bucket: mciuploads
         content_type: text/html
-        local_files_include_filter: mongoc/abi-compliance/compat_reports/**/*.html
+        local_files_include_filter: abi-compliance/compat_reports/**/compat_report.html
         permissions: public-read
         remote_file: mongo-c-driver/${branch_name}/${revision}/${version_id}/${build_id}/${task_id}/${execution}/abi-compliance-check/
     - command: s3.put
@@ -198,7 +198,7 @@ functions:
         aws_secret: ${aws_secret}
         bucket: mciuploads
         local_file: build.tar.gz
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${BUILD_NAME}/${build_id}.tar.gz
+        remote_file: ${project}/${build_variant}/${revision}/${BUILD_NAME}/${build_id}.tar.gz
     - command: archive.targz_extract
       params:
         destination: mongoc
@@ -453,19 +453,6 @@ functions:
         args:
           - -c
           - .evergreen/scripts/compile.sh
-  sasl-cyrus-winssl-compile:
-    - command: subprocess.exec
-      type: test
-      params:
-        binary: bash
-        working_dir: mongoc
-        add_expansions_to_env: true
-        env:
-          SASL: CYRUS
-          SSL: WINDOWS
-        args:
-          - -c
-          - .evergreen/scripts/compile.sh
   sasl-off-nossl-compile:
     - command: subprocess.exec
       type: test
@@ -552,7 +539,7 @@ functions:
         content_type: application/json
         local_file: mongoc/augmented-sbom.json
         permissions: public-read
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/sbom/augmented-sbom.json
+        remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/sbom/augmented-sbom.json
   scan-build:
     - command: subprocess.exec
       type: test
@@ -661,7 +648,7 @@ functions:
         content_type: ${content_type|application/x-gzip}
         local_file: ${build_id}.tar.gz
         permissions: public-read
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${task_name}/${build_id}.tar.gz
+        remote_file: ${project}/${build_variant}/${revision}/${task_name}/${build_id}.tar.gz
   upload-docs:
     - command: subprocess.exec
       params:
@@ -672,7 +659,7 @@ functions:
           AWS_SECRET_ACCESS_KEY: ${aws_secret}
         args:
           - -c
-          - aws s3 cp doc/html s3://mciuploads/mongo-c-driver/docs/libbson/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1
+          - aws s3 cp doc/html s3://mciuploads/${project}/docs/libbson/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1
     - command: s3.put
       params:
         display_name: libbson docs
@@ -682,7 +669,7 @@ functions:
         content_type: text/html
         local_file: mongoc/_build/for-docs/src/libbson/doc/html/index.html
         permissions: public-read
-        remote_file: mongo-c-driver/docs/libbson/${CURRENT_VERSION}/index.html
+        remote_file: ${project}/docs/libbson/${CURRENT_VERSION}/index.html
     - command: subprocess.exec
       params:
         binary: bash
@@ -692,7 +679,7 @@ functions:
           AWS_SECRET_ACCESS_KEY: ${aws_secret}
         args:
           - -c
-          - aws s3 cp doc/html s3://mciuploads/mongo-c-driver/docs/libmongoc/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1
+          - aws s3 cp doc/html s3://mciuploads/${project}/docs/libmongoc/${CURRENT_VERSION} --quiet --recursive --acl public-read --region us-east-1
     - command: s3.put
       params:
         display_name: libmongoc docs
@@ -702,7 +689,7 @@ functions:
         content_type: text/html
         local_file: mongoc/_build/for-docs/src/libmongoc/doc/html/index.html
         permissions: public-read
-        remote_file: mongo-c-driver/docs/libmongoc/${CURRENT_VERSION}/index.html
+        remote_file: ${project}/docs/libmongoc/${CURRENT_VERSION}/index.html
   upload-man-pages:
     - command: subprocess.exec
       params:
@@ -730,7 +717,7 @@ functions:
         content_type: text/html
         local_file: mongoc/bson-man-pages.html
         permissions: public-read
-        remote_file: mongo-c-driver/man-pages/libbson/${CURRENT_VERSION}/index.html
+        remote_file: ${project}/man-pages/libbson/${CURRENT_VERSION}/index.html
     - command: s3.put
       params:
         display_name: libmongoc man pages
@@ -740,7 +727,7 @@ functions:
         content_type: text/html
         local_file: mongoc/mongoc-man-pages.html
         permissions: public-read
-        remote_file: mongo-c-driver/man-pages/libmongoc/${CURRENT_VERSION}/index.html
+        remote_file: ${project}/man-pages/libmongoc/${CURRENT_VERSION}/index.html
   upload-mo-artifacts:
     - command: subprocess.exec
       params:
@@ -767,7 +754,7 @@ functions:
         local_file: mongoc/mongodb-logs.tar.gz
         optional: true
         permissions: public-read
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-mongodb-logs.tar.gz
+        remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-mongodb-logs.tar.gz
     - command: s3.put
       params:
         display_name: orchestration.log
@@ -778,7 +765,7 @@ functions:
         local_file: mongoc/MO/server.log
         optional: true
         permissions: public-read
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-orchestration.log
+        remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-orchestration.log
     - command: subprocess.exec
       params:
         binary: bash
@@ -821,7 +808,7 @@ functions:
         local_file: mongo-coredumps.tgz
         optional: true
         permissions: public-read
-        remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/coredumps/${task_id}-${execution}-coredumps.log
+        remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/coredumps/${task_id}-${execution}-coredumps.log
   upload-test-results:
     - command: subprocess.exec
       params:
diff -pruN 1.30.4-1/.evergreen/generated_configs/legacy-config.yml 2.0.2-1/.evergreen/generated_configs/legacy-config.yml
--- 1.30.4-1/.evergreen/generated_configs/legacy-config.yml	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/generated_configs/legacy-config.yml	2025-06-19 15:42:22.000000000 +0000
@@ -27,12 +27,12 @@ functions:
         set -o errexit
         export AWS_ACCESS_KEY_ID=${aws_key}
         export AWS_SECRET_ACCESS_KEY=${aws_secret}
-        aws s3 cp coverage s3://mciuploads/mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/coverage/ --recursive --acl public-read --region us-east-1
+        aws s3 cp coverage s3://mciuploads/${project}/${build_variant}/${revision}/${version_id}/${build_id}/coverage/ --recursive --acl public-read --region us-east-1
   - command: s3.put
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/coverage/index.html
+      remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/coverage/index.html
       bucket: mciuploads
       permissions: public-read
       local_file: mongoc/coverage/index.html
@@ -60,12 +60,12 @@ functions:
         set -o errexit
         export AWS_ACCESS_KEY_ID=${aws_key}
         export AWS_SECRET_ACCESS_KEY=${aws_secret}
-        aws s3 cp scan s3://mciuploads/mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/scan/ --recursive --acl public-read --region us-east-1
+        aws s3 cp scan s3://mciuploads/${project}/${build_variant}/${revision}/${version_id}/${build_id}/scan/ --recursive --acl public-read --region us-east-1
   - command: s3.put
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${build_variant}/${revision}/${version_id}/${build_id}/scan/index.html
+      remote_file: ${project}/${build_variant}/${revision}/${version_id}/${build_id}/scan/index.html
       bucket: mciuploads
       permissions: public-read
       local_file: mongoc/scan.html
@@ -94,7 +94,6 @@ functions:
         # Compile a program that links dynamically or statically to libmongoc,
         # using variables from pkg-config or CMake's find_package command.
         export BUILD_SAMPLE_WITH_CMAKE=${BUILD_SAMPLE_WITH_CMAKE}
-        export BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=${BUILD_SAMPLE_WITH_CMAKE_DEPRECATED}
         export ENABLE_SSL=${ENABLE_SSL}
         export ENABLE_SNAPPY=${ENABLE_SNAPPY}
         LINK_STATIC=  .evergreen/scripts/link-sample-program.sh
@@ -111,12 +110,10 @@ functions:
         set -o errexit
         # Compile a program that links dynamically or statically to libbson,
         # using variables from pkg-config or from CMake's find_package command.
-        BUILD_SAMPLE_WITH_CMAKE=  BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=  BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1 LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1 LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=1 LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=1 LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
   link sample program MSVC:
   - command: shell.exec
     type: test
@@ -355,21 +352,6 @@ tasks:
         set -o errexit
         env SNAPPY="OFF" ZLIB="OFF" ZSTD="ON" .evergreen/scripts/compile.sh
   - func: upload-build
-- name: debug-compile-no-align
-  tags:
-  - debug-compile
-  commands:
-  - func: find-cmake-latest
-  - command: shell.exec
-    type: test
-    params:
-      working_dir: mongoc
-      add_expansions_to_env: true
-      shell: bash
-      script: |-
-        set -o errexit
-        env EXTRA_CONFIGURE_FLAGS="-DENABLE_EXTRA_ALIGNMENT=OFF" SNAPPY="OFF" ZLIB="BUNDLED" ZSTD="OFF" .evergreen/scripts/compile.sh
-  - func: upload-build
 - name: debug-compile-nosasl-nossl
   tags:
   - debug-compile
@@ -649,40 +631,6 @@ tasks:
   - func: link sample program
     vars:
       BUILD_SAMPLE_WITH_CMAKE: 1
-- name: link-with-cmake-deprecated
-  commands:
-  - func: fetch-det
-  - func: bootstrap-mongo-orchestration
-  - func: link sample program
-    vars:
-      BUILD_SAMPLE_WITH_CMAKE: 1
-      BUILD_SAMPLE_WITH_CMAKE_DEPRECATED: 1
-- name: link-with-cmake-ssl-deprecated
-  commands:
-  - func: fetch-det
-  - func: bootstrap-mongo-orchestration
-  - func: link sample program
-    vars:
-      BUILD_SAMPLE_WITH_CMAKE: 1
-      BUILD_SAMPLE_WITH_CMAKE_DEPRECATED: 1
-      ENABLE_SSL: 1
-- name: link-with-cmake-snappy-deprecated
-  commands:
-  - func: fetch-det
-  - func: bootstrap-mongo-orchestration
-  - func: link sample program
-    vars:
-      BUILD_SAMPLE_WITH_CMAKE: 1
-      BUILD_SAMPLE_WITH_CMAKE_DEPRECATED: 1
-      ENABLE_SNAPPY: 'ON'
-- name: link-with-cmake-mac-deprecated
-  commands:
-  - func: fetch-det
-  - func: bootstrap-mongo-orchestration
-  - func: link sample program
-    vars:
-      BUILD_SAMPLE_WITH_CMAKE: 1
-      BUILD_SAMPLE_WITH_CMAKE_DEPRECATED: 1
 - name: link-with-cmake-windows
   commands:
   - func: fetch-det
@@ -753,7 +701,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/mongo-c-driver-debian-packages-${CURRENT_VERSION}.tar.gz
+      remote_file: ${project}/${branch_name}/mongo-c-driver-debian-packages-${CURRENT_VERSION}.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: deb.tar.gz
@@ -762,7 +710,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-debian-packages.tar.gz
+      remote_file: ${project}/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-debian-packages.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: deb.tar.gz
@@ -771,7 +719,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/mongo-c-driver-debian-packages-i386-${CURRENT_VERSION}.tar.gz
+      remote_file: ${project}/${branch_name}/mongo-c-driver-debian-packages-i386-${CURRENT_VERSION}.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: deb-i386.tar.gz
@@ -780,7 +728,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-debian-packages-i386.tar.gz
+      remote_file: ${project}/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-debian-packages-i386.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: deb-i386.tar.gz
@@ -808,7 +756,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/mongo-c-driver-rpm-packages-${CURRENT_VERSION}.tar.gz
+      remote_file: ${project}/${branch_name}/mongo-c-driver-rpm-packages-${CURRENT_VERSION}.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: rpm.tar.gz
@@ -817,7 +765,7 @@ tasks:
     params:
       aws_key: ${aws_key}
       aws_secret: ${aws_secret}
-      remote_file: mongo-c-driver/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-rpm-packages.tar.gz
+      remote_file: ${project}/${branch_name}/${revision}/${version_id}/${build_id}/${execution}/mongo-c-driver-rpm-packages.tar.gz
       bucket: mciuploads
       permissions: public-read
       local_file: rpm.tar.gz
@@ -1307,7 +1255,7 @@ tasks:
       shell: bash
       script: |-
         set -o errexit
-        env SANITIZE=address SASL=AUTO SSL=OPENSSL EXTRA_CONFIGURE_FLAGS='-DENABLE_EXTRA_ALIGNMENT=OFF' .evergreen/scripts/compile.sh
+        env SANITIZE=address SASL=AUTO SSL=OPENSSL .evergreen/scripts/compile.sh
   - func: run auth tests
     vars:
       ASAN: 'on'
@@ -1571,63 +1519,6 @@ tasks:
         env SASL=OFF SSL=OPENSSL .evergreen/scripts/compile.sh
   - func: run auth tests
   - func: upload-build
-- name: build-and-run-authentication-tests-libressl-2.5
-  commands:
-  - func: install ssl
-    vars:
-      SSL: libressl-2.5.2
-  - func: find-cmake-latest
-  - command: shell.exec
-    type: test
-    params:
-      working_dir: mongoc
-      add_expansions_to_env: true
-      shell: bash
-      script: |-
-        set -o errexit
-        env SASL=OFF SSL=LIBRESSL .evergreen/scripts/compile.sh
-  - func: run auth tests
-    vars:
-      require_tls12: true
-  - func: upload-build
-- name: build-and-run-authentication-tests-libressl-3.0-auto
-  commands:
-  - func: install ssl
-    vars:
-      SSL: libressl-3.0.2
-  - func: find-cmake-latest
-  - command: shell.exec
-    type: test
-    params:
-      working_dir: mongoc
-      add_expansions_to_env: true
-      shell: bash
-      script: |-
-        set -o errexit
-        env SASL=OFF SSL=AUTO .evergreen/scripts/compile.sh
-  - func: run auth tests
-    vars:
-      require_tls12: true
-  - func: upload-build
-- name: build-and-run-authentication-tests-libressl-3.0
-  commands:
-  - func: install ssl
-    vars:
-      SSL: libressl-3.0.2
-  - func: find-cmake-latest
-  - command: shell.exec
-    type: test
-    params:
-      working_dir: mongoc
-      add_expansions_to_env: true
-      shell: bash
-      script: |-
-        set -o errexit
-        env SASL=OFF SSL=LIBRESSL .evergreen/scripts/compile.sh
-  - func: run auth tests
-    vars:
-      require_tls12: true
-  - func: upload-build
 - name: test-latest-server-ipv6-client-ipv6-noauth-nosasl-nossl
   tags:
   - ipv4-ipv6
@@ -16343,11 +16234,8 @@ buildvariants:
   - debug-compile-no-counters
   - compile-tracing
   - link-with-cmake
-  - link-with-cmake-deprecated
   - link-with-cmake-ssl
-  - link-with-cmake-ssl-deprecated
   - link-with-cmake-snappy
-  - link-with-cmake-snappy-deprecated
   - name: link-with-cmake-mac
     distros:
     - macos-14-arm64
@@ -16399,16 +16287,13 @@ buildvariants:
   tags:
   - pr-merge-gate
 - name: openssl
-  display_name: OpenSSL / LibreSSL
+  display_name: OpenSSL
   run_on: archlinux-build
   tasks:
   - build-and-run-authentication-tests-openssl-1.0.1
   - build-and-run-authentication-tests-openssl-1.0.2
   - build-and-run-authentication-tests-openssl-1.1.0
   - build-and-run-authentication-tests-openssl-1.0.1-fips
-  - build-and-run-authentication-tests-libressl-2.5
-  - build-and-run-authentication-tests-libressl-3.0-auto
-  - build-and-run-authentication-tests-libressl-3.0
 - name: clang37
   display_name: clang 3.7 (Archlinux)
   expansions:
@@ -16428,7 +16313,6 @@ buildvariants:
   tasks:
   - release-compile
   - debug-compile-nosasl-nossl
-  - debug-compile-no-align
   - .debug-compile !.sspi .nossl .nosasl
   - .latest .nossl .nosasl
 - name: gcc82rhel
@@ -16472,7 +16356,6 @@ buildvariants:
   tasks:
   - release-compile
   - debug-compile-nosasl-nossl
-  - debug-compile-no-align
   - .latest .nossl .nosasl
 - name: gcc94
   display_name: GCC 9.4 (Ubuntu 20.04)
@@ -16484,7 +16367,6 @@ buildvariants:
   - debug-compile-nosrv
   - release-compile
   - debug-compile-nosasl-nossl
-  - debug-compile-no-align
   - debug-compile-sasl-openssl
   - debug-compile-nosasl-openssl
   - .authentication-tests .openssl
@@ -16504,7 +16386,6 @@ buildvariants:
   - .compression !.snappy
   - release-compile
   - debug-compile-nosasl-nossl
-  - debug-compile-no-align
   - debug-compile-nosrv
   - debug-compile-sasl-darwinssl
   - debug-compile-nosasl-nossl
@@ -16539,11 +16420,14 @@ buildvariants:
     CC: Visual Studio 15 2017 Win64
   run_on: windows-vsCurrent-large
   tasks:
+  - release-compile
   - debug-compile-nosasl-nossl
   - debug-compile-nosasl-openssl
   - debug-compile-sspi-winssl
+  - debug-compile-nosrv
   - .latest .nossl
   - .nosasl .latest .nossl
+  - .compression !.snappy !.zstd !.latest
   - test-dns-winssl
   - test-dns-auth-winssl
   - debug-compile-aws
@@ -16559,13 +16443,6 @@ buildvariants:
   tasks:
   - debug-compile-nosasl-nossl
   - .latest .nossl .nosasl .server
-- name: mingw
-  display_name: MinGW-W64
-  expansions:
-    CC: mingw
-  run_on: windows-vsCurrent-large
-  tasks:
-  - debug-compile-no-align
 - name: rhel8-power
   display_name: Power (ppc64le) (RHEL 8)
   expansions:
@@ -16586,7 +16463,6 @@ buildvariants:
   run_on: ubuntu2004-arm64-large
   tasks:
   - .compression !.snappy !.zstd
-  - debug-compile-no-align
   - release-compile
   - debug-compile-nosasl-nossl
   - debug-compile-nosasl-openssl
@@ -16602,7 +16478,6 @@ buildvariants:
   run_on: rhel8-zseries-large
   tasks:
   - release-compile
-  - debug-compile-no-align
   - debug-compile-nosasl-nossl
   - debug-compile-nosasl-openssl
   - debug-compile-sasl-openssl
diff -pruN 1.30.4-1/.evergreen/generated_configs/tasks.yml 2.0.2-1/.evergreen/generated_configs/tasks.yml
--- 1.30.4-1/.evergreen/generated_configs/tasks.yml	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/generated_configs/tasks.yml	2025-06-19 15:42:22.000000000 +0000
@@ -10,6 +10,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: asan-cse-sasl-cyrus-openssl-debian10-clang-test-4.2-server-auth
     run_on: debian10-small
@@ -23,6 +24,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -45,6 +47,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -64,6 +67,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: asan-cse-sasl-cyrus-openssl-ubuntu2004-clang-test-4.4-replica-auth
     run_on: ubuntu2004-small
@@ -77,6 +81,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -99,6 +104,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -122,6 +128,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -144,6 +151,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -167,6 +175,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -189,6 +198,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -212,6 +222,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -234,6 +245,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -257,6 +269,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -279,6 +292,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -302,6 +316,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -324,6 +339,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -347,6 +363,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -369,6 +386,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -392,6 +410,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -414,6 +433,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -437,6 +457,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -459,6 +480,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -482,6 +504,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -504,6 +527,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -527,6 +551,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -549,6 +574,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -572,6 +598,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -594,6 +621,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -613,6 +641,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: asan-sasl-cyrus-openssl-debian10-clang-test-4.2-replica-auth
     run_on: debian10-small
@@ -626,6 +655,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: replica_set }
@@ -646,6 +676,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -666,6 +697,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -682,6 +714,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: asan-sasl-cyrus-openssl-ubuntu2004-clang-test-4.4-replica-auth
     run_on: ubuntu2004-small
@@ -695,6 +728,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -715,6 +749,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -735,6 +770,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -755,6 +791,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -775,6 +812,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -795,6 +833,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -815,6 +854,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -835,6 +875,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -855,6 +896,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -875,6 +917,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -895,6 +938,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -915,6 +959,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -935,6 +980,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -955,6 +1001,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -975,6 +1022,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -995,6 +1043,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -1015,6 +1064,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -1035,6 +1085,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -1046,93 +1097,13 @@ tasks:
   - name: check-headers
     commands:
       - func: check-headers
-  - name: "check:sasl=Cyrus\_\u2022\_tls=LibreSSL\_\u2022\_test_mongocxx_ref=r3.8.0"
-    run_on:
-      - ubuntu2204-large
-      - debian10-large
-      - debian11-large
-      - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc]
-    commands:
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: bash
-          args:
-            - -c
-            - docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +env-warmup
-            - --sasl=Cyrus
-            - --tls=LibreSSL
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-      - command: subprocess.exec
-        type: test
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=LibreSSL
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=Cyrus\_\u2022\_tls=LibreSSL\_\u2022\_test_mongocxx_ref=r3.9.0"
-    run_on:
-      - ubuntu2204-large
-      - debian10-large
-      - debian11-large
-      - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc]
-    commands:
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: bash
-          args:
-            - -c
-            - docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +env-warmup
-            - --sasl=Cyrus
-            - --tls=LibreSSL
-            - --test_mongocxx_ref=r3.9.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-      - command: subprocess.exec
-        type: test
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=LibreSSL
-            - --test_mongocxx_ref=r3.9.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
   - name: "check:sasl=Cyrus\_\u2022\_tls=OpenSSL\_\u2022\_test_mongocxx_ref=none"
     run_on:
       - ubuntu2204-large
       - debian10-large
       - debian11-large
       - amazon2
-    tags: [earthly, pr-merge-gate, centos7-clang, centos7-gcc, u16-clang, u16-gcc]
+    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, centos7-clang, centos7-gcc, u16-clang, u16-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
     commands:
       - command: subprocess.exec
         type: setup
@@ -1166,93 +1137,13 @@ tasks:
             - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=Cyrus\_\u2022\_tls=OpenSSL\_\u2022\_test_mongocxx_ref=r3.8.0"
-    run_on:
-      - ubuntu2204-large
-      - debian10-large
-      - debian11-large
-      - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, u18-clang, u20-clang, u20-gcc, u22-clang, u22-gcc]
-    commands:
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: bash
-          args:
-            - -c
-            - docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +env-warmup
-            - --sasl=Cyrus
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-      - command: subprocess.exec
-        type: test
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=Cyrus\_\u2022\_tls=OpenSSL\_\u2022\_test_mongocxx_ref=r3.9.0"
-    run_on:
-      - ubuntu2204-large
-      - debian10-large
-      - debian11-large
-      - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
-    commands:
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: bash
-          args:
-            - -c
-            - docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +env-warmup
-            - --sasl=Cyrus
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.9.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-      - command: subprocess.exec
-        type: test
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.9.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
   - name: "check:sasl=Cyrus\_\u2022\_tls=off\_\u2022\_test_mongocxx_ref=none"
     run_on:
       - ubuntu2204-large
       - debian10-large
       - debian11-large
       - amazon2
-    tags: [earthly, pr-merge-gate, centos7-clang, centos7-gcc, u16-clang, u16-gcc]
+    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, centos7-clang, centos7-gcc, u16-clang, u16-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
     commands:
       - command: subprocess.exec
         type: setup
@@ -1286,13 +1177,13 @@ tasks:
             - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=Cyrus\_\u2022\_tls=off\_\u2022\_test_mongocxx_ref=r3.8.0"
+  - name: "check:sasl=off\_\u2022\_tls=OpenSSL\_\u2022\_test_mongocxx_ref=none"
     run_on:
       - ubuntu2204-large
       - debian10-large
       - debian11-large
       - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, u18-clang, u20-clang, u20-gcc, u22-clang, u22-gcc]
+    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, centos7-clang, centos7-gcc, u16-clang, u16-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
     commands:
       - command: subprocess.exec
         type: setup
@@ -1308,49 +1199,9 @@ tasks:
           working_dir: mongoc
           args:
             - +env-warmup
-            - --sasl=Cyrus
-            - --tls=off
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-      - command: subprocess.exec
-        type: test
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=off
-            - --test_mongocxx_ref=r3.8.0
-            - --env=${MONGOC_EARTHLY_ENV}
-            - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=Cyrus\_\u2022\_tls=off\_\u2022\_test_mongocxx_ref=r3.9.0"
-    run_on:
-      - ubuntu2204-large
-      - debian10-large
-      - debian11-large
-      - amazon2
-    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
-    commands:
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: bash
-          args:
-            - -c
-            - docker login -u "${artifactory_username}" --password-stdin artifactory.corp.mongodb.com <<<"${artifactory_password}"
-      - command: subprocess.exec
-        type: setup
-        params:
-          binary: ./tools/earthly.sh
-          working_dir: mongoc
-          args:
-            - +env-warmup
-            - --sasl=Cyrus
-            - --tls=off
-            - --test_mongocxx_ref=r3.9.0
+            - --sasl=off
+            - --tls=OpenSSL
+            - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
       - command: subprocess.exec
@@ -1360,19 +1211,19 @@ tasks:
           working_dir: mongoc
           args:
             - +run
-            - --targets=test-example test-cxx-driver
-            - --sasl=Cyrus
-            - --tls=off
-            - --test_mongocxx_ref=r3.9.0
+            - --targets=test-example
+            - --sasl=off
+            - --tls=OpenSSL
+            - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
-  - name: "check:sasl=off\_\u2022\_tls=OpenSSL\_\u2022\_test_mongocxx_ref=r3.8.0"
+  - name: "check:sasl=off\_\u2022\_tls=off\_\u2022\_test_mongocxx_ref=none"
     run_on:
       - ubuntu2204-large
       - debian10-large
       - debian11-large
       - amazon2
-    tags: [earthly, pr-merge-gate, u22-gcc]
+    tags: [earthly, pr-merge-gate, alpine3.16-clang, alpine3.16-gcc, alpine3.17-clang, alpine3.17-gcc, alpine3.18-clang, alpine3.18-gcc, alpine3.19-clang, alpine3.19-gcc, archlinux-clang, archlinux-gcc, centos7-clang, centos7-gcc, u16-clang, u16-gcc, u18-clang, u18-gcc, u20-clang, u20-gcc, u22-clang, u22-gcc]
     commands:
       - command: subprocess.exec
         type: setup
@@ -1389,8 +1240,8 @@ tasks:
           args:
             - +env-warmup
             - --sasl=off
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.8.0
+            - --tls=off
+            - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
       - command: subprocess.exec
@@ -1400,10 +1251,10 @@ tasks:
           working_dir: mongoc
           args:
             - +run
-            - --targets=test-example test-cxx-driver
+            - --targets=test-example
             - --sasl=off
-            - --tls=OpenSSL
-            - --test_mongocxx_ref=r3.8.0
+            - --tls=off
+            - --test_mongocxx_ref=none
             - --env=${MONGOC_EARTHLY_ENV}
             - --c_compiler=${MONGOC_EARTHLY_C_COMPILER}
   - name: clang-format
@@ -1418,6 +1269,7 @@ tasks:
       - func: cse-sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-darwinssl-macos-11-arm64-clang-test-6.0-server-auth
     run_on: macos-11-arm64
@@ -1431,6 +1283,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -1447,6 +1300,7 @@ tasks:
       - func: cse-sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-darwinssl-macos-14-arm64-clang-test-6.0-server-auth
     run_on: macos-14-arm64
@@ -1460,6 +1314,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -1480,6 +1335,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1500,6 +1356,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -1520,6 +1377,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1540,6 +1398,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -1560,6 +1419,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -1580,6 +1440,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -1596,6 +1457,7 @@ tasks:
       - func: cse-sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-darwinssl-macos-14-clang-test-4.2-server-auth
     run_on: macos-14
@@ -1609,6 +1471,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -1629,6 +1492,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -1649,6 +1513,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -1665,6 +1530,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-debian10-gcc-compile
     run_on: debian10-large
@@ -1674,6 +1540,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-debian10-gcc-test-4.2-replica-auth
     run_on: debian10-small
@@ -1687,6 +1554,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1707,6 +1575,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -1723,6 +1592,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-debian11-gcc-compile
     run_on: debian11-large
@@ -1732,6 +1602,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-debian92-clang-compile
     run_on: debian92-large
@@ -1741,6 +1612,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-debian92-gcc-compile
     run_on: debian92-large
@@ -1750,6 +1622,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-rhel8-zseries-gcc-compile
     run_on: rhel8-zseries-large
@@ -1760,6 +1633,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-rhel8-zseries-gcc-test-5.0-server-auth
     run_on: rhel8-zseries-small
@@ -1774,6 +1648,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -1795,6 +1670,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1816,6 +1692,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -1837,6 +1714,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1858,6 +1736,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -1879,6 +1758,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -1900,6 +1780,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -1916,6 +1797,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-ubuntu2004-arm64-gcc-compile
     run_on: ubuntu2004-arm64-large
@@ -1925,6 +1807,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-ubuntu2004-arm64-gcc-test-4.4-replica-auth
     run_on: ubuntu2004-arm64-small
@@ -1938,6 +1821,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1958,6 +1842,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -1978,6 +1863,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -1998,6 +1884,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -2018,6 +1905,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2038,6 +1926,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -2058,6 +1947,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2078,6 +1968,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -2098,6 +1989,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2118,6 +2010,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -2138,6 +2031,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -2158,6 +2052,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -2174,6 +2069,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-ubuntu2004-gcc-compile
     run_on: ubuntu2004-large
@@ -2183,6 +2079,7 @@ tasks:
       - func: cse-sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-ubuntu2004-gcc-test-4.4-replica-auth
     run_on: ubuntu2004-small
@@ -2196,6 +2093,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2216,6 +2114,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -2236,6 +2135,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2256,6 +2156,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -2276,6 +2177,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2296,6 +2198,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -2316,6 +2219,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2336,6 +2240,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -2356,6 +2261,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2376,6 +2282,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -2396,6 +2303,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -2416,6 +2324,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -2431,7 +2340,8 @@ tasks:
       - func: find-cmake-latest
       - func: cse-sasl-cyrus-openssl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
   - name: cse-sasl-cyrus-openssl-windows-2019-vs2017-x64-test-4.2-server-auth
     run_on: windows-vsCurrent-small
@@ -2444,7 +2354,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -2464,7 +2375,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -2484,7 +2396,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -2504,7 +2417,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -2524,7 +2438,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2544,7 +2459,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -2564,7 +2480,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2584,7 +2501,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -2604,7 +2522,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -2624,7 +2543,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -2640,7 +2560,8 @@ tasks:
       - func: find-cmake-latest
       - func: cse-sasl-cyrus-winssl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
   - name: cse-sasl-cyrus-winssl-windows-2019-vs2017-x64-test-4.2-server-auth
     run_on: windows-vsCurrent-small
@@ -2653,7 +2574,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -2673,7 +2595,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -2693,7 +2616,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -2713,7 +2637,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -2733,7 +2658,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2753,7 +2679,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -2773,7 +2700,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -2793,7 +2721,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -2813,7 +2742,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -2833,7 +2763,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -2858,7 +2789,6 @@ tasks:
           env:
             CC: gcc
             CFLAGS: -fno-omit-frame-pointer
-            EXTRA_CONFIGURE_FLAGS: -DENABLE_EXTRA_ALIGNMENT=OFF
             SSL: OPENSSL
           args:
             - -c
@@ -3161,6 +3091,7 @@ tasks:
       - func: openssl-static-compile
         vars:
           CC: gcc
+          CXX: g++
   - name: openssl-static-compile-debian11-gcc
     run_on: debian11-large
     tags: [openssl-static-matrix, debian11, gcc]
@@ -3169,6 +3100,7 @@ tasks:
       - func: openssl-static-compile
         vars:
           CC: gcc
+          CXX: g++
   - name: openssl-static-compile-debian92-gcc
     run_on: debian92-large
     tags: [openssl-static-matrix, debian92, gcc]
@@ -3177,6 +3109,7 @@ tasks:
       - func: openssl-static-compile
         vars:
           CC: gcc
+          CXX: g++
   - name: openssl-static-compile-ubuntu2004-gcc
     run_on: ubuntu2004-large
     tags: [openssl-static-matrix, ubuntu2004, gcc]
@@ -3185,6 +3118,7 @@ tasks:
       - func: openssl-static-compile
         vars:
           CC: gcc
+          CXX: g++
   - name: sasl-cyrus-darwinssl-macos-11-arm64-clang-compile
     run_on: macos-11-arm64
     tags: [sasl-matrix-darwinssl, compile, macos-11-arm64, clang, sasl-cyrus]
@@ -3193,6 +3127,7 @@ tasks:
       - func: sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: sasl-cyrus-darwinssl-macos-11-arm64-clang-test-6.0-server-auth
     run_on: macos-11-arm64
@@ -3206,6 +3141,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3226,6 +3162,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -3242,6 +3179,7 @@ tasks:
       - func: sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: sasl-cyrus-darwinssl-macos-14-arm64-clang-test-6.0-server-auth
     run_on: macos-14-arm64
@@ -3255,6 +3193,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3275,6 +3214,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -3295,6 +3235,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -3315,6 +3256,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -3331,6 +3273,7 @@ tasks:
       - func: sasl-cyrus-darwinssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: sasl-cyrus-darwinssl-macos-14-clang-test-4.0-server-auth
     run_on: macos-14
@@ -3344,6 +3287,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.0" }
             - { key: TOPOLOGY, value: server }
@@ -3364,6 +3308,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -3384,6 +3329,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -3404,6 +3350,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -3412,6 +3359,79 @@ tasks:
       - func: bootstrap-mongo-orchestration
       - func: run-simple-http-server
       - func: run-tests
+  - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile
+    run_on: amazon2023-arm64-latest-large-m8g
+    tags: [sasl-matrix-openssl, compile, amazon2023-arm64-latest-large-m8g, gcc, sasl-cyrus]
+    commands:
+      - func: find-cmake-latest
+      - func: sasl-cyrus-openssl-compile
+        vars:
+          CC: gcc
+          CXX: g++
+      - func: upload-build
+  - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-replica-auth
+    run_on: amazon2023-arm64-latest-large-m8g
+    tags: [sasl-matrix-openssl, test, amazon2023-arm64-latest-large-m8g, gcc, sasl-cyrus, auth, replica, latest, openssl]
+    depends_on: [{ name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: latest }
+            - { key: TOPOLOGY, value: replica_set }
+            - { key: SSL, value: openssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-server-auth
+    run_on: amazon2023-arm64-latest-large-m8g
+    tags: [sasl-matrix-openssl, test, amazon2023-arm64-latest-large-m8g, gcc, sasl-cyrus, auth, server, latest, openssl]
+    depends_on: [{ name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: latest }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: openssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-sharded-auth
+    run_on: amazon2023-arm64-latest-large-m8g
+    tags: [sasl-matrix-openssl, test, amazon2023-arm64-latest-large-m8g, gcc, sasl-cyrus, auth, sharded, latest, openssl]
+    depends_on: [{ name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: latest }
+            - { key: TOPOLOGY, value: sharded_cluster }
+            - { key: SSL, value: openssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
   - name: sasl-cyrus-openssl-debian10-gcc-compile
     run_on: debian10-large
     tags: [sasl-matrix-openssl, compile, debian10, gcc, sasl-cyrus]
@@ -3420,6 +3440,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-debian10-gcc-test-4.2-replica-auth
     run_on: debian10-small
@@ -3433,6 +3454,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: replica_set }
@@ -3453,6 +3475,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -3469,6 +3492,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-debian92-clang-compile
     run_on: debian92-large
@@ -3478,6 +3502,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: sasl-cyrus-openssl-debian92-gcc-compile
     run_on: debian92-large
@@ -3487,6 +3512,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-rhel8-power-gcc-compile
     run_on: rhel8-power-large
@@ -3497,6 +3523,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-rhel8-power-gcc-test-4.2-server-auth
     run_on: rhel8-power-small
@@ -3511,6 +3538,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -3532,6 +3560,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -3553,6 +3582,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -3574,6 +3604,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3595,6 +3626,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -3616,6 +3648,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -3637,6 +3670,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -3654,6 +3688,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-rhel8-zseries-gcc-test-5.0-server-auth
     run_on: rhel8-zseries-small
@@ -3668,6 +3703,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -3689,6 +3725,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3710,6 +3747,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -3731,6 +3769,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -3752,6 +3791,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -3768,6 +3808,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-ubuntu2004-arm64-gcc-compile
     run_on: ubuntu2004-arm64-large
@@ -3777,6 +3818,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-ubuntu2004-arm64-gcc-test-4.4-server-auth
     run_on: ubuntu2004-arm64-small
@@ -3790,6 +3832,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -3810,6 +3853,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -3830,6 +3874,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3850,6 +3895,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -3870,6 +3916,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -3890,6 +3937,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -3906,6 +3954,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: sasl-cyrus-openssl-ubuntu2004-gcc-compile
     run_on: ubuntu2004-large
@@ -3915,6 +3964,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-cyrus-openssl-ubuntu2004-gcc-test-4.4-server-auth
     run_on: ubuntu2004-small
@@ -3928,6 +3978,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -3948,6 +3999,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -3968,6 +4020,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -3988,6 +4041,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -4008,6 +4062,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -4028,6 +4083,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4043,7 +4099,8 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-cyrus-openssl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
   - name: sasl-cyrus-openssl-windows-2019-vs2017-x64-test-latest-server-auth
     run_on: windows-vsCurrent-small
@@ -4056,7 +4113,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4065,175 +4123,6 @@ tasks:
       - func: bootstrap-mongo-orchestration
       - func: run-simple-http-server
       - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-    run_on: windows-vsCurrent-large
-    tags: [sasl-matrix-winssl, compile, windows-vsCurrent, vs2017x64, sasl-cyrus]
-    commands:
-      - func: find-cmake-latest
-      - func: sasl-cyrus-winssl-compile
-        vars:
-          CC: Visual Studio 15 2017 Win64
-      - func: upload-build
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-4.0-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "4.0", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "4.0" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-4.2-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "4.2", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "4.2" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-4.4-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "4.4", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "4.4" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-5.0-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "5.0", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "5.0" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-6.0-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "6.0", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "6.0" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-7.0-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "7.0", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "7.0" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-8.0-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, "8.0", winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: "8.0" }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
-  - name: sasl-cyrus-winssl-windows-2019-vs2017-x64-test-latest-server-auth
-    run_on: windows-vsCurrent-small
-    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-cyrus, auth, server, latest, winssl]
-    depends_on: [{ name: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile }]
-    commands:
-      - func: fetch-build
-        vars:
-          BUILD_NAME: sasl-cyrus-winssl-windows-2019-vs2017-x64-compile
-      - command: expansions.update
-        params:
-          updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
-            - { key: AUTH, value: auth }
-            - { key: MONGODB_VERSION, value: latest }
-            - { key: TOPOLOGY, value: server }
-            - { key: SSL, value: winssl }
-      - func: fetch-det
-      - func: bootstrap-mongo-orchestration
-      - func: run-simple-http-server
-      - func: run-tests
   - name: sasl-off-nossl-debian10-gcc-compile
     run_on: debian10-large
     tags: [sasl-matrix-nossl, compile, debian10, gcc, sasl-off]
@@ -4242,6 +4131,7 @@ tasks:
       - func: sasl-off-nossl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-off-nossl-debian10-gcc-test-4.2-replica-noauth
     run_on: debian10-small
@@ -4255,6 +4145,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4275,6 +4166,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -4295,6 +4187,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4311,6 +4204,7 @@ tasks:
       - func: sasl-off-nossl-compile
         vars:
           CC: gcc
+          CXX: g++
       - func: upload-build
   - name: sasl-off-nossl-ubuntu2004-gcc-test-4.4-replica-noauth
     run_on: ubuntu2004-small
@@ -4324,6 +4218,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4344,6 +4239,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -4364,6 +4260,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4384,6 +4281,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4404,6 +4302,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -4424,6 +4323,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4444,6 +4344,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4464,6 +4365,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -4484,6 +4386,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4504,6 +4407,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4524,6 +4428,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -4544,6 +4449,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4564,6 +4470,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -4584,6 +4491,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -4604,6 +4512,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4624,6 +4533,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -4644,6 +4554,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4664,6 +4575,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: gcc }
+            - { key: CXX, value: g++ }
             - { key: AUTH, value: noauth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -4679,7 +4591,8 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-off-nossl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
   - name: sasl-off-winssl-windows-2019-vs2017-x64-compile
     run_on: windows-vsCurrent-large
@@ -4688,7 +4601,8 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-off-winssl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
   - name: sasl-off-winssl-windows-2019-vs2017-x86-compile
     run_on: windows-vsCurrent-large
@@ -4697,7 +4611,8 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-off-winssl-compile
         vars:
-          CC: Visual Studio 15 2017
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: Win32
       - func: upload-build
   - name: sasl-sspi-winssl-windows-2019-mingw-compile
     run_on: windows-vsCurrent-large
@@ -4707,6 +4622,7 @@ tasks:
       - func: sasl-sspi-winssl-compile
         vars:
           CC: mingw
+          CXX: mingw
       - func: upload-build
   - name: sasl-sspi-winssl-windows-2019-mingw-test-8.0-server-auth
     run_on: windows-vsCurrent-small
@@ -4720,6 +4636,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: mingw }
+            - { key: CXX, value: mingw }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -4740,6 +4657,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: mingw }
+            - { key: CXX, value: mingw }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4755,8 +4673,135 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-sspi-winssl-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
       - func: upload-build
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-4.0-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "4.0", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "4.0" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-4.2-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "4.2", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "4.2" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-4.4-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "4.4", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "4.4" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-5.0-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "5.0", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "5.0" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-6.0-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "6.0", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "6.0" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
+  - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-7.0-server-auth
+    run_on: windows-vsCurrent-small
+    tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "7.0", winssl]
+    depends_on: [{ name: sasl-sspi-winssl-windows-2019-vs2017-x64-compile }]
+    commands:
+      - func: fetch-build
+        vars:
+          BUILD_NAME: sasl-sspi-winssl-windows-2019-vs2017-x64-compile
+      - command: expansions.update
+        params:
+          updates:
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
+            - { key: AUTH, value: auth }
+            - { key: MONGODB_VERSION, value: "7.0" }
+            - { key: TOPOLOGY, value: server }
+            - { key: SSL, value: winssl }
+      - func: fetch-det
+      - func: bootstrap-mongo-orchestration
+      - func: run-simple-http-server
+      - func: run-tests
   - name: sasl-sspi-winssl-windows-2019-vs2017-x64-test-8.0-server-auth
     run_on: windows-vsCurrent-small
     tags: [sasl-matrix-winssl, test, windows-vsCurrent, vs2017x64, sasl-sspi, auth, server, "8.0", winssl]
@@ -4768,7 +4813,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -4788,7 +4834,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 Win64 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: x64 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4804,7 +4851,8 @@ tasks:
       - func: find-cmake-latest
       - func: sasl-sspi-winssl-compile
         vars:
-          CC: Visual Studio 15 2017
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: Win32
       - func: upload-build
   - name: sasl-sspi-winssl-windows-2019-vs2017-x86-test-8.0-server-auth
     run_on: windows-vsCurrent-small
@@ -4817,7 +4865,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: Win32 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -4837,7 +4886,8 @@ tasks:
       - command: expansions.update
         params:
           updates:
-            - { key: CC, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR, value: Visual Studio 15 2017 }
+            - { key: CMAKE_GENERATOR_PLATFORM, value: Win32 }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -4859,6 +4909,7 @@ tasks:
       - func: scan-build
         vars:
           CC: clang
+          CXX: clang++
       - func: upload scan artifacts
   - name: scan-build-ubuntu2004-arm64-clang
     run_on: ubuntu2004-arm64-large
@@ -4868,6 +4919,7 @@ tasks:
       - func: scan-build
         vars:
           CC: clang
+          CXX: clang++
       - func: upload scan artifacts
   - name: scan-build-ubuntu2004-clang-i686
     run_on: ubuntu2004-large
@@ -4877,52 +4929,178 @@ tasks:
       - func: scan-build
         vars:
           CC: clang
+          CXX: clang++
           MARCH: i686
       - func: upload scan artifacts
-  - name: std-c11-debian10-clang-compile
+  - name: std-c11-debian10-gcc-compile
     run_on: debian10-large
-    tags: [std-matrix, debian10, clang, compile, std-c11]
+    tags: [std-matrix, debian10, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-8
+          CXX: g++-8
+          C_STD_VERSION: 11
+  - name: std-c11-debian11-gcc-compile
+    run_on: debian11-large
+    tags: [std-matrix, debian11, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-10
+          CXX: g++-10
+          C_STD_VERSION: 11
+  - name: std-c11-rhel76-gcc-compile
+    run_on: rhel76-large
+    tags: [std-matrix, rhel76, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel80-clang-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, clang, compile, std-c11]
     commands:
       - func: find-cmake-latest
       - func: std-compile
         vars:
           CC: clang
+          CXX: clang++
           C_STD_VERSION: 11
-  - name: std-c11-debian10-gcc-compile
-    run_on: debian10-large
-    tags: [std-matrix, debian10, gcc, compile, std-c11]
+  - name: std-c11-rhel80-gcc-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, gcc, compile, std-c11]
     commands:
       - func: find-cmake-latest
       - func: std-compile
         vars:
           CC: gcc
+          CXX: g++
           C_STD_VERSION: 11
-  - name: std-c11-debian11-clang-compile
-    run_on: debian11-large
-    tags: [std-matrix, debian11, clang, compile, std-c11]
+  - name: std-c11-rhel84-clang-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, clang, compile, std-c11]
     commands:
       - func: find-cmake-latest
       - func: std-compile
         vars:
           CC: clang
+          CXX: clang++
           C_STD_VERSION: 11
-  - name: std-c11-debian11-gcc-compile
-    run_on: debian11-large
-    tags: [std-matrix, debian11, gcc, compile, std-c11]
+  - name: std-c11-rhel84-gcc-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, gcc, compile, std-c11]
     commands:
       - func: find-cmake-latest
       - func: std-compile
         vars:
           CC: gcc
+          CXX: g++
           C_STD_VERSION: 11
-  - name: std-c11-debian92-clang-compile
-    run_on: debian92-large
-    tags: [std-matrix, debian92, clang, compile, std-c11]
+  - name: std-c11-rhel90-clang-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel90-gcc-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel91-clang-compile
+    run_on: rhel91-large
+    tags: [std-matrix, rhel91, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel92-clang-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel92-gcc-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel93-clang-compile
+    run_on: rhel93-large
+    tags: [std-matrix, rhel93, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel94-clang-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel94-gcc-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel95-clang-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, clang, compile, std-c11]
     commands:
       - func: find-cmake-latest
       - func: std-compile
         vars:
           CC: clang
+          CXX: clang++
+          C_STD_VERSION: 11
+  - name: std-c11-rhel95-gcc-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, gcc, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
           C_STD_VERSION: 11
   - name: std-c11-ubuntu2004-clang-compile
     run_on: ubuntu2004-large
@@ -4931,7 +5109,8 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
-          CC: clang
+          CC: clang-10
+          CXX: clang++-10
           C_STD_VERSION: 11
   - name: std-c11-ubuntu2004-gcc-compile
     run_on: ubuntu2004-large
@@ -4940,7 +5119,18 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
-          CC: gcc
+          CC: gcc-9
+          CXX: g++-9
+          C_STD_VERSION: 11
+  - name: std-c11-ubuntu2204-clang-compile
+    run_on: ubuntu2204-large
+    tags: [std-matrix, ubuntu2204, clang, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-12
+          CXX: clang++-12
           C_STD_VERSION: 11
   - name: std-c11-windows-2019-vs2017-x64-compile
     run_on: windows-vsCurrent-large
@@ -4949,7 +5139,28 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 11
+  - name: std-c11-windows-2019-vs2019-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2019x64, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 16 2019
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 11
+  - name: std-c11-windows-2019-vs2022-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2022x64, compile, std-c11]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 17 2022
+          CMAKE_GENERATOR_PLATFORM: x64
           C_STD_VERSION: 11
   - name: std-c17-debian10-gcc-compile
     run_on: debian10-large
@@ -4958,7 +5169,8 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
-          CC: gcc
+          CC: gcc-8
+          CXX: g++-8
           C_STD_VERSION: 17
   - name: std-c17-debian11-gcc-compile
     run_on: debian11-large
@@ -4967,7 +5179,178 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
+          CC: gcc-10
+          CXX: g++-10
+          C_STD_VERSION: 17
+  - name: std-c17-rhel80-clang-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel80-gcc-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel84-clang-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel84-gcc-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel90-clang-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel90-gcc-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
           CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel91-clang-compile
+    run_on: rhel91-large
+    tags: [std-matrix, rhel91, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel92-clang-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel92-gcc-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel93-clang-compile
+    run_on: rhel93-large
+    tags: [std-matrix, rhel93, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel94-clang-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel94-gcc-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel95-clang-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 17
+  - name: std-c17-rhel95-gcc-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 17
+  - name: std-c17-ubuntu2004-clang-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-10
+          CXX: clang++-10
+          C_STD_VERSION: 17
+  - name: std-c17-ubuntu2004-gcc-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, gcc, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-9
+          CXX: g++-9
+          C_STD_VERSION: 17
+  - name: std-c17-ubuntu2204-clang-compile
+    run_on: ubuntu2204-large
+    tags: [std-matrix, ubuntu2204, clang, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-12
+          CXX: clang++-12
           C_STD_VERSION: 17
   - name: std-c17-windows-2019-vs2017-x64-compile
     run_on: windows-vsCurrent-large
@@ -4976,8 +5359,439 @@ tasks:
       - func: find-cmake-latest
       - func: std-compile
         vars:
-          CC: Visual Studio 15 2017 Win64
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 17
+  - name: std-c17-windows-2019-vs2019-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2019x64, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 16 2019
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 17
+  - name: std-c17-windows-2019-vs2022-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2022x64, compile, std-c17]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 17 2022
+          CMAKE_GENERATOR_PLATFORM: x64
           C_STD_VERSION: 17
+  - name: std-c23-debian11-gcc-compile
+    run_on: debian11-large
+    tags: [std-matrix, debian11, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-10
+          CXX: g++-10
+          C_STD_VERSION: 23
+  - name: std-c23-rhel84-clang-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel90-clang-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel90-gcc-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel91-clang-compile
+    run_on: rhel91-large
+    tags: [std-matrix, rhel91, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel92-clang-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel92-gcc-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel93-clang-compile
+    run_on: rhel93-large
+    tags: [std-matrix, rhel93, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel94-clang-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel94-gcc-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel95-clang-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 23
+  - name: std-c23-rhel95-gcc-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 23
+  - name: std-c23-ubuntu2004-clang-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-10
+          CXX: clang++-10
+          C_STD_VERSION: 23
+  - name: std-c23-ubuntu2004-gcc-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, gcc, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-9
+          CXX: g++-9
+          C_STD_VERSION: 23
+  - name: std-c23-ubuntu2204-clang-compile
+    run_on: ubuntu2204-large
+    tags: [std-matrix, ubuntu2204, clang, compile, std-c23]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-12
+          CXX: clang++-12
+          C_STD_VERSION: 23
+  - name: std-c99-debian10-gcc-compile
+    run_on: debian10-large
+    tags: [std-matrix, debian10, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-8
+          CXX: g++-8
+          C_STD_VERSION: 99
+  - name: std-c99-debian11-gcc-compile
+    run_on: debian11-large
+    tags: [std-matrix, debian11, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-10
+          CXX: g++-10
+          C_STD_VERSION: 99
+  - name: std-c99-rhel76-gcc-compile
+    run_on: rhel76-large
+    tags: [std-matrix, rhel76, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel80-clang-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel80-gcc-compile
+    run_on: rhel80-large
+    tags: [std-matrix, rhel80, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel84-clang-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel84-gcc-compile
+    run_on: rhel84-large
+    tags: [std-matrix, rhel84, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel90-clang-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel90-gcc-compile
+    run_on: rhel90-large
+    tags: [std-matrix, rhel90, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel91-clang-compile
+    run_on: rhel91-large
+    tags: [std-matrix, rhel91, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel92-clang-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel92-gcc-compile
+    run_on: rhel92-large
+    tags: [std-matrix, rhel92, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel93-clang-compile
+    run_on: rhel93-large
+    tags: [std-matrix, rhel93, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel94-clang-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel94-gcc-compile
+    run_on: rhel94-large
+    tags: [std-matrix, rhel94, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel95-clang-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang
+          CXX: clang++
+          C_STD_VERSION: 99
+  - name: std-c99-rhel95-gcc-compile
+    run_on: rhel95-large
+    tags: [std-matrix, rhel95, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc
+          CXX: g++
+          C_STD_VERSION: 99
+  - name: std-c99-ubuntu2004-clang-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-10
+          CXX: clang++-10
+          C_STD_VERSION: 99
+  - name: std-c99-ubuntu2004-gcc-compile
+    run_on: ubuntu2004-large
+    tags: [std-matrix, ubuntu2004, gcc, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: gcc-9
+          CXX: g++-9
+          C_STD_VERSION: 99
+  - name: std-c99-ubuntu2204-clang-compile
+    run_on: ubuntu2204-large
+    tags: [std-matrix, ubuntu2204, clang, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CC: clang-12
+          CXX: clang++-12
+          C_STD_VERSION: 99
+  - name: std-c99-windows-2019-vs2017-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2017x64, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 99
+  - name: std-c99-windows-2019-vs2019-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2019x64, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 16 2019
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 99
+  - name: std-c99-windows-2019-vs2022-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2022x64, compile, std-c99]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 17 2022
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: 99
+  - name: std-clatest-windows-2019-vs2017-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2017x64, compile, std-clatest]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 15 2017
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: latest
+  - name: std-clatest-windows-2019-vs2019-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2019x64, compile, std-clatest]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 16 2019
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: latest
+  - name: std-clatest-windows-2019-vs2022-x64-compile
+    run_on: windows-vsCurrent-large
+    tags: [std-matrix, windows-vsCurrent, vs2022x64, compile, std-clatest]
+    commands:
+      - func: find-cmake-latest
+      - func: std-compile
+        vars:
+          CMAKE_GENERATOR: Visual Studio 17 2022
+          CMAKE_GENERATOR_PLATFORM: x64
+          C_STD_VERSION: latest
   - name: tsan-sasl-cyrus-openssl-debian10-clang-compile
     run_on: debian10-large
     tags: [sanitizers-matrix-tsan, compile, debian10, clang, tsan, sasl-cyrus]
@@ -4986,6 +5800,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: tsan-sasl-cyrus-openssl-debian10-clang-test-4.2-replica-auth
     run_on: debian10-small
@@ -4999,6 +5814,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5019,6 +5835,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: server }
@@ -5039,6 +5856,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.2" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5055,6 +5873,7 @@ tasks:
       - func: sasl-cyrus-openssl-compile
         vars:
           CC: clang
+          CXX: clang++
       - func: upload-build
   - name: tsan-sasl-cyrus-openssl-ubuntu2004-clang-test-4.4-replica-auth
     run_on: ubuntu2004-small
@@ -5068,6 +5887,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5088,6 +5908,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: server }
@@ -5108,6 +5929,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "4.4" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5128,6 +5950,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5148,6 +5971,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: server }
@@ -5168,6 +5992,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "5.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5188,6 +6013,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5208,6 +6034,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: server }
@@ -5228,6 +6055,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "6.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5248,6 +6076,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5268,6 +6097,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: server }
@@ -5288,6 +6118,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "7.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5308,6 +6139,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: replica_set }
@@ -5328,6 +6160,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: server }
@@ -5348,6 +6181,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: "8.0" }
             - { key: TOPOLOGY, value: sharded_cluster }
@@ -5368,6 +6202,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: replica_set }
@@ -5388,6 +6223,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: server }
@@ -5408,6 +6244,7 @@ tasks:
         params:
           updates:
             - { key: CC, value: clang }
+            - { key: CXX, value: clang++ }
             - { key: AUTH, value: auth }
             - { key: MONGODB_VERSION, value: latest }
             - { key: TOPOLOGY, value: sharded_cluster }
diff -pruN 1.30.4-1/.evergreen/generated_configs/variants.yml 2.0.2-1/.evergreen/generated_configs/variants.yml
--- 1.30.4-1/.evergreen/generated_configs/variants.yml	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/generated_configs/variants.yml	2025-06-19 15:42:22.000000000 +0000
@@ -180,7 +180,6 @@ buildvariants:
       ASAN: "on"
       CC: gcc
       CFLAGS: -fno-omit-frame-pointer
-      EXTRA_CONFIGURE_FLAGS: -DENABLE_EXTRA_ALIGNMENT=OFF
       SANITIZE: address,undefined
     tasks:
       - name: mock-server-test
@@ -194,7 +193,6 @@ buildvariants:
       ASAN: "on"
       CFLAGS: -fno-omit-frame-pointer
       CHECK_LOG: "ON"
-      EXTRA_CONFIGURE_FLAGS: -DENABLE_EXTRA_ALIGNMENT=OFF
       SANITIZE: address,undefined
     tasks:
       - name: .sanitizers-matrix-asan
@@ -203,7 +201,7 @@ buildvariants:
     expansions:
       CFLAGS: -fno-omit-frame-pointer
       CHECK_LOG: "ON"
-      EXTRA_CONFIGURE_FLAGS: -DENABLE_EXTRA_ALIGNMENT=OFF -DENABLE_SHM_COUNTERS=OFF
+      EXTRA_CONFIGURE_FLAGS: -DENABLE_SHM_COUNTERS=OFF
       SANITIZE: thread
     tasks:
       - name: .sanitizers-matrix-tsan
@@ -234,6 +232,7 @@ buildvariants:
       - name: sasl-cyrus-openssl-ubuntu2004-arm64-gcc-compile
       - name: sasl-cyrus-openssl-ubuntu2004-gcc-compile
       - name: sasl-cyrus-openssl-windows-2019-vs2017-x64-compile
+      - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-compile
       - name: sasl-cyrus-openssl-rhel8-power-gcc-test-4.2-server-auth
         batchtime: 1440
       - name: sasl-cyrus-openssl-rhel8-power-gcc-test-4.4-server-auth
@@ -273,6 +272,9 @@ buildvariants:
       - name: sasl-cyrus-openssl-windows-2019-vs2017-x64-test-latest-server-auth
       - name: sasl-cyrus-openssl-debian10-gcc-test-4.2-server-auth
       - name: sasl-cyrus-openssl-debian10-gcc-test-4.2-replica-auth
+      - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-server-auth
+      - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-replica-auth
+      - name: sasl-cyrus-openssl-amazon2023-arm64-latest-large-m8g-gcc-test-latest-sharded-auth
   - name: sasl-matrix-winssl
     display_name: sasl-matrix-winssl
     expansions: {}
diff -pruN 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_generator/functions.py 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_generator/functions.py
--- 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_generator/functions.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_generator/functions.py	2025-06-19 15:42:22.000000000 +0000
@@ -31,7 +31,7 @@ def func(func_name: str, **kwargs: Value
 
 def s3_put(remote_file: str, project_path: bool = True, **kwargs: Value) -> ValueMapping:
     if project_path:
-        remote_file = "mongo-c-driver/" + remote_file
+        remote_file = "${project}/" + remote_file
 
     return ValueOrderedDict(
         [
diff -pruN 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/functions.py 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/functions.py
--- 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/functions.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/functions.py	2025-06-19 15:42:22.000000000 +0000
@@ -30,7 +30,7 @@ all_functions = OD([
         shell_mongoc(r'''
         export AWS_ACCESS_KEY_ID=${aws_key}
         export AWS_SECRET_ACCESS_KEY=${aws_secret}
-        aws s3 cp coverage s3://mciuploads/mongo-c-driver/%s/coverage/ --recursive --acl public-read --region us-east-1
+        aws s3 cp coverage s3://mciuploads/${project}/%s/coverage/ --recursive --acl public-read --region us-east-1
         ''' % (build_path,), test=False, silent=True),
         s3_put(build_path + '/coverage/index.html', aws_key='${aws_key}',
                aws_secret='${aws_secret}',
@@ -49,7 +49,7 @@ all_functions = OD([
         shell_mongoc(r'''
         export AWS_ACCESS_KEY_ID=${aws_key}
         export AWS_SECRET_ACCESS_KEY=${aws_secret}
-        aws s3 cp scan s3://mciuploads/mongo-c-driver/%s/scan/ --recursive --acl public-read --region us-east-1
+        aws s3 cp scan s3://mciuploads/${project}/%s/scan/ --recursive --acl public-read --region us-east-1
         ''' % (build_path,), test=False, silent=True),
         s3_put(build_path + '/scan/index.html', aws_key='${aws_key}',
                aws_secret='${aws_secret}', local_file='mongoc/scan.html',
@@ -67,7 +67,6 @@ all_functions = OD([
         # Compile a program that links dynamically or statically to libmongoc,
         # using variables from pkg-config or CMake's find_package command.
         export BUILD_SAMPLE_WITH_CMAKE=${BUILD_SAMPLE_WITH_CMAKE}
-        export BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=${BUILD_SAMPLE_WITH_CMAKE_DEPRECATED}
         export ENABLE_SSL=${ENABLE_SSL}
         export ENABLE_SNAPPY=${ENABLE_SNAPPY}
         LINK_STATIC=  .evergreen/scripts/link-sample-program.sh
@@ -79,12 +78,10 @@ all_functions = OD([
         shell_mongoc(r'''
         # Compile a program that links dynamically or statically to libbson,
         # using variables from pkg-config or from CMake's find_package command.
-        BUILD_SAMPLE_WITH_CMAKE=  BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=  BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1 LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
-        BUILD_SAMPLE_WITH_CMAKE=1 BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1 LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=  LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=  LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=1 LINK_STATIC=  .evergreen/scripts/link-sample-program-bson.sh
+        BUILD_SAMPLE_WITH_CMAKE=1 LINK_STATIC=1 .evergreen/scripts/link-sample-program-bson.sh
         ''',
         include_expansions_in_env=['distro_id']),
     )),
diff -pruN 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/tasks.py 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/tasks.py
--- 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/tasks.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/tasks.py	2025-06-19 15:42:22.000000000 +0000
@@ -55,7 +55,7 @@ class CompileTask(NamedTask):
         CFLAGS: str | None = None,
         LDFLAGS: str | None = None,
         EXTRA_CONFIGURE_FLAGS: str | None = None,
-        SSL: Literal["WINDOWS", "DARWIN", "OPENSSL", "OPENSSL_STATIC", "LIBRESSL", "OFF", None] = None,
+        SSL: Literal["WINDOWS", "DARWIN", "OPENSSL", "OPENSSL_STATIC", "OFF", None] = None,
         ENABLE_SHM_COUNTERS: OptToggleStr = None,
         CHECK_LOG: OptToggleStr = None,
         TRACING: OptToggleStr = None,
@@ -151,7 +151,6 @@ class CompileWithClientSideEncryptionAsa
         CFLAGS="-fno-omit-frame-pointer",
         COMPILE_LIBMONGOCRYPT="ON",
         CHECK_LOG="ON",
-        EXTRA_CONFIGURE_FLAGS="-DENABLE_EXTRA_ALIGNMENT=OFF",
         PATH="/usr/lib/llvm-3.8/bin:$PATH",
     )
     cls_tags: ClassVar[Sequence[str]] = ["client-side-encryption"]
@@ -187,12 +186,6 @@ all_tasks = [
     CompileTask("debug-compile-compression-zlib", tags=["zlib", "compression"], compression="zlib"),
     CompileTask("debug-compile-compression-snappy", tags=["snappy", "compression"], compression="snappy"),
     CompileTask("debug-compile-compression-zstd", tags=["zstd", "compression"], compression="zstd"),
-    CompileTask(
-        "debug-compile-no-align",
-        tags=["debug-compile"],
-        compression="zlib",
-        EXTRA_CONFIGURE_FLAGS="-DENABLE_EXTRA_ALIGNMENT=OFF",
-    ),
     CompileTask("debug-compile-nosasl-nossl", tags=["debug-compile", "nosasl", "nossl"], SSL="OFF"),
     CompileTask("debug-compile-lto", CFLAGS="-flto"),
     CompileTask("debug-compile-lto-thin", CFLAGS="-flto=thin"),
@@ -226,36 +219,6 @@ all_tasks = [
         suffix_commands=[func("link sample program", BUILD_SAMPLE_WITH_CMAKE=1, ENABLE_SNAPPY="ON")],
     ),
     LinkTask("link-with-cmake-mac", suffix_commands=[func("link sample program", BUILD_SAMPLE_WITH_CMAKE=1)]),
-    LinkTask(
-        "link-with-cmake-deprecated",
-        suffix_commands=[func("link sample program", BUILD_SAMPLE_WITH_CMAKE=1, BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1)],
-    ),
-    LinkTask(
-        "link-with-cmake-ssl-deprecated",
-        suffix_commands=[
-            func(
-                "link sample program",
-                BUILD_SAMPLE_WITH_CMAKE=1,
-                BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1,
-                ENABLE_SSL=1,
-            )
-        ],
-    ),
-    LinkTask(
-        "link-with-cmake-snappy-deprecated",
-        suffix_commands=[
-            func(
-                "link sample program",
-                BUILD_SAMPLE_WITH_CMAKE=1,
-                BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1,
-                ENABLE_SNAPPY="ON",
-            )
-        ],
-    ),
-    LinkTask(
-        "link-with-cmake-mac-deprecated",
-        suffix_commands=[func("link sample program", BUILD_SAMPLE_WITH_CMAKE=1, BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=1)],
-    ),
     LinkTask("link-with-cmake-windows", suffix_commands=[func("link sample program MSVC")]),
     LinkTask(
         "link-with-cmake-windows-ssl",
@@ -696,7 +659,7 @@ all_tasks = chain(
                 func("find-cmake-latest"),
                 shell_mongoc(
                     """
-            env SANITIZE=address SASL=AUTO SSL=OPENSSL EXTRA_CONFIGURE_FLAGS='-DENABLE_EXTRA_ALIGNMENT=OFF' .evergreen/scripts/compile.sh
+            env SANITIZE=address SASL=AUTO SSL=OPENSSL .evergreen/scripts/compile.sh
             """,
                     add_expansions_to_env=True,
                 ),
@@ -771,8 +734,6 @@ class SSLTask(Task):
 
         if enable_ssl is not False:
             script += " SSL=" + enable_ssl
-        elif "libressl" in version:
-            script += " SSL=LIBRESSL"
         else:
             script += " SSL=OPENSSL"
 
@@ -816,10 +777,7 @@ all_tasks = chain(
             "l",
             cflags="-Wno-redundant-decls",
         ),
-        SSLTask("openssl-1.1.0", "l"),
-        SSLTask("libressl-2.5", ".2", test_params=dict(require_tls12=True)),
-        SSLTask("libressl-3.0", ".2", enable_ssl="AUTO", test_params=dict(require_tls12=True)),
-        SSLTask("libressl-3.0", ".2", test_params=dict(require_tls12=True)),
+        SSLTask("openssl-1.1.0", "l")
     ],
 )
 
diff -pruN 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/variants.py 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/variants.py
--- 1.30.4-1/.evergreen/legacy_config_generator/evergreen_config_lib/variants.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/legacy_config_generator/evergreen_config_lib/variants.py	2025-06-19 15:42:22.000000000 +0000
@@ -48,11 +48,8 @@ all_variants = [
             "debug-compile-no-counters",
             "compile-tracing",
             "link-with-cmake",
-            "link-with-cmake-deprecated",
             "link-with-cmake-ssl",
-            "link-with-cmake-ssl-deprecated",
             "link-with-cmake-snappy",
-            "link-with-cmake-snappy-deprecated",
             OD([("name", "link-with-cmake-mac"), ("distros", ["macos-14-arm64"])]),
             OD([("name", "link-with-cmake-mac-deprecated"), ("distros", ["macos-14-arm64"])]),
             OD([("name", "link-with-cmake-windows"), ("distros", ["windows-vsCurrent-large"])]),
@@ -82,16 +79,13 @@ all_variants = [
     ),
     Variant(
         "openssl",
-        "OpenSSL / LibreSSL",
+        "OpenSSL",
         "archlinux-build",
         [
             "build-and-run-authentication-tests-openssl-1.0.1",
             "build-and-run-authentication-tests-openssl-1.0.2",
             "build-and-run-authentication-tests-openssl-1.1.0",
-            "build-and-run-authentication-tests-openssl-1.0.1-fips",
-            "build-and-run-authentication-tests-libressl-2.5",
-            "build-and-run-authentication-tests-libressl-3.0-auto",
-            "build-and-run-authentication-tests-libressl-3.0",
+            "build-and-run-authentication-tests-openssl-1.0.1-fips"
         ],
         {},
     ),
@@ -114,7 +108,6 @@ all_variants = [
         [
             "release-compile",
             "debug-compile-nosasl-nossl",
-            "debug-compile-no-align",
             ".debug-compile !.sspi .nossl .nosasl",
             ".latest .nossl .nosasl",
         ],
@@ -154,7 +147,7 @@ all_variants = [
         "gcc94-i686",
         "GCC 9.4 (i686) (Ubuntu 20.04)",
         "ubuntu2004-test",
-        ["release-compile", "debug-compile-nosasl-nossl", "debug-compile-no-align", ".latest .nossl .nosasl"],
+        ["release-compile", "debug-compile-nosasl-nossl", ".latest .nossl .nosasl"],
         {"CC": "gcc", "MARCH": "i686"},
     ),
     Variant(
@@ -166,7 +159,6 @@ all_variants = [
             "debug-compile-nosrv",
             "release-compile",
             "debug-compile-nosasl-nossl",
-            "debug-compile-no-align",
             "debug-compile-sasl-openssl",
             "debug-compile-nosasl-openssl",
             ".authentication-tests .openssl",
@@ -188,7 +180,6 @@ all_variants = [
             ".compression !.snappy",
             "release-compile",
             "debug-compile-nosasl-nossl",
-            "debug-compile-no-align",
             "debug-compile-nosrv",
             "debug-compile-sasl-darwinssl",
             "debug-compile-nosasl-nossl",
@@ -226,11 +217,14 @@ all_variants = [
         "Windows (VS 2017)",
         "windows-vsCurrent-large",
         [
+            "release-compile",
             "debug-compile-nosasl-nossl",
             "debug-compile-nosasl-openssl",
             "debug-compile-sspi-winssl",
+            "debug-compile-nosrv",
             ".latest .nossl",
             ".nosasl .latest .nossl",
+            ".compression !.snappy !.zstd !.latest",
             "test-dns-winssl",
             "test-dns-auth-winssl",
             "debug-compile-aws",
@@ -250,7 +244,6 @@ all_variants = [
         ["debug-compile-nosasl-nossl", ".latest .nossl .nosasl .server"],
         {"CC": "mingw"},
     ),
-    Variant("mingw", "MinGW-W64", "windows-vsCurrent-large", ["debug-compile-no-align"], {"CC": "mingw"}),
     Variant(
         "rhel8-power",
         "Power (ppc64le) (RHEL 8)",
@@ -272,7 +265,6 @@ all_variants = [
         "ubuntu2004-arm64-large",
         [
             ".compression !.snappy !.zstd",
-            "debug-compile-no-align",
             "release-compile",
             "debug-compile-nosasl-nossl",
             "debug-compile-nosasl-openssl",
@@ -291,7 +283,6 @@ all_variants = [
         [
             "release-compile",
             #      '.compression', --> TODO: waiting on ticket CDRIVER-3258
-            "debug-compile-no-align",
             "debug-compile-nosasl-nossl",
             "debug-compile-nosasl-openssl",
             "debug-compile-sasl-openssl",
diff -pruN 1.30.4-1/.evergreen/scripts/abi-compliance-check.sh 2.0.2-1/.evergreen/scripts/abi-compliance-check.sh
--- 1.30.4-1/.evergreen/scripts/abi-compliance-check.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/abi-compliance-check.sh	2025-06-19 15:42:22.000000000 +0000
@@ -19,8 +19,11 @@ declare current base
 current="$(cat VERSION_CURRENT)-${today:?}+git${head_commit:?}" # e.g. 2.3.4-dev
 base=$(cat etc/prior_version.txt)                               # e.g. 1.2.3
 
+current_verdir="$(echo "${current:?}" | perl -lne 'm|^(\d+\.\d+\.\d+).*$|; print $1')" # Strip any suffixes.
+base_verdir="${base:?}"
+
 # Double-check we are testing against the same API major version.
-if [[ "${base:?}" != 1.* ]]; then
+if [[ "${base_verdir:?}" != 2.* ]]; then
   echo "API major version mismatch: base version is ${base:?} but current version is ${current:?}" >&2
   exit 1
 fi
@@ -68,13 +71,13 @@ cat >|old.xml <<DOC
 </libs>
 
 <add_include_paths>
-  $(pwd)/base-install/include/libbson-1.0/
-  $(pwd)/base-install/include/libmongoc-1.0/
+  $(pwd)/base-install/include/bson-${base_verdir:?}/
+  $(pwd)/base-install/include/mongoc-${base_verdir:?}/
 </add_include_paths>
 
 <headers>
-  $(pwd)/base-install/include/libbson-1.0/bson/bson.h
-  $(pwd)/base-install/include/libmongoc-1.0/mongoc/mongoc.h
+  $(pwd)/base-install/include/bson-${base_verdir:?}/bson/bson.h
+  $(pwd)/base-install/include/mongoc-${base_verdir:?}/mongoc/mongoc.h
 </headers>
 DOC
 
@@ -88,16 +91,17 @@ cat >|new.xml <<DOC
 </libs>
 
 <add_include_paths>
-  $(pwd)/current-install/include/libbson-1.0/
-  $(pwd)/current-install/include/libmongoc-1.0/
+  $(pwd)/current-install/include/bson-${current_verdir:?}/
+  $(pwd)/current-install/include/mongoc-${current_verdir:?}/
 </add_include_paths>
 
 <headers>
-  $(pwd)/current-install/include/libbson-1.0/bson/bson.h
-  $(pwd)/current-install/include/libmongoc-1.0/mongoc/mongoc.h
+  $(pwd)/current-install/include/bson-${current_verdir:?}/bson/bson.h
+  $(pwd)/current-install/include/mongoc-${current_verdir:?}/mongoc/mongoc.h
 </headers>
 DOC
 
+# Allow task to upload the HTML report despite failed status.
 if ! abi-compliance-checker -lib mongo-c-driver -old old.xml -new new.xml; then
   find . -name log.txt -exec cat {} + >&2 || true
   declare status
diff -pruN 1.30.4-1/.evergreen/scripts/build-and-test-with-toolchain.sh 2.0.2-1/.evergreen/scripts/build-and-test-with-toolchain.sh
--- 1.30.4-1/.evergreen/scripts/build-and-test-with-toolchain.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/build-and-test-with-toolchain.sh	2025-06-19 15:42:22.000000000 +0000
@@ -35,8 +35,6 @@ toolchain_base_dir="$(readlink -f /opt/m
 declare toolchain_lib_dir="${toolchain_base_dir}/lib"
 
 declare -a ssl_vers=(
-  "libressl-2.5"
-  "libressl-3.0"
   "openssl-1.0.1"
   "openssl-1.0.1-fips"
   "openssl-1.0.2"
@@ -60,11 +58,7 @@ for ssl_ver in "${ssl_vers[@]}"; do
   "${cmake_binary}" --version
 
   declare ssl
-  if [[ "${ssl_ver#*libressl}" != "${ssl_ver}" ]]; then
-    ssl="LIBRESSL"
-  else
-    ssl="OPENSSL"
-  fi
+  ssl="OPENSSL"
 
   declare output_file
   output_file="$(mktemp)"
diff -pruN 1.30.4-1/.evergreen/scripts/check-installed-files-bson.bat 2.0.2-1/.evergreen/scripts/check-installed-files-bson.bat
--- 1.30.4-1/.evergreen/scripts/check-installed-files-bson.bat	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/check-installed-files-bson.bat	1970-01-01 00:00:00.000000000 +0000
@@ -1,76 +0,0 @@
-rem Validations shared by link-sample-program-msvc-bson.bat and
-rem link-sample-program-mingw-bson.bat
-
-echo off
-
-rem Notice that the dll goes in "bin".
-set DLL=%INSTALL_DIR%\bin\bson-1.0.dll
-set LIB_DLL=%INSTALL_DIR%\bin\libbson-1.0.dll
-set LIB_LIB=%INSTALL_DIR%\lib\libbson-1.0.lib
-if "%MINGW%"=="1" (
-  if not exist %LIB_DLL% (
-    echo %LIB_DLL% is missing!
-    exit /B 1
-  ) else (
-    echo libbson-1.0.dll check ok
-  )
-  if exist %DLL% (
-    echo %DLL% is present and should not be!
-    exit /B 1
-  )
-) else (
-  if not exist %DLL% (
-    echo %DLL% is missing!
-    exit /B 1
-  ) else (
-    echo bson-1.0.dll check ok
-  )
-  if exist %LIB_LIB% (
-    echo %LIB_LIB% is present and should not be!
-    exit /B 1
-  ) else (
-    echo libbson-1.0.lib check ok
-  )
-)
-if not exist %INSTALL_DIR%\lib\pkgconfig\libbson-1.0.pc (
-  echo libbson-1.0.pc missing!
-  exit /B 1
-) else (
-  echo libbson-1.0.pc check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-1.0-config.cmake (
-  echo bson-1.0-config.cmake missing!
-  exit /B 1
-) else (
-  echo bson-1.0-config.cmake check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-1.0-config-version.cmake (
-  echo bson-1.0-config-version.cmake missing!
-  exit /B 1
-) else (
-  echo bson-1.0-config-version.cmake check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-targets.cmake (
-  echo bson-targets.cmake missing!
-  exit /B 1
-) else (
-  echo bson-targets.cmake check ok
-)
-
-if "%LINK_STATIC%"=="1" (
-  if not exist %INSTALL_DIR%\lib\pkgconfig\libbson-static-1.0.pc (
-    echo libbson-static-1.0.pc missing!
-    exit /B 1
-  ) else (
-    echo libbson-static-1.0.pc check ok
-  )
-) else (
-  if exist %INSTALL_DIR%\lib\pkgconfig\libbson-static-1.0.pc (
-    echo libbson-static-1.0.pc should not have been installed!
-    exit /B 1
-  ) else (
-    echo libbson-static-1.0.pc missing, as expected
-  )
-)
-
-echo on
diff -pruN 1.30.4-1/.evergreen/scripts/check-installed-files.bat 2.0.2-1/.evergreen/scripts/check-installed-files.bat
--- 1.30.4-1/.evergreen/scripts/check-installed-files.bat	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/check-installed-files.bat	1970-01-01 00:00:00.000000000 +0000
@@ -1,66 +0,0 @@
-rem Validations shared by link-sample-program-msvc.bat and
-rem link-sample-program-mingw.bat
-
-echo off
-
-rem Notice that the dll goes in "bin".
-set DLL=%INSTALL_DIR%\bin\mongoc-1.0.dll
-set LIB_DLL=%INSTALL_DIR%\bin\libmongoc-1.0.dll
-set LIB_LIB=%INSTALL_DIR%\lib\libmongoc-1.0.lib
-if "%MINGW%"=="1" (
-  if not exist %LIB_DLL% (
-    echo %LIB_DLL% is missing!
-    exit /B 1
-  ) else (
-    echo libmongoc-1.0.dll check ok
-  )
-  if exist %DLL% (
-    echo %DLL% is present and should not be!
-    exit /B 1
-  )
-) else (
-  if not exist %DLL% (
-    echo %DLL% is missing!
-    exit /B 1
-  ) else (
-    echo mongoc-1.0.dll check ok
-  )
-  if exist %LIB_LIB% (
-    echo %LIB_LIB% is present and should not be!
-    exit /B 1
-  ) else (
-    echo libmongoc-1.0.lib check ok
-  )
-)
-if not exist %INSTALL_DIR%\lib\pkgconfig\libmongoc-1.0.pc (
-  echo libmongoc-1.0.pc missing!
-  exit /B 1
-) else (
-  echo libmongoc-1.0.pc check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\mongoc-1.0\mongoc-1.0-config.cmake (
-  echo mongoc-1.0-config.cmake missing!
-  exit /B 1
-) else (
-  echo mongoc-1.0-config.cmake check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\mongoc-1.0\mongoc-1.0-config-version.cmake (
-  echo mongoc-1.0-config-version.cmake missing!
-  exit /B 1
-) else (
-  echo mongoc-1.0-config-version.cmake check ok
-)
-if not exist %INSTALL_DIR%\lib\cmake\mongoc-1.0\mongoc-targets.cmake (
-  echo mongoc-targets.cmake missing!
-  exit /B 1
-) else (
-  echo mongoc-targets.cmake check ok
-)
-if not exist %INSTALL_DIR%\lib\pkgconfig\libmongoc-static-1.0.pc (
-  echo libmongoc-static-1.0.pc missing!
-  exit /B 1
-) else (
-  echo libmongoc-static-1.0.pc check ok
-)
-
-echo on
diff -pruN 1.30.4-1/.evergreen/scripts/check-preludes.py 2.0.2-1/.evergreen/scripts/check-preludes.py
--- 1.30.4-1/.evergreen/scripts/check-preludes.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/check-preludes.py	2025-06-19 15:42:22.000000000 +0000
@@ -35,7 +35,7 @@ checks = [
             MONGOC_PREFIX / "mongoc-prelude.h",
             MONGOC_PREFIX / "mongoc.h",
         ],
-        "include": '#include <mongoc/mongoc-prelude.h>',
+        "include": "#include <mongoc/mongoc-prelude.h>",
     },
     {
         "name": "libbson",
@@ -50,7 +50,7 @@ checks = [
         "name": "common",
         "headers": list(COMMON_PREFIX.glob("*.h")),
         "exclusions": [COMMON_PREFIX / "common-prelude.h"],
-        "include": '#include <common-prelude.h>',
+        "include": "#include <common-prelude.h>",
     },
 ]
 
@@ -59,7 +59,7 @@ for check in checks:
     print(f"Checking headers for {NAME}")
     assert len(check["headers"]) > 0
     for header in check["headers"]:
-        if header in check["exclusions"]:
+        if header in check["exclusions"] or header.name.endswith("-private.h"):
             continue
         lines = Path(header).read_text(encoding="utf-8").splitlines()
         if check["include"] not in lines:
diff -pruN 1.30.4-1/.evergreen/scripts/compile-libmongocrypt.sh 2.0.2-1/.evergreen/scripts/compile-libmongocrypt.sh
--- 1.30.4-1/.evergreen/scripts/compile-libmongocrypt.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-libmongocrypt.sh	2025-06-19 15:42:22.000000000 +0000
@@ -10,16 +10,26 @@ compile_libmongocrypt() {
   # `.evergreen/scripts/kms-divergence-check.sh` to ensure that there is no
   # divergence in the copied files.
 
-  git clone -q --depth=1 https://github.com/mongodb/libmongocrypt --branch 1.12.0 || return
+  # Clone libmongocrypt and check-out 1.13.0.
+  git clone -q --depth=1 https://github.com/mongodb/libmongocrypt --branch 1.13.0 || return
 
   declare -a crypt_cmake_flags=(
     "-DMONGOCRYPT_MONGOC_DIR=${mongoc_dir}"
     "-DBUILD_TESTING=OFF"
     "-DENABLE_ONLINE_TESTS=OFF"
     "-DENABLE_MONGOC=OFF"
-    "-DBUILD_VERSION=1.12.0"
+    "-DBUILD_VERSION=1.13.0"
   )
 
+  . "$(dirname "${BASH_SOURCE[0]}")/find-ccache.sh"
+  find_ccache_and_export_vars "$(pwd)/libmongocrypt" || true
+  if command -v "${CMAKE_C_COMPILER_LAUNCHER:-}" && [[ "${OSTYPE:?}" == cygwin ]]; then
+    crypt_cmake_flags+=(
+      "-DCMAKE_POLICY_DEFAULT_CMP0141=NEW"
+      "-DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded"
+    )
+  fi
+
   env \
     DEBUG="0" \
     CMAKE_EXE="${cmake_binary}" \
diff -pruN 1.30.4-1/.evergreen/scripts/compile-openssl-static.sh 2.0.2-1/.evergreen/scripts/compile-openssl-static.sh
--- 1.30.4-1/.evergreen/scripts/compile-openssl-static.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-openssl-static.sh	2025-06-19 15:42:22.000000000 +0000
@@ -8,6 +8,8 @@ set -o pipefail
 . "$(dirname "${BASH_SOURCE[0]}")/use-tools.sh" paths
 
 check_var_opt CC
+check_var_opt CMAKE_GENERATOR
+check_var_opt CMAKE_GENERATOR_PLATFORM
 check_var_opt MARCH
 
 declare script_dir
@@ -39,7 +41,6 @@ configure_flags_append_if_not_null() {
 }
 
 configure_flags_append "-DCMAKE_SKIP_RPATH=TRUE" # Avoid hardcoding absolute paths to dependency libraries.
-configure_flags_append "-DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF"
 configure_flags_append "-DENABLE_MAINTAINER_FLAGS=ON"
 configure_flags_append "-DENABLE_SSL=OPENSSL"
 configure_flags_append "-DOPENSSL_USE_STATIC_LIBS=ON"
@@ -77,15 +78,6 @@ if [[ "${OSTYPE}" == darwin* ]]; then
   CFLAGS+=" -Wno-unknown-pragmas"
 fi
 
-case "${CC}" in
-clang)
-  CXX=clang++
-  ;;
-gcc)
-  CXX=g++
-  ;;
-esac
-
 if [[ "${OSTYPE}" == darwin* && "${HOSTTYPE}" == "arm64" ]]; then
   configure_flags_append "-DCMAKE_OSX_ARCHITECTURES=arm64"
 fi
diff -pruN 1.30.4-1/.evergreen/scripts/compile-scan-build.sh 2.0.2-1/.evergreen/scripts/compile-scan-build.sh
--- 1.30.4-1/.evergreen/scripts/compile-scan-build.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-scan-build.sh	2025-06-19 15:42:22.000000000 +0000
@@ -32,7 +32,6 @@ configure_flags_append_if_not_null() {
 
 configure_flags_append "-DCMAKE_PREFIX_PATH=${cmake_prefix_path}"
 configure_flags_append "-DCMAKE_SKIP_RPATH=TRUE" # Avoid hardcoding absolute paths to dependency libraries.
-configure_flags_append "-DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF"
 configure_flags_append "-DENABLE_CLIENT_SIDE_ENCRYPTION=ON"
 configure_flags_append "-DENABLE_DEBUG_ASSERTIONS=ON"
 configure_flags_append "-DENABLE_MAINTAINER_FLAGS=ON"
diff -pruN 1.30.4-1/.evergreen/scripts/compile-std.sh 2.0.2-1/.evergreen/scripts/compile-std.sh
--- 1.30.4-1/.evergreen/scripts/compile-std.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-std.sh	2025-06-19 15:42:22.000000000 +0000
@@ -7,10 +7,13 @@ set -o pipefail
 . "$(dirname "${BASH_SOURCE[0]}")/env-var-utils.sh"
 . "$(dirname "${BASH_SOURCE[0]}")/use-tools.sh" paths
 
-check_var_req CC
+check_var_opt CC
+check_var_opt CMAKE_GENERATOR
+check_var_opt CMAKE_GENERATOR_PLATFORM
 
-check_var_opt C_STD_VERSION
+check_var_req C_STD_VERSION
 check_var_opt CFLAGS
+check_var_opt CXXFLAGS
 check_var_opt MARCH
 
 declare script_dir
@@ -37,18 +40,26 @@ configure_flags_append_if_not_null() {
 
 configure_flags_append "-DCMAKE_PREFIX_PATH=${install_dir}"
 configure_flags_append "-DCMAKE_SKIP_RPATH=TRUE" # Avoid hardcoding absolute paths to dependency libraries.
-configure_flags_append "-DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF"
 configure_flags_append "-DENABLE_CLIENT_SIDE_ENCRYPTION=ON"
 configure_flags_append "-DENABLE_DEBUG_ASSERTIONS=ON"
 configure_flags_append "-DENABLE_MAINTAINER_FLAGS=ON"
 
-configure_flags_append_if_not_null C_STD_VERSION "-DCMAKE_C_STANDARD=${C_STD_VERSION}"
+if [[ "${C_STD_VERSION}" == "latest" ]]; then
+  [[ "${CMAKE_GENERATOR:-}" =~ "Visual Studio" ]] || {
+    echo "C_STD_VERSION=latest to enable /std:clatest is only supported with Visual Studio generators" 1>&2
+    exit 1
+  }
+
+  configure_flags_append "-DCMAKE_C_FLAGS=/std:clatest"
+else
+  configure_flags_append_if_not_null C_STD_VERSION "-DCMAKE_C_STANDARD=${C_STD_VERSION}"
+fi
 
 if [[ "${OSTYPE}" == darwin* && "${HOSTTYPE}" == "arm64" ]]; then
   configure_flags_append "-DCMAKE_OSX_ARCHITECTURES=arm64"
 fi
 
-if [[ "${CC}" =~ ^"Visual Studio " ]]; then
+if [[ "${CMAKE_GENERATOR:-}" =~ "Visual Studio" ]]; then
   # Avoid C standard conformance issues with Windows 10 SDK headers.
   # See: https://developercommunity.visualstudio.com/t/stdc17-generates-warning-compiling-windowsh/1249671#T-N1257345
   configure_flags_append "-DCMAKE_SYSTEM_VERSION=10.0.20348.0"
@@ -56,53 +67,22 @@ fi
 
 declare -a flags
 
-if [[ ! "${CC}" =~ ^"Visual Studio " ]]; then
-  case "${MARCH}" in
-  i686)
-    flags+=("-m32" "-march=i386")
-    ;;
-  esac
-
-  case "${HOSTTYPE}" in
-  s390x)
-    flags+=("-march=z196" "-mtune=zEC12")
-    ;;
-  x86_64)
-    flags+=("-m64" "-march=x86-64")
-    ;;
-  powerpc64le)
-    flags+=("-mcpu=power8" "-mtune=power8" "-mcmodel=medium")
-    ;;
-  esac
-fi
-
-if [[ "${CC}" =~ ^"Visual Studio " ]]; then
+if [[ "${CMAKE_GENERATOR:-}" =~ "Visual Studio" ]]; then
   # Even with -DCMAKE_SYSTEM_VERSION=10.0.20348.0, winbase.h emits conformance warnings.
   flags+=('/wd5105')
 fi
 
+if [[ "${OSTYPE}" == darwin* ]]; then
+  flags+=('-Wno-unknown-pragmas')
+fi
+
 # CMake and compiler environment variables.
-export CC
-export CXX
 export CFLAGS
 export CXXFLAGS
 
 CFLAGS+=" ${flags+${flags[*]}}"
 CXXFLAGS+=" ${flags+${flags[*]}}"
 
-if [[ "${OSTYPE}" == darwin* ]]; then
-  CFLAGS+=" -Wno-unknown-pragmas"
-fi
-
-case "${CC}" in
-clang)
-  CXX=clang++
-  ;;
-gcc)
-  CXX=g++
-  ;;
-esac
-
 # Ensure find-cmake-latest.sh is sourced *before* add-build-dirs-to-paths.sh
 # to avoid interfering with potential CMake build configuration.
 # shellcheck source=.evergreen/scripts/find-cmake-latest.sh
@@ -110,6 +90,9 @@ esac
 declare cmake_binary
 cmake_binary="$(find_cmake_latest)"
 
+declare build_dir
+build_dir="cmake-build"
+
 # shellcheck source=.evergreen/scripts/add-build-dirs-to-paths.sh
 . "${script_dir}/add-build-dirs-to-paths.sh"
 
@@ -123,6 +106,16 @@ if [[ "${OSTYPE}" == darwin* ]]; then
   }
 fi
 
+export CMAKE_BUILD_PARALLEL_LEVEL
+CMAKE_BUILD_PARALLEL_LEVEL="$(nproc)"
+
+if [[ "${CMAKE_GENERATOR:-}" =~ "Visual Studio" ]]; then
+  # MSBuild needs additional assistance.
+  # https://devblogs.microsoft.com/cppblog/improved-parallelism-in-msbuild/
+  export UseMultiToolTask=1
+  export EnforceProcessCountAcrossBuilds=1
+fi
+
 echo "Installing libmongocrypt..."
 # shellcheck source=.evergreen/scripts/compile-libmongocrypt.sh
 "${script_dir}/compile-libmongocrypt.sh" "${cmake_binary}" "${mongoc_dir}" "${install_dir}" &>output.txt || {
@@ -131,12 +124,26 @@ echo "Installing libmongocrypt..."
 }
 echo "Installing libmongocrypt... done."
 
-echo "CFLAGS: ${CFLAGS}"
-echo "configure_flags: ${configure_flags[*]}"
-
 # Use ccache if able.
 . "${script_dir:?}/find-ccache.sh"
 find_ccache_and_export_vars "$(pwd)" || true
+if command -v "${CMAKE_C_COMPILER_LAUNCHER:-}" && [[ "${OSTYPE:?}" == cygwin ]]; then
+  configure_flags_append "-DCMAKE_POLICY_DEFAULT_CMP0141=NEW"
+  configure_flags_append "-DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=$<$<CONFIG:Debug,RelWithDebInfo>:Embedded>"
+fi
+
+echo "CFLAGS: ${CFLAGS}"
+echo "configure_flags: ${configure_flags[*]}"
+
+if [[ "${CMAKE_GENERATOR:-}" =~ "Visual Studio" ]]; then
+  all_target="ALL_BUILD"
+else
+  all_target="all"
+fi
 
-"${cmake_binary}" "${configure_flags[@]}" .
-"${cmake_binary}" --build .
+"${cmake_binary}" -S . -B "${build_dir:?}" "${configure_flags[@]}"
+"${cmake_binary}" --build "${build_dir:?}" --config Debug \
+  --target mongo_c_driver_tests \
+  --target mongo_c_driver_examples \
+  --target public-header-warnings \
+  --target "${all_target:?}"
diff -pruN 1.30.4-1/.evergreen/scripts/compile-unix.sh 2.0.2-1/.evergreen/scripts/compile-unix.sh
--- 1.30.4-1/.evergreen/scripts/compile-unix.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-unix.sh	2025-06-19 15:42:22.000000000 +0000
@@ -10,6 +10,8 @@ set -o pipefail
 check_var_opt BYPASS_FIND_CMAKE "OFF"
 check_var_opt C_STD_VERSION # CMake default: 99.
 check_var_opt CC
+check_var_opt CMAKE_GENERATOR
+check_var_opt CMAKE_GENERATOR_PLATFORM
 check_var_opt CFLAGS
 check_var_opt CHECK_LOG "OFF"
 check_var_opt COMPILE_LIBMONGOCRYPT "OFF"
@@ -66,7 +68,6 @@ configure_flags_append_if_not_null() {
 configure_flags_append "-DCMAKE_INSTALL_PREFIX=${install_dir}"
 configure_flags_append "-DCMAKE_PREFIX_PATH=${cmake_prefix_path}"
 configure_flags_append "-DCMAKE_SKIP_RPATH=TRUE" # Avoid hardcoding absolute paths to dependency libraries.
-configure_flags_append "-DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF"
 configure_flags_append "-DENABLE_HTML_DOCS=OFF"
 configure_flags_append "-DENABLE_MAINTAINER_FLAGS=ON"
 configure_flags_append "-DENABLE_MAN_PAGES=OFF"
@@ -119,8 +120,6 @@ powerpc64le)
 esac
 
 # CMake and compiler environment variables.
-export CC
-export CXX
 export CFLAGS
 export CXXFLAGS
 
@@ -135,15 +134,6 @@ if [[ "${OSTYPE}" == darwin* && "${HOSTT
   configure_flags_append "-DCMAKE_OSX_ARCHITECTURES=arm64"
 fi
 
-case "${CC}" in
-clang)
-  CXX=clang++
-  ;;
-gcc)
-  CXX=g++
-  ;;
-esac
-
 declare cmake_binary
 if [[ "${BYPASS_FIND_CMAKE}" == "OFF" ]]; then
   # Ensure find-cmake-latest.sh is sourced *before* add-build-dirs-to-paths.sh
@@ -220,4 +210,4 @@ build_dir="cmake-build"
 if [[ "$EXTRA_CONFIGURE_FLAGS" != *"ENABLE_MONGOC=OFF"* ]]; then
   # Check public headers for extra warnings.
   "${cmake_binary}" --build "${build_dir:?}" --target public-header-warnings
-fi
\ No newline at end of file
+fi
diff -pruN 1.30.4-1/.evergreen/scripts/compile-windows.sh 2.0.2-1/.evergreen/scripts/compile-windows.sh
--- 1.30.4-1/.evergreen/scripts/compile-windows.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/compile-windows.sh	2025-06-19 15:42:22.000000000 +0000
@@ -11,7 +11,9 @@ set -o igncr # Ignore CR in this script
 
 check_var_opt BYPASS_FIND_CMAKE "OFF"
 check_var_opt C_STD_VERSION # CMake default: 99.
-check_var_opt CC "Visual Studio 15 2017 Win64"
+check_var_opt CC
+check_var_opt CMAKE_GENERATOR
+check_var_opt CMAKE_GENERATOR_PLATFORM
 check_var_opt COMPILE_LIBMONGOCRYPT "OFF"
 check_var_opt EXTRA_CONFIGURE_FLAGS
 check_var_opt RELEASE "OFF"
@@ -134,7 +136,15 @@ if [ "${COMPILE_LIBMONGOCRYPT}" = "ON" ]
   configure_flags_append "-DENABLE_CLIENT_SIDE_ENCRYPTION=ON"
 fi
 
-"${cmake_binary:?}" -S . -B "${build_dir:?}" -G "$CC" "${configure_flags[@]}" "${extra_configure_flags[@]}"
+# Use ccache if able.
+. "${script_dir:?}/find-ccache.sh"
+find_ccache_and_export_vars "$(pwd)" || true
+if command -v "${CMAKE_C_COMPILER_LAUNCHER:-}" && [[ "${OSTYPE:?}" == cygwin ]]; then
+  configure_flags_append "-DCMAKE_POLICY_DEFAULT_CMP0141=NEW"
+  configure_flags_append "-DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=$<$<CONFIG:Debug,RelWithDebInfo>:Embedded>"
+fi
+
+"${cmake_binary:?}" -S . -B "${build_dir:?}" "${configure_flags[@]}" "${extra_configure_flags[@]}"
 "${cmake_binary:?}" --build "${build_dir:?}" --config "${build_config:?}"
 "${cmake_binary:?}" --install "${build_dir:?}" --config "${build_config:?}"
 
@@ -147,4 +157,4 @@ fi
 if [[ "$EXTRA_CONFIGURE_FLAGS" != *"ENABLE_MONGOC=OFF"* ]]; then
   # Check public headers for extra warnings.
   "${cmake_binary:?}" --build "${build_dir:?}" --config "${build_config:?}" --target public-header-warnings
-fi
\ No newline at end of file
+fi
diff -pruN 1.30.4-1/.evergreen/scripts/install-ssl.sh 2.0.2-1/.evergreen/scripts/install-ssl.sh
--- 1.30.4-1/.evergreen/scripts/install-ssl.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/install-ssl.sh	2025-06-19 15:42:22.000000000 +0000
@@ -81,18 +81,6 @@ install_openssl_fips() {
   install_openssl
 }
 
-install_libressl() {
-  curl --retry 5 -o ssl.tar.gz "https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/${SSL}.tar.gz"
-  tar zxf ssl.tar.gz
-  pushd "${SSL}"
-  (
-    set -o xtrace
-    ./configure --prefix="${install_dir}"
-    make -s -j "${njobs}" install
-  ) >/dev/null
-  popd # "${SSL}"
-}
-
 case "${SSL}" in
 openssl-*-fips)
   export LC_ALL
@@ -106,7 +94,4 @@ openssl-*)
   install_openssl
   ;;
 
-libressl-*)
-  install_libressl
-  ;;
 esac
diff -pruN 1.30.4-1/.evergreen/scripts/install-uninstall-check-windows.cmd 2.0.2-1/.evergreen/scripts/install-uninstall-check-windows.cmd
--- 1.30.4-1/.evergreen/scripts/install-uninstall-check-windows.cmd	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/install-uninstall-check-windows.cmd	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,9 @@ set CMAKE_MAKE_PROGRAM=C:\mingw-w64\x86_
 rem Ensure Cygwin executables like sh.exe are not in PATH
 set PATH=C:\cygwin\bin;C:\Windows\system32;C:\Windows;C:\mingw-w64\x86_64-4.9.1-posix-seh-rt_v3-rev1\mingw64\bin;C:\mongoc;src\libbson;src\libmongoc
 
+set version=1.31.0
+set major=1
+
 if "%BSON_ONLY%"=="1" (
    set BUILD_DIR=%CD%\build-dir-bson
    set INSTALL_DIR=%CD%\install-dir-bson
@@ -120,29 +123,11 @@ echo.%CC%| findstr /I "gcc">Nul && (
   )
 )
 
-if exist %INSTALL_DIR%\lib\pkgconfig\libbson-1.0.pc (
-   echo libbson-1.0.pc found!
-   exit /B 1
-) else (
-   echo libbson-1.0.pc check ok
-)
-if exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-1.0-config.cmake (
-   echo bson-1.0-config.cmake found!
-   exit /B 1
-) else (
-   echo bson-1.0-config.cmake check ok
-)
-if exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-1.0-config-version.cmake (
-   echo bson-1.0-config-version.cmake found!
+if exist %INSTALL_DIR%\lib\pkgconfig\bson%major%.pc (
+   echo bson%major%.pc found!
    exit /B 1
 ) else (
-   echo bson-1.0-config-version.cmake check ok
-)
-if exist %INSTALL_DIR%\lib\cmake\bson-1.0\bson-targets.cmake (
-   echo bson-targets.cmake found!
-   exit /B 1
-) else (
-   echo bson-targets.cmake check ok
+   echo bson%major%.pc check ok
 )
 if not exist %INSTALL_DIR%\lib\canary.txt (
    echo canary.txt not found!
@@ -157,11 +142,11 @@ if not exist %INSTALL_DIR%\lib (
    echo %INSTALL_DIR%\lib check ok
 )
 if "%BSON_ONLY%" NEQ "1" (
-   if exist %INSTALL_DIR%\lib\pkgconfig\libmongoc-1.0.pc (
-     echo libmongoc-1.0.pc found!
+   if exist %INSTALL_DIR%\lib\pkgconfig\mongoc%major%.pc (
+     echo mongoc%major%.pc found!
      exit /B 1
    ) else (
-     echo libmongoc-1.0.pc check ok
+     echo mongoc%major%.pc check ok
    )
    if exist %INSTALL_DIR%\lib\cmake\mongoc-1.0\mongoc-1.0-config.cmake (
      echo mongoc-1.0-config.cmake found!
@@ -182,23 +167,17 @@ if "%BSON_ONLY%" NEQ "1" (
      echo mongoc-targets.cmake check ok
    )
 )
-if exist %INSTALL_DIR%\include\libbson-1.0\bson\bson.h (
+if exist %INSTALL_DIR%\include\bson-%version%\bson\bson.h (
    echo bson\bson.h found!
    exit /B 1
 ) else (
    echo bson\bson.h check ok
 )
-if exist %INSTALL_DIR%\include\libbson-1.0\bson.h (
-   echo bson.h found!
-   exit /B 1
-) else (
-   echo bson.h check ok
-)
-if exist %INSTALL_DIR%\include\libbson-1.0 (
-   echo $INSTALL_DIR\include\libbson-1.0 found!
+if exist %INSTALL_DIR%\include\bson-%version% (
+   echo $INSTALL_DIR\include\bson-%version% found!
    exit /B 1
 ) else (
-   echo $INSTALL_DIR\include\libbson-1.0 check ok
+   echo $INSTALL_DIR\include\bson-%version% check ok
 )
 if "%BSON_ONLY%" NEQ "1" (
    if exist %INSTALL_DIR%\include\libmongoc-1.0\mongoc\mongoc.h (
diff -pruN 1.30.4-1/.evergreen/scripts/install-uninstall-check.sh 2.0.2-1/.evergreen/scripts/install-uninstall-check.sh
--- 1.30.4-1/.evergreen/scripts/install-uninstall-check.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/install-uninstall-check.sh	2025-06-19 15:42:22.000000000 +0000
@@ -13,6 +13,13 @@ CMAKE=$(find_cmake_latest)
 . $DIR/check-symlink.sh
 SRCROOT=$(pwd)
 
+# The major version of the project. Appears in certain install filenames.
+_full_version=$(cat "$DIR/../../VERSION_CURRENT")
+version="${_full_version%-*}"  # 1.2.3-dev → 1.2.3
+major="${version%%.*}"         # 1.2.3     → 1
+echo "major version: $major"
+echo " full version: $version"
+
 # Use ccache if able.
 . $DIR/find-ccache.sh
 find_ccache_and_export_vars "$(pwd)" || true
@@ -20,7 +27,7 @@ find_ccache_and_export_vars "$(pwd)" ||
 SCRATCH_DIR=$(pwd)/.scratch
 rm -rf "$SCRATCH_DIR"
 mkdir -p "$SCRATCH_DIR"
-cp -vr -- "$SRCROOT"/* "$SCRATCH_DIR"
+cp -r -- "$SRCROOT"/* "$SCRATCH_DIR"
 
 if [ "$BSON_ONLY" ]; then
   BUILD_DIR=$SCRATCH_DIR/build-dir-bson
@@ -58,8 +65,8 @@ if [[ -f $DIR/find-ccache.sh ]]; then
   find_ccache_and_export_vars "$SCRATCH_DIR" || true
 fi
 
-$CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX -DCMAKE_PREFIX_PATH=$INSTALL_DIR/lib/cmake $BSON_ONLY_OPTION "$SCRATCH_DIR"
-$CMAKE --build .
+$CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX -DBUILD_TESTING=OFF -DCMAKE_PREFIX_PATH=$INSTALL_DIR/lib/cmake $BSON_ONLY_OPTION "$SCRATCH_DIR"
+$CMAKE --build . --parallel
 if [ "$DESTDIR" ]; then
    DESTDIR=$DESTDIR $CMAKE --build . --target install
 else
@@ -93,29 +100,23 @@ $CMAKE --build . --target uninstall
 
 set +o xtrace
 
-if test -f $INSTALL_DIR/lib/pkgconfig/libbson-1.0.pc; then
-  echo "libbson-1.0.pc found!"
-  exit 1
-else
-  echo "libbson-1.0.pc check ok"
-fi
-if test -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-1.0-config.cmake; then
-  echo "bson-1.0-config.cmake found!"
+if test -f $INSTALL_DIR/lib/pkgconfig/bson$major.pc; then
+  echo "bson$major.pc found!"
   exit 1
 else
-  echo "bson-1.0-config.cmake check ok"
+  echo "bson$major.pc check ok"
 fi
-if test -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-1.0-config-version.cmake; then
-  echo "bson-1.0-config-version.cmake found!"
+if test -f $INSTALL_DIR/lib/cmake/bson-$version/bsonConfig.cmake; then
+  echo "bsonConfig.cmake found!"
   exit 1
 else
-  echo "bson-1.0-config-version.cmake check ok"
+  echo "bsonConfig.cmake check ok"
 fi
-if test -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-targets.cmake; then
-  echo "bson-targets.cmake found!"
+if test -f $INSTALL_DIR/lib/cmake/bson-$version/bsonConfigVersion.cmake; then
+  echo "bsonConfigVersion.cmake found!"
   exit 1
 else
-  echo "bson-targets.cmake check ok"
+  echo "bsonConfigVersion.cmake check ok"
 fi
 if test ! -f $INSTALL_DIR/lib/canary.txt; then
   echo "canary.txt not found!"
@@ -130,11 +131,11 @@ else
   echo "$INSTALL_DIR/lib check ok"
 fi
 if [ -z "$BSON_ONLY" ]; then
-  if test -f $INSTALL_DIR/lib/pkgconfig/libmongoc-1.0.pc; then
-    echo "libmongoc-1.0.pc found!"
+  if test -f $INSTALL_DIR/lib/pkgconfig/mongoc$major.pc; then
+    echo "mongoc$major.pc found!"
     exit 1
   else
-    echo "libmongoc-1.0.pc check ok"
+    echo "mongoc$major.pc check ok"
   fi
   if test -f $INSTALL_DIR/lib/cmake/mongoc-1.0/mongoc-1.0-config.cmake; then
     echo "mongoc-1.0-config.cmake found!"
@@ -155,23 +156,17 @@ if [ -z "$BSON_ONLY" ]; then
     echo "mongoc-targets.cmake check ok"
   fi
 fi
-if test -f $INSTALL_DIR/include/libbson-1.0/bson/bson.h; then
+if test -f $INSTALL_DIR/include/bson-$version/bson/bson.h; then
   echo "bson/bson.h found!"
   exit 1
 else
   echo "bson/bson.h check ok"
 fi
-if test -f $INSTALL_DIR/include/libbson-1.0/bson.h; then
-  echo "bson.h found!"
+if test -d $INSTALL_DIR/include/bson-$version; then
+  echo "$INSTALL_DIR/include/bson-$version found!"
   exit 1
 else
-  echo "bson.h check ok"
-fi
-if test -d $INSTALL_DIR/include/libbson-1.0; then
-  echo "$INSTALL_DIR/include/libbson-1.0 found!"
-  exit 1
-else
-  echo "$INSTALL_DIR/include/libbson-1.0 check ok"
+  echo "$INSTALL_DIR/include/bson-$version check ok"
 fi
 if [ -z "$BSON_ONLY" ]; then
   if test -f $INSTALL_DIR/include/libmongoc-1.0/mongoc/mongoc.h; then
@@ -180,12 +175,6 @@ if [ -z "$BSON_ONLY" ]; then
   else
     echo "mongoc/mongoc.h check ok"
   fi
-  if test -f $INSTALL_DIR/include/libmongoc-1.0/mongoc.h; then
-    echo "mongoc.h found!"
-    exit 1
-  else
-    echo "mongoc.h check ok"
-  fi
   if test -d $INSTALL_DIR/include/libmongoc-1.0; then
     echo "$INSTALL_DIR/include/libmongoc-1.0 found!"
     exit 1
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program-bson.sh 2.0.2-1/.evergreen/scripts/link-sample-program-bson.sh
--- 1.30.4-1/.evergreen/scripts/link-sample-program-bson.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program-bson.sh	2025-06-19 15:42:22.000000000 +0000
@@ -4,27 +4,29 @@ set -o errexit  # Exit the script with e
 # Supported/used environment variables:
 #   LINK_STATIC              Whether to statically link to libbson
 #   BUILD_SAMPLE_WITH_CMAKE  Link program w/ CMake. Default: use pkg-config.
-#   BUILD_SAMPLE_WITH_CMAKE_DEPRECATED  If BUILD_SAMPLE_WITH_CMAKE is set, then use deprecated CMake scripts instead.
 
 
-echo "LINK_STATIC=$LINK_STATIC BUILD_SAMPLE_WITH_CMAKE=$BUILD_SAMPLE_WITH_CMAKE BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=$BUILD_SAMPLE_WITH_CMAKE_DEPRECATED"
+echo "LINK_STATIC=$LINK_STATIC BUILD_SAMPLE_WITH_CMAKE=$BUILD_SAMPLE_WITH_CMAKE"
 
 DIR=$(dirname $0)
 . $DIR/find-cmake-latest.sh
 CMAKE=$(find_cmake_latest)
 . $DIR/check-symlink.sh
 
+# The major version of the project. Appears in certain install filenames.
+_full_version=$(cat "$DIR/../../VERSION_CURRENT")
+version="${_full_version%-*}"  # 1.2.3-dev → 1.2.3
+major="${version%%.*}"         # 1.2.3     → 1
+echo "major version: $major"
+echo " full version: $version"
+
 # Get the kernel name, lowercased
 OS=$(uname -s | tr '[:upper:]' '[:lower:]')
 echo "OS: $OS"
 
 if [ "$OS" = "darwin" ]; then
-  SO=dylib
-  LIB_SO=libbson-1.0.0.dylib
   LDD="otool -L"
 else
-  SO=so
-  LIB_SO=libbson-1.0.so.0.0.0
   LDD=ldd
 fi
 
@@ -52,29 +54,13 @@ fi
 
 if [ "$LINK_STATIC" ]; then
   # Our CMake system builds shared and static by default.
-  $CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DENABLE_TESTS=OFF "$SCRATCH_DIR"
+  $CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DBUILD_TESTING=OFF -DENABLE_TESTS=OFF -DENABLE_MONGOC=OFF "$SCRATCH_DIR"
   $CMAKE --build . --parallel
   $CMAKE --build . --parallel --target install
 else
-  $CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DENABLE_TESTS=OFF -DENABLE_STATIC=OFF "$SCRATCH_DIR"
+  $CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DBUILD_TESTING=OFF -DENABLE_TESTS=OFF -DENABLE_MONGOC=OFF -DENABLE_STATIC=OFF "$SCRATCH_DIR"
   $CMAKE --build . --parallel
   $CMAKE --build . --parallel --target install
-
-  set +o xtrace
-
-  if test -f $INSTALL_DIR/lib/libbson-static-1.0.a; then
-    echo "libbson-static-1.0.a shouldn't have been installed"
-    exit 1
-  fi
-  if test -f $INSTALL_DIR/lib/libbson-1.0.a; then
-    echo "libbson-1.0.a shouldn't have been installed"
-    exit 1
-  fi
-  if test -f $INSTALL_DIR/lib/pkgconfig/libbson-static-1.0.pc; then
-    echo "libbson-static-1.0.pc shouldn't have been installed"
-    exit 1
-  fi
-
 fi
 
 # Revert ccache options, they no longer apply.
@@ -82,83 +68,10 @@ unset CCACHE_BASEDIR CCACHE_NOHASHDIR
 
 ls -l $INSTALL_DIR/lib
 
-set +o xtrace
-
-# Check on Linux that libbson is installed into lib/ like:
-# libbson-1.0.so -> libbson-1.0.so.0
-# libbson-1.0.so.0 -> libbson-1.0.so.0.0.0
-# libbson-1.0.so.0.0.0
-if [ "$OS" != "darwin" ]; then
-  # From check-symlink.sh
-  check_symlink libbson-1.0.so libbson-1.0.so.0
-  check_symlink libbson-1.0.so.0 libbson-1.0.so.0.0.0
-  SONAME=$(objdump -p $INSTALL_DIR/lib/$LIB_SO|grep SONAME|awk '{print $2}')
-  EXPECTED_SONAME="libbson-1.0.so.0"
-  if [ "$SONAME" != "$EXPECTED_SONAME" ]; then
-    echo "SONAME should be $EXPECTED_SONAME, not $SONAME"
-    exit 1
-  else
-    echo "library name check ok, SONAME=$SONAME"
-  fi
-else
-  # Just test that the shared lib was installed.
-  if test ! -f $INSTALL_DIR/lib/$LIB_SO; then
-    echo "$LIB_SO missing!"
-    exit 1
-  else
-    echo "$LIB_SO check ok"
-  fi
-fi
-
-if test ! -f $INSTALL_DIR/lib/pkgconfig/libbson-1.0.pc; then
-  echo "libbson-1.0.pc missing!"
-  exit 1
-else
-  echo "libbson-1.0.pc check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-1.0-config.cmake; then
-  echo "bson-1.0-config.cmake missing!"
-  exit 1
-else
-  echo "bson-1.0-config.cmake check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-1.0-config-version.cmake; then
-  echo "bson-1.0-config-version.cmake missing!"
-  exit 1
-else
-  echo "bson-1.0-config-version.cmake check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/bson-1.0/bson-targets.cmake; then
-  echo "bson-targets.cmake missing!"
-  exit 1
-else
-  echo "bson-targets.cmake check ok"
-fi
-
-if [ "$LINK_STATIC" ]; then
-  if test ! -f $INSTALL_DIR/lib/libbson-static-1.0.a; then
-    echo "libbson-static-1.0.a missing!"
-    exit 1
-  else
-    echo "libbson-static-1.0.a check ok"
-  fi
-  if test ! -f $INSTALL_DIR/lib/pkgconfig/libbson-static-1.0.pc; then
-    echo "libbson-static-1.0.pc missing!"
-    exit 1
-  else
-    echo "libbson-static-1.0.pc check ok"
-  fi
-fi
-
 cd $SRCROOT
 
 if [ "$BUILD_SAMPLE_WITH_CMAKE" ]; then
-  # Test our CMake package config file with CMake's find_package command.
-  if [ "$BUILD_SAMPLE_WITH_CMAKE_DEPRECATED" ]; then
-    EXAMPLE_DIR=$SRCROOT/src/libbson/examples/cmake-deprecated/find_package
-  else
-    EXAMPLE_DIR=$SRCROOT/src/libbson/examples/cmake/find_package
-  fi
+  EXAMPLE_DIR=$SRCROOT/src/libbson/examples/cmake/find_package
 
   if [ "$LINK_STATIC" ]; then
     EXAMPLE_DIR="${EXAMPLE_DIR}_static"
@@ -174,12 +87,12 @@ else
 
   if [ "$LINK_STATIC" ]; then
     echo "pkg-config output:"
-    echo $(pkg-config --libs --cflags libbson-static-1.0)
-    ./compile-with-pkg-config-static.sh
+    echo $(pkg-config --libs --cflags bson$major-static)
+    env major=$major ./compile-with-pkg-config-static.sh
   else
     echo "pkg-config output:"
-    echo $(pkg-config --libs --cflags libbson-1.0)
-    ./compile-with-pkg-config.sh
+    echo $(pkg-config --libs --cflags bson$major)
+    env major=$major ./compile-with-pkg-config.sh
   fi
 fi
 
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program-mingw-bson.cmd 2.0.2-1/.evergreen/scripts/link-sample-program-mingw-bson.cmd
--- 1.30.4-1/.evergreen/scripts/link-sample-program-mingw-bson.cmd	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program-mingw-bson.cmd	2025-06-19 15:42:22.000000000 +0000
@@ -19,6 +19,9 @@ mkdir %INSTALL_DIR%
 
 set PATH=%PATH%;%INSTALL_DIR%\bin
 
+set major=1
+set version=1.31.0
+
 cd %BUILD_DIR%
 robocopy "%SRCROOT%" "%BUILD_DIR%" /E /XD ".git" "%BUILD_DIR%" "_build" "cmake-build" /NP /NFL /NDL
 
@@ -34,22 +37,6 @@ if errorlevel 1 (
    exit /B 1
 )
 
-set MINGW=1
-call ..\.evergreen\scripts\check-installed-files-bson.bat
-if errorlevel 1 (
-   exit /B 1
-)
-set MINGW=
-
-if not exist %INSTALL_DIR%\lib\libbson-static-1.0.a (
-  echo libbson-static-1.0.a missing!
-  exit /B 1
-) else (
-  echo libbson-static-1.0.a check ok
-)
-
-cd %SRCROOT%
-
 rem Test our pkg-config file
 set EXAMPLE_DIR=%SRCROOT%\src\libbson\examples\
 cd %EXAMPLE_DIR%
@@ -60,7 +47,7 @@ exit /B 0
 set PKG_CONFIG_PATH=%INSTALL_DIR%\lib\pkgconfig
 
 rem http://stackoverflow.com/questions/2323292
-for /f %%i in ('pkg-config --libs --cflags libbson-1.0') do set PKG_CONFIG_OUT=%%i
+for /f %%i in ('pkg-config --libs --cflags bson%major%') do set PKG_CONFIG_OUT=%%i
 
 echo PKG_CONFIG_OUT is %PKG_CONFIG_OUT%
 
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program-mingw.cmd 2.0.2-1/.evergreen/scripts/link-sample-program-mingw.cmd
--- 1.30.4-1/.evergreen/scripts/link-sample-program-mingw.cmd	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program-mingw.cmd	2025-06-19 15:42:22.000000000 +0000
@@ -20,6 +20,8 @@ mkdir %INSTALL_DIR%
 
 set PATH=%PATH%;%INSTALL_DIR%\bin
 
+set major=1
+
 cd %BUILD_DIR%
 robocopy "%SRCROOT%" "%BUILD_DIR%" /E /XD ".git" "%BUILD_DIR%" "_build" "cmake-build" /NP /NFL /NDL
 
@@ -35,22 +37,6 @@ if errorlevel 1 (
    exit /B 1
 )
 
-set MINGW=1
-call ..\.evergreen\scripts\check-installed-files.bat
-if errorlevel 1 (
-   exit /B 1
-)
-set MINGW=
-
-if not exist %INSTALL_DIR%\lib\libmongoc-static-1.0.a (
-  echo libmongoc-static-1.0.a missing!
-  exit /B 1
-) else (
-  echo libmongoc-static-1.0.a check ok
-)
-
-cd %SRCROOT%
-
 rem Test our pkg-config file
 set EXAMPLE_DIR=%SRCROOT%\src\libmongoc\examples\
 cd %EXAMPLE_DIR%
@@ -61,7 +47,7 @@ exit /B 0
 set PKG_CONFIG_PATH=%INSTALL_DIR%\lib\pkgconfig
 
 rem http://stackoverflow.com/questions/2323292
-for /f %%i in ('pkg-config --libs --cflags libmongoc-1.0') do set PKG_CONFIG_OUT=%%i
+for /f %%i in ('pkg-config --libs --cflags mongoc%major%') do set PKG_CONFIG_OUT=%%i
 
 echo PKG_CONFIG_OUT is %PKG_CONFIG_OUT%
 
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program-msvc-bson.cmd 2.0.2-1/.evergreen/scripts/link-sample-program-msvc-bson.cmd
--- 1.30.4-1/.evergreen/scripts/link-sample-program-msvc-bson.cmd	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program-msvc-bson.cmd	2025-06-19 15:42:22.000000000 +0000
@@ -26,19 +26,14 @@ cd %BUILD_DIR%
 robocopy "%SRCROOT%" "%BUILD_DIR%" /E /XD ".git" "%BUILD_DIR%" "_build" "cmake-build" /NP /NFL /NDL
 
 if "%LINK_STATIC%"=="1" (
-  %CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_TESTS=OFF .
+  %CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_TESTS=OFF .
 ) else (
-  %CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_TESTS=OFF -DENABLE_STATIC=OFF .
+  %CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_TESTS=OFF -DENABLE_STATIC=OFF .
 )
 
 %CMAKE% --build . --target ALL_BUILD --config "Debug" -- /m
 %CMAKE% --build . --target INSTALL --config "Debug" -- /m
 
-call ..\.evergreen\scripts\check-installed-files-bson.bat
-if errorlevel 1 (
-   exit /B %errorlevel%
-)
-
 rem Test our CMake package config file with CMake's find_package command.
 set EXAMPLE_DIR=%SRCROOT%\src\libbson\examples\cmake\find_package
 
@@ -47,7 +42,7 @@ if "%LINK_STATIC%"=="1" (
 )
 
 cd %EXAMPLE_DIR%
-%CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake .
+%CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake .
 %CMAKE% --build . --target ALL_BUILD --config "Debug" -- /m
 
 rem Yes, they should've named it "dependencies".
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program-msvc.cmd 2.0.2-1/.evergreen/scripts/link-sample-program-msvc.cmd
--- 1.30.4-1/.evergreen/scripts/link-sample-program-msvc.cmd	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program-msvc.cmd	2025-06-19 15:42:22.000000000 +0000
@@ -33,7 +33,7 @@ if "%ENABLE_SNAPPY%"=="1" (
   curl -sS --retry 5 -LO https://github.com/google/snappy/archive/1.1.7.tar.gz
   %TAR% xzf 1.1.7.tar.gz
   cd snappy-1.1.7
-  %CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% .
+  %CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% .
   %CMAKE% --build . --target ALL_BUILD --config "Debug" -- /m
   %CMAKE% --build . --target INSTALL --config "Debug" -- /m
   set SNAPPY_OPTION=-DENABLE_SNAPPY=ON
@@ -44,37 +44,14 @@ if "%ENABLE_SNAPPY%"=="1" (
 cd %BUILD_DIR%
 rem Build libmongoc
 if "%ENABLE_SSL%"=="1" (
-  %CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_SSL=WINDOWS %ENABLE_SNAPPY_OPTION% .
+  %CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_SSL=WINDOWS %ENABLE_SNAPPY_OPTION% .
 ) else (
-  %CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_SSL=OFF %ENABLE_SNAPPY_OPTION% .
+  %CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DENABLE_SSL=OFF %ENABLE_SNAPPY_OPTION% .
 )
 
 %CMAKE% --build . --target ALL_BUILD --config "Debug" -- /m
 %CMAKE% --build . --target INSTALL --config "Debug" -- /m
 
-call ..\.evergreen\scripts\check-installed-files.bat
-if errorlevel 1 (
-   exit /B %errorlevel%
-)
-
-rem Shim library around the DLL.
-set SHIM=%INSTALL_DIR%\lib\mongoc-1.0.lib
-if not exist %SHIM% (
-  echo %SHIM% is missing!
-  exit /B 1
-) else (
-  echo %SHIM% check ok
-)
-
-if not exist %INSTALL_DIR%\lib\mongoc-static-1.0.lib (
-  echo mongoc-static-1.0.lib missing!
-  exit /B 1
-) else (
-  echo mongoc-static-1.0.lib check ok
-)
-
-cd %SRCROOT%
-
 rem Test our CMake package config file with CMake's find_package command.
 set EXAMPLE_DIR=%SRCROOT%\src\libmongoc\examples\cmake\find_package
 
@@ -90,7 +67,7 @@ if "%ENABLE_SSL%"=="1" (
   set MONGODB_EXAMPLE_URI="mongodb://localhost/?ssl=true&sslclientcertificatekeyfile=client.pem&sslcertificateauthorityfile=ca.pem&sslallowinvalidhostnames=true"
 )
 
-%CMAKE% -G "Visual Studio 15 2017 Win64" -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake .
+%CMAKE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_PREFIX_PATH=%INSTALL_DIR%\lib\cmake .
 %CMAKE% --build . --target ALL_BUILD --config "Debug" -- /m
 
 rem Yes, they should've named it "dependencies".
diff -pruN 1.30.4-1/.evergreen/scripts/link-sample-program.sh 2.0.2-1/.evergreen/scripts/link-sample-program.sh
--- 1.30.4-1/.evergreen/scripts/link-sample-program.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/link-sample-program.sh	2025-06-19 15:42:22.000000000 +0000
@@ -4,30 +4,32 @@ set -o errexit  # Exit the script with e
 # Supported/used environment variables:
 #   LINK_STATIC                Whether to statically link to libmongoc
 #   BUILD_SAMPLE_WITH_CMAKE    Link program w/ CMake. Default: use pkg-config.
-#   BUILD_SAMPLE_WITH_CMAKE_DEPRECATED  If BUILD_SAMPLE_WITH_CMAKE is set, then use deprecated CMake scripts instead.
 #   ENABLE_SSL                 Set -DENABLE_SSL
 #   ENABLE_SNAPPY              Set -DENABLE_SNAPPY
 #   CMAKE                      Path to cmake executable.
 
 
-echo "LINK_STATIC=$LINK_STATIC BUILD_SAMPLE_WITH_CMAKE=$BUILD_SAMPLE_WITH_CMAKE BUILD_SAMPLE_WITH_CMAKE_DEPRECATED=$BUILD_SAMPLE_WITH_CMAKE_DEPRECATED"
+echo "LINK_STATIC=$LINK_STATIC BUILD_SAMPLE_WITH_CMAKE=$BUILD_SAMPLE_WITH_CMAKE"
 
 DIR=$(dirname $0)
 . $DIR/find-cmake-latest.sh
 CMAKE=$(find_cmake_latest)
 . $DIR/check-symlink.sh
 
+# The major version of the project. Appears in certain install filenames.
+_full_version=$(cat "$DIR/../../VERSION_CURRENT")
+version="${_full_version%-*}"  # 1.2.3-dev → 1.2.3
+major="${version%%.*}"         # 1.2.3     → 1
+echo "major version: $major"
+echo " full version: $version"
+
 # Get the kernel name, lowercased
 OS=$(uname -s | tr '[:upper:]' '[:lower:]')
 echo "OS: $OS"
 
 if [ "$OS" = "darwin" ]; then
-  SO=dylib
-  LIB_SO=libmongoc-1.0.0.dylib
   LDD="otool -L"
 else
-  SO=so
-  LIB_SO=libmongoc-1.0.so.0
   LDD=ldd
 fi
 
@@ -76,9 +78,13 @@ ZSTD="AUTO"
 if [[ -f $DIR/find-ccache.sh ]]; then
   . $DIR/find-ccache.sh
   find_ccache_and_export_vars "$SCRATCH_DIR" || true
+  if command -v "${CMAKE_C_COMPILER_LAUNCHER:-}" && [[ "${OSTYPE:?}" == cygwin ]]; then
+    configure_flags_append "-DCMAKE_POLICY_DEFAULT_CMP0141=NEW"
+    configure_flags_append "-DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=$<$<CONFIG:Debug,RelWithDebInfo>:Embedded>"
+  fi
 fi
 
-$CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DCMAKE_PREFIX_PATH=$INSTALL_DIR/lib/cmake $SSL_CMAKE_OPTION $SNAPPY_CMAKE_OPTION $STATIC_CMAKE_OPTION -DENABLE_ZSTD=$ZSTD "$SCRATCH_DIR"
+$CMAKE -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DCMAKE_PREFIX_PATH=$INSTALL_DIR/lib/cmake -DBUILD_TESTING=OFF $SSL_CMAKE_OPTION $SNAPPY_CMAKE_OPTION $STATIC_CMAKE_OPTION -DENABLE_ZSTD=$ZSTD "$SCRATCH_DIR"
 $CMAKE --build . --parallel
 $CMAKE --build . --parallel --target install
 
@@ -87,100 +93,17 @@ unset CCACHE_BASEDIR CCACHE_NOHASHDIR
 
 ls -l $INSTALL_DIR/lib
 
-set +o xtrace
-
-# Check on Linux that libmongoc is installed into lib/ like:
-# libmongoc-1.0.so -> libmongoc-1.0.so.0
-# libmongoc-1.0.so.0 -> libmongoc-1.0.so.0.0.0
-# libmongoc-1.0.so.0.0.0
-if [ "$OS" != "darwin" ]; then
-  # From check-symlink.sh
-  check_symlink libmongoc-1.0.so libmongoc-1.0.so.0
-  check_symlink libmongoc-1.0.so.0 libmongoc-1.0.so.0.0.0
-  SONAME=$(objdump -p $INSTALL_DIR/lib/$LIB_SO|grep SONAME|awk '{print $2}')
-  EXPECTED_SONAME="libmongoc-1.0.so.0"
-  if [ "$SONAME" != "$EXPECTED_SONAME" ]; then
-    echo "SONAME should be $EXPECTED_SONAME, not $SONAME"
-    exit 1
-  else
-    echo "library name check ok, SONAME=$SONAME"
-  fi
-else
-  # Just test that the shared lib was installed.
-  if test ! -f $INSTALL_DIR/lib/$LIB_SO; then
-    echo "$LIB_SO missing!"
-    exit 1
-  else
-    echo "$LIB_SO check ok"
-  fi
-fi
-
-
-if test ! -f $INSTALL_DIR/lib/pkgconfig/libmongoc-1.0.pc; then
-  echo "libmongoc-1.0.pc missing!"
-  exit 1
-else
-  echo "libmongoc-1.0.pc check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/mongoc-1.0/mongoc-1.0-config.cmake; then
-  echo "mongoc-1.0-config.cmake missing!"
-  exit 1
-else
-  echo "mongoc-1.0-config.cmake check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/mongoc-1.0/mongoc-1.0-config-version.cmake; then
-  echo "mongoc-1.0-config-version.cmake missing!"
-  exit 1
-else
-  echo "mongoc-1.0-config-version.cmake check ok"
-fi
-if test ! -f $INSTALL_DIR/lib/cmake/mongoc-1.0/mongoc-targets.cmake; then
-  echo "mongoc-targets.cmake missing!"
-  exit 1
-else
-  echo "mongoc-targets.cmake check ok"
-fi
-
-
-if [ "$LINK_STATIC" ]; then
-  if test ! -f $INSTALL_DIR/lib/libmongoc-static-1.0.a; then
-    echo "libmongoc-static-1.0.a missing!"
-    exit 1
-  else
-    echo "libmongoc-static-1.0.a check ok"
-  fi
-  if test ! -f $INSTALL_DIR/lib/pkgconfig/libmongoc-static-1.0.pc; then
-    echo "libmongoc-static-1.0.pc missing!"
-    exit 1
-  else
-    echo "libmongoc-static-1.0.pc check ok"
-  fi
-else
-  if test -f $INSTALL_DIR/lib/libmongoc-static-1.0.a; then
-    echo "libmongoc-static-1.0.a shouldn't have been installed"
-    exit 1
-  fi
-  if test -f $INSTALL_DIR/lib/libmongoc-1.0.a; then
-    echo "libmongoc-1.0.a shouldn't have been installed"
-    exit 1
-  fi
-  if test -f $INSTALL_DIR/lib/pkgconfig/libmongoc-static-1.0.pc; then
-    echo "libmongoc-static-1.0.pc shouldn't have been installed"
-    exit 1
-  fi
-fi
-
-if [ "$OS" = "darwin" && "${HOSTTYPE:?}" != "arm64" ]; then
-  if test -f $INSTALL_DIR/bin/mongoc-stat; then
-    echo "mongoc-stat shouldn't have been installed"
+if [ "$OS" = "darwin" ] && [ "${HOSTTYPE:?}" != "arm64" ]; then
+  if test -f $INSTALL_DIR/bin/mongoc$major-stat; then
+    echo "mongoc$major-stat shouldn't have been installed"
     exit 1
   fi
 else
-  if test ! -f $INSTALL_DIR/bin/mongoc-stat; then
-    echo "mongoc-stat missing!"
+  if test ! -f $INSTALL_DIR/bin/mongoc$major-stat; then
+    echo "mongoc$major-stat missing!"
     exit 1
   else
-    echo "mongoc-stat check ok"
+    echo "mongoc$major-stat check ok"
   fi
 fi
 
@@ -206,12 +129,12 @@ else
 
   if [ "$LINK_STATIC" ]; then
     echo "pkg-config output:"
-    echo $(pkg-config --libs --cflags libmongoc-static-1.0)
-    ./compile-with-pkg-config-static.sh
+    echo $(pkg-config --libs --cflags mongoc$major-static)
+    env major=$major ./compile-with-pkg-config-static.sh
   else
     echo "pkg-config output:"
-    echo $(pkg-config --libs --cflags libmongoc-1.0)
-    ./compile-with-pkg-config.sh
+    echo $(pkg-config --libs --cflags mongoc$major)
+    env major=$major ./compile-with-pkg-config.sh
   fi
 fi
 
diff -pruN 1.30.4-1/.evergreen/scripts/run-auth-tests.sh 2.0.2-1/.evergreen/scripts/run-auth-tests.sh
--- 1.30.4-1/.evergreen/scripts/run-auth-tests.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/run-auth-tests.sh	2025-06-19 15:42:22.000000000 +0000
@@ -27,11 +27,9 @@ chmod 700 "${secrets_dir}"
 # Create certificate to test X509 auth with Atlas:
 atlas_x509_path="${secrets_dir:?}/atlas_x509.pem"
 echo "${atlas_x509_cert_base64:?}" | base64 --decode > "${secrets_dir:?}/atlas_x509.pem"
-# On Windows, convert certificate to PKCS#1 to work around CDRIVER-4269:
+# Fix path on Windows:
 if $IS_WINDOWS; then
-    openssl pkey -in "${secrets_dir:?}/atlas_x509.pem" -traditional > "${secrets_dir:?}/atlas_x509_pkcs1.pem"
-    openssl x509 -in "${secrets_dir:?}/atlas_x509.pem" >> "${secrets_dir:?}/atlas_x509_pkcs1.pem"
-    atlas_x509_path="$(cygpath -m "${secrets_dir:?}/atlas_x509_pkcs1.pem")"
+    atlas_x509_path="$(cygpath -m "${secrets_dir:?}/atlas_x509.pem")"
 fi
 
 # Create Kerberos config and keytab files.
@@ -98,7 +96,7 @@ esac
 
 # Archlinux (which we use for testing various self-installed OpenSSL versions)
 # stores their trust list under /etc/ca-certificates/extracted/.
-# We need to copy it to our custom installed OpenSSL/LibreSSL trust store.
+# We need to copy it to our custom installed OpenSSL trust store.
 declare pem_file="/etc/ca-certificates/extracted/tls-ca-bundle.pem"
 if [[ -f "${pem_file}" ]]; then
   [[ ! -d "${install_dir}" ]] || cp -v "${pem_file}" "${install_dir}/cert.pem"
diff -pruN 1.30.4-1/.evergreen/scripts/run-ocsp-cache-test.sh 2.0.2-1/.evergreen/scripts/run-ocsp-cache-test.sh
--- 1.30.4-1/.evergreen/scripts/run-ocsp-cache-test.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/.evergreen/scripts/run-ocsp-cache-test.sh	2025-06-19 15:42:22.000000000 +0000
@@ -68,7 +68,7 @@ if [[ -d "${openssl_install_dir}" ]]; th
 fi
 
 # This test will hang after the first ping.
-LD_LIBRARY_PATH="${openssl_lib_prefix}" "${mongoc_dir}/src/libmongoc/test-mongoc-cache" "${mongoc_dir}/.evergreen/ocsp/${CERT_TYPE}/ca.pem" &
+LD_LIBRARY_PATH="${openssl_lib_prefix}" "${mongoc_dir}/cmake-build/src/libmongoc/test-mongoc-cache" "${mongoc_dir}/.evergreen/ocsp/${CERT_TYPE}/ca.pem" &
 sleep 5 # Give the program time to contact the OCSP responder
 
 pkill -nf "ocsp_mock" # We assume that the mock OCSP responder is named "ocsp_mock"
diff -pruN 1.30.4-1/CMakeLists.txt 2.0.2-1/CMakeLists.txt
--- 1.30.4-1/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -111,15 +111,13 @@ mongo_bool_setting(USE_BUNDLED_UTF8PROC
                    ADVANCED)
 mongo_setting(
    ENABLE_SSL [[Enable TLS connection and SCRAM authentication.]]
-   OPTIONS WINDOWS DARWIN OPENSSL LIBRESSL OFF AUTO
+   OPTIONS WINDOWS DARWIN OPENSSL OFF AUTO
    DEFAULT VALUE AUTO
    VALIDATE CODE [[
       if(ENABLE_SSL STREQUAL "DARWIN" AND NOT APPLE)
          message(WARNING "ENABLE_SSL=DARWIN is only supported on Apple platforms")
       elseif(ENABLE_SSL STREQUAL "WINDOWS" AND NOT WIN32)
          message(WARNING "ENABLE_SSL=WINDOWS is only supported on Windows platforms")
-      elseif (ENABLE_SSL STREQUAL "LIBRESSL")
-         message(DEPRECATION "ENABLE_SSL=LIBRESSL is deprecated and may be removed in a future major release")
       endif()
    ]]
 )
@@ -149,21 +147,11 @@ mongo_setting(
          message(WARNING "ENABLE_SASL=SSPI is only supported on Windows platforms")
       endif()
       if(ENABLE_SASL STREQUAL "CYRUS" AND WIN32)
-         message(DEPRECATION "ENABLE_SASL=CYRUS on Windows platforms is deprecated and may be removed in a future major release")
+         message(WARNING "ENABLE_SASL=CYRUS on Windows platforms is unsupported. Use ENABLE_SASL=SSPI or ENABLE_SASL=OFF instead")
       endif()
    ]]
 )
 
-mongo_setting(CYRUS_PLUGIN_PATH_PREFIX "An absolute path prefix to enable loading Cyrus SASL plugins on Windows"
-   TYPE STRING
-   VISIBLE_IF [[ENABLE_SASL STREQUAL "CYRUS" AND WIN32]]
-   VALIDATE CODE [[
-      if (CYRUS_PLUGIN_PATH_PREFIX)
-         message(DEPRECATION "CYRUS_PLUGIN_PATH_PREFIX is deprecated and may be removed in a future major release")
-      endif ()
-   ]]
-)
-
 mongo_setting(ENABLE_CLIENT_SIDE_ENCRYPTION "Enable In-Use Encryption support. Requires additional support libraries."
               OPTIONS ON OFF AUTO
               DEFAULT VALUE AUTO)
@@ -184,8 +172,6 @@ mongo_setting(ENABLE_MONGODB_AWS_AUTH "E
 # Optional features that are DISABLED by default:
 mongo_bool_setting(ENABLE_RDTSCP "Enable fast performance counters using the Intel RDTSCP instruction"
                    DEFAULT VALUE OFF)
-mongo_bool_setting(ENABLE_APPLE_FRAMEWORK "Build libraries as Apple Frameworks on Darwin platforms"
-                   DEFAULT VALUE OFF)
 mongo_bool_setting(
    ENABLE_CRYPTO_SYSTEM_PROFILE "Use system crypto profile"
    DEFAULT VALUE OFF
@@ -196,41 +182,8 @@ mongo_bool_setting(
    ]]
 )
 
-# Deprecated options:
-mongo_bool_setting(
-   ENABLE_AUTOMATIC_INIT_AND_CLEANUP
-      "[Deprecated] Enable automatic initialization of the C driver library"
-   DEFAULT EVAL [[
-         set(DEFAULT OFF)
-         if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
-            message(VERBOSE "For backwards compatibility, when using GCC the default of "
-                            "ENABLE_AUTOMATIC_INIT_AND_CLEANUP is ON")
-            set(DEFAULT ON)
-         endif()
-      ]]
-      DEVEL VALUE OFF
-   VALIDATE CODE [[
-      if(ENABLE_AUTOMATIC_INIT_AND_CLEANUP)
-         if(NOT CMAKE_C_COMPILER_ID STREQUAL "GNU")
-            message(WARNING "ENABLE_AUTOMATIC_INIT_AND_CLEANUP is only supported on GCC.")
-         endif()
-         message(DEPRECATION
-                  "Enabling ENABLE_AUTOMATIC_INIT_AND_CLEANUP is deprecated and "
-                  "may be removed in a future release")
-      endif()
-   ]]
-)
-mongo_bool_setting(
-   ENABLE_EXTRA_ALIGNMENT
-      "[Deprecated] Enable extra alignment on libbson types"
-   DEFAULT VALUE ON
-      DEVEL VALUE OFF
-   VALIDATE CODE [[
-      if(ENABLE_EXTRA_ALIGNMENT AND MONGO_SANITIZE MATCHES "undefined")
-         message(WARNING "ENABLE_EXTRA_ALIGNMENT=“${ENABLE_EXTRA_ALIGNMENT}” will create conflicts with UndefinedBehaviorSanitizer")
-      endif()
-   ]]
-)
+# Announce the build configuration. Used by `mlib_build_config_is()` in `mlib/config.h`
+add_compile_definitions(_MLIB_BUILD_CONFIG=$<CONFIG>)
 
 if(ENABLE_COVERAGE)
    mongo_platform_link_options(--coverage)
@@ -331,6 +284,9 @@ if(ENABLE_MAINTAINER_FLAGS)
       gnu-like:-Wuninitialized
       # Disabled, for now:
       gnu-like:-Wno-strict-aliasing
+      # Sign-comparison-mismatch:
+      gnu-like:-Wsign-compare
+      msvc:/we4018
    )
 endif()
 
@@ -343,8 +299,6 @@ if ( (ENABLE_BUILD_DEPENDECIES STREQUAL
    set (ENABLE_BUILD_DEPENDECIES ON)
 endif ()
 
-mongo_pick(BSON_EXTRA_ALIGN 1 0 ENABLE_EXTRA_ALIGNMENT)
-
 mongo_pick(MONGOC_ENABLE_RDTSCP 1 0 ENABLE_RDTSCP)
 
 mongo_pick(MONGOC_ENABLE_STATIC_BUILD 1 0 ENABLE_STATIC)
@@ -352,31 +306,17 @@ mongo_pick(MONGOC_ENABLE_STATIC_INSTALL
            [[ENABLE_STATIC AND NOT ENABLE_STATIC STREQUAL "BUILD_ONLY"]])
 
 if (USE_SYSTEM_LIBBSON)
-   # The input variable BSON_ROOT_DIR is respected for backwards compatibility,
-   # but you should use the standard CMAKE_PREFIX_PATH instead.
-   message (STATUS "Searching for libbson CMake packages")
-   find_package (bson-1.0
-      "${PROJECT_VERSION}"
-      HINTS
-      ${BSON_ROOT_DIR})
-
-   if (NOT bson-1.0_FOUND)
-      message (FATAL_ERROR "System libbson not found")
-   endif ()
-
-   message (STATUS "libbson found version \"${bson-1.0_VERSION}\"")
-   message (STATUS "disabling test-libmongoc since using system libbson")
-   SET (ENABLE_TESTS OFF)
+   find_package (bson "${PROJECT_VERSION}" REQUIRED)
+   # Disable test-libmongoc since we are using a system libbson
+   set (ENABLE_TESTS OFF)
 
    set (USING_SYSTEM_BSON TRUE)
-   if (NOT TARGET mongo::bson_shared)
-           message (FATAL_ERROR "System libbson built without shared library target")
+   if (NOT TARGET bson::shared)
+      message (FATAL_ERROR "System libbson built without shared library target")
    endif ()
-   set (BSON_LIBRARIES mongo::bson_shared)
-   if (NOT TARGET mongo::bson_static)
-           message (FATAL_ERROR "System libbson built without static library target")
+   if (NOT TARGET bson::static)
+      message (FATAL_ERROR "System libbson built without static library target")
    endif ()
-   set (BSON_STATIC_LIBRARIES mongo::bson_static)
 endif ()
 
 set (BUILD_SOURCE_DIR ${CMAKE_BINARY_DIR})
@@ -399,9 +339,15 @@ set (CMAKE_BUILD_WITH_INSTALL_RPATH OFF)
 # Include any custom library paths in the final RPATH.
 set (CMAKE_INSTALL_RPATH_USE_LINK_PATH ON)
 
-# Install libs with names like @rpath/libmongoc-1.0.0.dylib, not bare names.
+# Install libs with names like @rpath/libfoo.dylib, not bare names.
 set (CMAKE_MACOSX_RPATH ON)
 
+# Distinguish DLL import libs with a .dll.lib suffix. Also prevents filename collisions
+# between static libraries and the import libraries
+if(WIN32)
+   set (CMAKE_IMPORT_LIBRARY_SUFFIX .dll.lib)
+endif()
+
 # https://cmake.org/cmake/help/v3.11/policy/CMP0042.html
 # Enable a CMake 3.0+ policy that sets CMAKE_MACOSX_RPATH by default, and
 # silence a CMake 3.11 warning that the old behavior is deprecated.
@@ -449,14 +395,7 @@ add_subdirectory (src/common)
 
 if (NOT USING_SYSTEM_BSON)
    message (STATUS "Using bundled libbson")
-
    add_subdirectory (src/libbson)
-   # Defined in src/libbson/CMakeLists.txt
-   set (BSON_STATIC_LIBRARIES bson_static)
-   set (BSON_LIBRARIES bson_shared)
-   set (BSON_STATIC_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/src/libbson/src" "${PROJECT_BINARY_DIR}/src/libbson/src")
-   set (BSON_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/src/libbson/src" "${PROJECT_BINARY_DIR}/src/libbson/src")
-   set (BSON_STATIC_PUBLIC_DEFINITIONS "BSON_STATIC")
 endif ()
 
 if (MSVC)
@@ -476,11 +415,6 @@ if (ENABLE_MONGOC)
    # Ensure the default behavior: don't ignore RPATH settings.
    set (CMAKE_SKIP_BUILD_RPATH OFF)
 
-   if (APPLE)
-      # Until CDRIVER-520.
-      add_definitions (-Wno-deprecated-declarations)
-   endif ()
-
    if (NOT ENABLE_MONGODB_AWS_AUTH MATCHES "ON|OFF|AUTO")
       message (FATAL_ERROR "ENABLE_MONGODB_AWS_AUTH option must be ON, AUTO, or OFF")
    endif ()
@@ -531,7 +465,7 @@ if (ENABLE_MONGOC)
 endif ()
 
 install (FILES COPYING NEWS README.rst THIRD_PARTY_NOTICES
-   DESTINATION ${CMAKE_INSTALL_DATADIR}/mongo-c-driver
+   DESTINATION ${CMAKE_INSTALL_DATADIR}/mongo-c-driver/${PROJECT_VERSION}
 )
 
 if (ENABLE_UNINSTALL)
@@ -543,7 +477,7 @@ if (ENABLE_UNINSTALL)
       # Generate a different script name for uninstalling libbson only:
       set (UNINSTALL_SCRIPT_NAME "uninstall-bson")
    endif ()
-   set (UNINSTALL_PROG_DIR "${CMAKE_INSTALL_DATADIR}/mongo-c-driver")
+   set (UNINSTALL_PROG_DIR "${CMAKE_INSTALL_DATADIR}/mongo-c-driver/${PROJECT_VERSION}")
    include (GenerateUninstaller)
 endif ()
 
diff -pruN 1.30.4-1/CONTRIBUTING.md 2.0.2-1/CONTRIBUTING.md
--- 1.30.4-1/CONTRIBUTING.md	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/CONTRIBUTING.md	2025-06-19 15:42:22.000000000 +0000
@@ -289,8 +289,9 @@ The set of mock KMS servers running in t
 | 8999 | ca.pem | server.pem | python -u kms_http_server.py --ca_file ../x509gen/ca.pem --cert_file ../x509gen/server.pem --port 8999
 | 9000 | ca.pem | expired.pem | python -u kms_http_server.py --ca_file ../x509gen/ca.pem --cert_file ../x509gen/expired.pem --port 9000
 | 9001 | ca.pem | wrong-host.pem | python -u kms_http_server.py --ca_file ../x509gen/ca.pem --cert_file ../x509gen/wrong-host.pem --port 9001
-| 9002 | ca.pem | server.pem | python -u kms_http_server.py --ca_file ../x509gen/ca.pem --cert_file ../x509gen/server.pem --port --require_client_cert 9002
+| 9002 | ca.pem | server.pem | python -u kms_http_server.py --ca_file ../x509gen/ca.pem --cert_file ../x509gen/server.pem --require_client_cert --port 9002
 | 5698 | ca.pem | server.pem | python -u kms_kmip_server.py
+| 9003 | ca.pem | server.pem | python kms_failpoint_server.py --port 9003
 
 The path to `ca.pem` and `client.pem` must be passed through the following environment variables:
 
diff -pruN 1.30.4-1/Earthfile 2.0.2-1/Earthfile
--- 1.30.4-1/Earthfile	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/Earthfile	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,5 @@
 VERSION --arg-scope-and-set --pass-args 0.7
-FROM alpine:3.21
+LOCALLY
 
 IMPORT ./tools/ AS tools
 
@@ -37,10 +37,8 @@ build:
         "$source_dir"
     ENV CCACHE_HOME=/root/.cache/ccache
     RUN cmake -S "$source_dir" -B "$build_dir" -G "Ninja Multi-Config" \
-        -D ENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF \
         -D ENABLE_MAINTAINER_FLAGS=ON \
         -D ENABLE_SHM_COUNTERS=ON \
-        -D ENABLE_EXTRA_ALIGNMENT=OFF \
         -D ENABLE_SASL=$(echo $sasl | __str upper) \
         -D ENABLE_SNAPPY=ON \
         -D ENABLE_SRV=ON \
@@ -66,7 +64,6 @@ test-example:
     # Add the example files
     COPY --dir \
         src/libmongoc/examples/cmake \
-        src/libmongoc/examples/cmake-deprecated \
         src/libmongoc/examples/hello_mongoc.c \
         /opt/mongoc-test/
     # Configure and build it
@@ -147,20 +144,11 @@ multibuild:
         --sasl=Cyrus --sasl=off \
         --c_compiler=gcc --c_compiler=clang \
         --test_mongocxx_ref=master
-    # Note: At time of writing, Ubuntu does not support LibreSSL, so run those
-    #   tests on a separate BUILD line that does not include Ubuntu:
-    BUILD +run --targets "test-example" \
-        --env=alpine3.16 --env=alpine3.17 --env=alpine3.18 --env=alpine3.19 \
-        --env=archlinux \
-        --tls=LibreSSL \
-        --sasl=Cyrus --sasl=off \
-        --c_compiler=gcc --c_compiler=clang \
-        --test_mongocxx_ref=master
 
 # release-archive :
 #   Create a release archive of the source tree. (Refer to dev docs)
 release-archive:
-    FROM artifactory.corp.mongodb.com/dockerhub/library/alpine:3.20
+    FROM alpine:3.20
     RUN apk add git bash
     ARG --required prefix
     ARG --required ref
@@ -205,7 +193,7 @@ release-archive:
 
 # Obtain the signing public key. Exported as an artifact /c-driver.pub
 signing-pubkey:
-    FROM artifactory.corp.mongodb.com/dockerhub/library/alpine:3.20
+    FROM alpine:3.20
     RUN apk add curl
     RUN curl --location --silent --fail "https://pgp.mongodb.com/c-driver.pub" -o /c-driver.pub
     SAVE ARTIFACT /c-driver.pub
@@ -235,7 +223,7 @@ sign-file:
 #   Generate a signed release artifact. Refer to the "Earthly" page of our dev docs for more information.
 #   (Refer to dev docs)
 signed-release:
-    FROM artifactory.corp.mongodb.com/dockerhub/library/alpine:3.20
+    FROM alpine:3.20
     RUN apk add git
     # The version of the release. This affects the filepaths of the output and is the default for --ref
     ARG --required version
@@ -324,7 +312,7 @@ sbom-validate:
             --exclude jira
 
 snyk:
-    FROM --platform=linux/amd64 artifactory.corp.mongodb.com/dockerhub/library/ubuntu:24.04
+    FROM --platform=linux/amd64 ubuntu:24.04
     RUN apt-get update && apt-get -y install curl
     RUN curl --location https://github.com/snyk/cli/releases/download/v1.1291.1/snyk-linux -o /usr/local/bin/snyk
     RUN chmod a+x /usr/local/bin/snyk
@@ -396,7 +384,7 @@ test-vcpkg-manifest-mode:
         make test-manifest-mode
 
 vcpkg-base:
-    FROM artifactory.corp.mongodb.com/dockerhub/library/alpine:3.18
+    FROM alpine:3.18
     RUN apk add cmake curl gcc g++ musl-dev ninja-is-really-ninja zip unzip tar \
                 build-base git pkgconf perl bash linux-headers
     ENV VCPKG_ROOT=/opt/vcpkg-git
@@ -455,7 +443,7 @@ env.alpine3.19:
     DO --pass-args +ALPINE_ENV --version=3.19
 
 env.archlinux:
-    FROM --pass-args tools+init-env --from artifactory.corp.mongodb.com/dockerhub/library/archlinux
+    FROM --pass-args tools+init-env --from archlinux
     RUN pacman-key --init
     ARG --required purpose
 
@@ -476,7 +464,7 @@ env.centos7:
 ALPINE_ENV:
     COMMAND
     ARG --required version
-    FROM --pass-args tools+init-env --from artifactory.corp.mongodb.com/dockerhub/library/alpine:$version
+    FROM --pass-args tools+init-env --from alpine:$version
     # XXX: On Alpine, we just use the system's CMake. At time of writing, it is
     # very up-to-date and much faster than building our own from source (since
     # Kitware does not (yet) provide libmuslc builds of CMake)
@@ -498,7 +486,7 @@ ALPINE_ENV:
 UBUNTU_ENV:
     COMMAND
     ARG --required version
-    FROM --pass-args tools+init-env --from artifactory.corp.mongodb.com/dockerhub/library/ubuntu:$version
+    FROM --pass-args tools+init-env --from ubuntu:$version
     RUN __install curl build-essential
     ARG --required purpose
 
@@ -516,7 +504,7 @@ UBUNTU_ENV:
 CENTOS_ENV:
     COMMAND
     ARG --required version
-    FROM --pass-args tools+init-env --from artifactory.corp.mongodb.com/dockerhub/library/centos:$version
+    FROM --pass-args tools+init-env --from centos:$version
     # Update repositories to use vault.centos.org
     RUN sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-* && \
         sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
diff -pruN 1.30.4-1/NEWS 2.0.2-1/NEWS
--- 1.30.4-1/NEWS	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/NEWS	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,21 @@
-libmongoc 1.30.4
-================
+libmongoc 2.0.2
+===============
+
+Fixes:
+
+  * Fix message of `bson_strerror_r` on Windows.
+  * Fix memory leaks with Windows Secure Channel.
+  * Fix loading PKCS#8 RSA keys with Windows Secure Channel.
+
+Thanks to everyone who contributed to the development of this release.
+
+  * Kevin Albertson
+  * Colby Pike
+
+
+
+libmongoc 2.0.1
+===============
 
 Fixes:
 
@@ -12,32 +28,188 @@ Thanks to everyone who contributed to th
 
 
 
-libmongoc 1.30.3
-================
+libmongoc 2.0.0
+===============
 
-New Features:
+## Notes
+
+* In a future minor release the minimum supported MongoDB Server version will be raised from 4.0 to 4.2. This is in accordance with [MongoDB Software Lifecycle Schedules](https://www.mongodb.com/legal/support-policy/lifecycles).
+* Raise required version of libmongocrypt to 1.13.0 to support In-Use Encryption (corresponds to the CMake option: `ENABLE_CLIENT_SIDE_ENCRYPTION`).
 
-* In anticipation of the 2.0 release of mongo-c-driver, new CMake packages and
-  imported targets have been defined (for both `bson` and `mongoc`). To import
-  `mongoc` with the new names, call `find_package` for the `mongoc` package. The
-  new imported targets are named `mongoc::static`, `mongoc::shared`, and
-  `mongoc::mongoc` (which points to either the static or the shared library,
-  depending on an import-time configuration option).
-
-  The new package and target names will remain unchanged when upgrading to the
-  2.0 release, allowing consumers to support both major versions without
-  modifying their CMake project. The current imported target names will be
-  removed from the 2.0 release, and should not be used for
-  forward-compatibility.
+## Changes
+
+* Passing `batchSize:0` as an option to `mongoc_client_watch`, `mongoc_database_watch`, or `mongoc_collection_watch`
+  now applies `batchSize:0` to the `aggregate` command. Useful to request an immediate cursor. Previously the value
+  was ignored.
+* `bson_oid_init_sequence` is removed. Use `bson_oid_init` instead.
+* `mongoc_server_description_host` changes the return type from `mongoc_host_list_t *` to `const mongoc_host_list_t *`.
+* URI authentication credentials validation (only applicable during creation of a new `mongoc_uri_t` object from a connection string):
+  * The requirement that a username is non-empty when specified is now enforced regardless of authentication mechanism.
+  * Username and password specification requirements are now validated and returns a client error for the specified authentication mechanism.
+    * e.g. it is a client error to not specify a username or a password for SCRAM-SHA-1, SCRAM-SHA-256, and PLAIN.
+    * e.g. it is a client error to specify a password for MONGODB-X509.
+    * e.g. it is a client error to specify a username or a password without the other for MONGODB-AWS.
+  * `authSource` is now correctly defaulted to `"$external"` for MONGODB-AWS (instead of the database name or `"admin"`).
+  * `authMechanism` is now validated and returns a client error for invalid or unsupported values.
+  * `authMechanismProperties` is now validated and returns a client error for invalid or unsupported properties for the specified authentication mechanism.
+  * `authMechanismProperties` now correctly supports `':'` within property values.
+    * Old behavior: `authMechanismProperties=A:B,C:D:E,F:G` is parsed as `{'A': 'B', 'C': 'D:E,F:G'}`.
+    * New behavior: `authMechanismProperties=A:B,C:D:E,F:G` is parsed as `{'A': 'B': 'C': 'D:E', 'F': 'G'}`.
+* Calling `mongoc_bulk_operation_execute` on the same `mongoc_bulk_operation_t` repeatedly is an error. Previously this was only discouraged in documentation.
+* Consistently apply `__cdecl` calling convention to function declarations in public API. Intended to support consumers building their code using a different [default calling convention](https://learn.microsoft.com/en-us/cpp/build/reference/gd-gr-gv-gz-calling-convention) with MSVC. The mongoc and bson libraries only support being built with the `__cdecl` default calling convention.
+* `mongoc_client_set_ssl_opts` now ignores a pooled `mongoc_client_t` and logs an error. Use `mongoc_client_pool_set_ssl_opts` to set TLS options on a `mongoc_client_pool_t` before popping any clients.
+* `mongoc_client_set_ssl_stream_initiator` now ignores a pooled `mongoc_client_t` and logs an error.
+* The pkg-config files `libmongoc-1.0`, `libmongoc-static-1.0`, `libbson-1.0`,
+  and `libbson-static-1.0` have been renamed to `mongoc2`, `mongoc2-static`,
+  `bson2`, and `bson2-static`, respectively.
+
+### CMake Packages and Imported Targets
+
+The `mongoc-1.0` (and `bson-1.0`) CMake packages have been removed. Instead, use
+`mongoc` or `bson`, and specify a version or version range to be imported:
+
+```cmake
+find_package(mongoc 1.30...2.0)
+```
+
+The new packages import different target names:
+
+- `mongo::mongoc_static` → `mongoc::static`
+- `mongo::mongoc_shared` → `mongoc::shared`
+- The target `mongoc::mongoc` is a shim target that points to either the shared
+  library or the static library.
+
+The BSON library has had similar name changes.
+
+## Removals
+
+* The `bson_md5_t` struct and associated API is removed.
+* The client side matching feature, `mongoc_matcher_t` and related functions are removed.
+* `mongoc_server_description_ismaster` is removed. Use the equivalent `mongoc_server_description_hello` instead.
+* `MONGOC_QUERY_SLAVE_OK` is removed. Use the equivalent `MONGOC_QUERY_SECONDARY_OK` instead.
+* `MONGOC_URI_SLAVEOK` is removed. It was unused.
+* `mongoc_client_command`, `mongoc_database_command`, and `mongoc_collection_command` are removed. Use `mongoc_client_command_simple`,  `mongoc_database_command_simple`, and `mongoc_collection_command_simple` instead.
+* `MONGOC_URI_MAXIDLETIMEMS` and `MONGOC_URI_WAITQUEUEMULTIPLE` are removed. They were unused.
+* `bson_string_t` and associated functions are removed.
+* Support for `ENABLE_SASL=CYRUS` on Windows is removed. Use `ENABLE_SASL=SSPI` or `ENABLE_SASL=OFF` instead.
+    * The associated Windows-only option `CYRUS_PLUGIN_PATH_PREFIX` is removed.
+* Support for the deprecated `minPoolSize` URI option is removed along with associated API: `MONGOC_URI_MINPOOLSIZE` and `mongoc_client_pool_min_size`.
+* Support for LibreSSL (the CMake option `ENABLE_SSL=LIBRESSL`) is removed. Associated API is removed (`MONGOC_ENABLE_SSL_LIBRESSL` and  `mongoc_stream_tls_libressl_new`).
+* `MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED` (value -1) is removed. Use `MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED` (value 0) which is handled equivalently. If specified in a URI, replace: `mongodb://host/?w=-1` with `mongodb://host/?w=0`.
+* The deprecated CMake option `ENABLE_AUTOMATIC_INIT_AND_CLEANUP` is removed. See [Initialization and cleanup](https://mongoc.org/libmongoc/1.30.2/init-cleanup.html) for expected use of `mongoc_init()` and `mongoc_cleanup()`.
+* `mongoc_client_get_database_names` is removed. Use `mongoc_client_get_database_names_with_opts` instead.
+* `mongoc_client_find_databases` is removed. Use `mongoc_client_find_databases_with_opts` instead.
+* `mongoc_client_get_max_message_size` is removed.
+* `mongoc_client_get_max_bson_size` is removed.
+* Deprecated `mongoc_apm_command_*_get_server_connection_id` functions are removed. Use `mongoc_apm_command_*_get_server_connection_id_int64` instead.
+* Deprecated index management API is removed:
+  * `mongoc_collection_create_index_with_opts`, `mongoc_collection_create_index`, and `mongoc_collection_ensure_index` are removed. Use `mongoc_collection_create_indexes_with_opts` instead.
+  * `mongoc_index_opt_t`, `mongoc_index_opt_geo_t` `mongoc_index_opt_wt_t` are removed. Pass options using `bson_t` to `mongoc_collection_create_indexes_with_opts` instead.
+  * `mongoc_collection_find_indexes` is removed. Use `mongoc_collection_find_indexes_with_opts` instead.
+  * See [MongoDB documentation](https://www.mongodb.com/docs/languages/c/c-driver/current/indexes/) for working with indexes.
+* Deprecated cursor API is removed:
+  * `mongoc_cursor_is_alive` is removed. Use the equivalent `mongoc_cursor_more` instead.
+  * `mongoc_cursor_set_hint` is removed. Use the equivalent `mongoc_cursor_set_server_id` instead.
+  * `mongoc_cursor_get_hint` is removed. Use the equivalent `mongoc_cursor_get_server_id` instead.
+  * `mongoc_cursor_new_from_command_reply` is removed. Use `mongoc_cursor_new_from_command_reply_with_opts` instead.
+* Deprecated CRUD API is removed:
+  * `mongoc_collection_save` is removed. Use `mongoc_collection_insert_one` or `mongoc_collection_replace_one` instead.
+  * `mongoc_collection_delete` is removed. Use `mongoc_collection_delete_one` or `mongoc_collection_delete_many` instead.
+  * `mongoc_delete_flags_t` and `mongoc_reply_flags_t` are removed.
+  * `mongoc_collection_find` is removed. Use `mongoc_collection_find_with_opts` instead.
+  * `mongoc_collection_insert_bulk` is removed. Use `mongoc_collection_insert_many` instead.
+  * `mongoc_collection_create_bulk_operation` is removed. Use `mongoc_collection_create_bulk_operation_with_opts` instead.
+  * `mongoc_collection_get_last_error` is removed. To get results from write operations, instead use:
+      * `mongoc_collection_update_one`
+      * `mongoc_collection_update_many`
+      * `mongoc_collection_replace_one`
+      * `mongoc_collection_delete_one`
+      * `mongoc_collection_delete_many`
+      * `mongoc_collection_insert_one`
+      * `mongoc_collection_insert_many`
+      * `mongoc_bulkwrite_t`
+      * `mongoc_bulk_operation_t`
+  * `mongoc_bulk_operation_delete` is removed. Use `mongoc_bulk_operation_remove()` instead.
+  * `mongoc_bulk_operation_delete_one` is removed. Use `mongoc_bulk_operation_remove_one` instead.
+  * `mongoc_bulk_operation_get_hint` is removed. Use `mongoc_bulk_operation_get_server_id` instead.
+  * `mongoc_bulk_operation_set_hint` is removed. Use `mongoc_bulk_operation_set_server_id` instead.
+  * `mongoc_collection_count` and `mongoc_collection_count_with_opts` are removed. Use `mongoc_collection_count_documents` or `mongoc_collection_estimated_document_count` instead.
+* `mongoc_collection_stats` is removed. Use the [$collStats aggregation pipeline stage](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) with `mongoc_collection_aggregate` instead.
+* `mongoc_collection_validate` is removed. Run the [validate](https://www.mongodb.com/docs/manual/reference/command/validate/) command directly with `mongoc_client_read_command_with_opts` instead.
+* Deprecated API for `mongoc_database_t` is removed:
+  * `mongoc_database_find_collections` is removed. Use `mongoc_database_find_collections_with_opts` instead.
+  * `mongoc_database_get_collection_names` is removed. Use `mongoc_database_get_collection_names_with_opts` instead.
+* Deprecated GridFS API has been removed:
+  * `mongoc_gridfs_find` is removed. Use `mongoc_gridfs_find_with_opts` instead.
+  * `mongoc_gridfs_find_one` is removed. Use `mongoc_gridfs_find_one_with_opts` instead.
+* Deprecated TLS stream API is removed:
+  * `mongoc_stream_tls_do_handshake` is removed. Use `mongoc_stream_tls_handshake` instead.
+  * `mongoc_stream_tls_check_cert` is removed. Use `mongoc_stream_tls_handshake` instead.
+  * `mongoc_stream_tls_new` is removed. Use `mongoc_stream_tls_new_with_hostname` instead.
+* Deprecated URI API has been removed:
+  * `mongoc_uri_get_service` is removed. Use `mongoc_uri_get_srv_hostname` instead.
+  * `mongoc_uri_get_read_prefs` is removed. Use `mongoc_uri_get_read_prefs_t` instead.
+  * `mongoc_uri_get_ssl` is removed. Use `mongoc_uri_get_tls` instead.
+* Deprecated write concern API is removed:
+  * `mongoc_write_concern_get_fsync` is removed. Use `mongoc_write_concern_get_journal` instead.
+  * `mongoc_write_concern_set_fsync` is removed. Use `mongoc_write_concern_set_journal` instead.
+* The `libmongoc-ssl-1.0` pkg-config file has been removed.
+
+### Forwarding headers (`#include <bson.h>` and `#include <mongoc.h>`)
+
+The compatibility "forwarding" headers have been removed (previously added in 1.13.0). This means it is no longer valid to include the literal header names `mongoc.h` or `bson.h` directly:
+
+```c
+#include <bson.h> // No longer provided!
+#include <mongoc.h> // No longer provided!
+```
+
+Instead, the names must be prefixed with the parent directory: `mongoc/mongoc.h` and `bson/bson.h`:
+
+```c
+#include <bson/bson.h>
+#include <mongoc/mongoc.h>
+```
+
+### `mongoc_client_kill_cursor`
+
+`mongoc_client_kill_cursor` is removed. It did not accept a server identifier. It was only reliable when connected to a single server.
+
+Sending [killCursors](https://www.mongodb.com/docs/manual/reference/command/killCursors/) is not typically needed. `mongoc_cursor_t` manages the cursor lifetime. If needed, use a generic command helper to manually send a `killCursors` command:
+
+```c
+bson_t *cmd = BCON_NEW ("killCursors", "coll", "cursors", "[", BCON_INT64 (cursor_id), "]");
+bool ok = mongoc_client_command_simple_with_server_id (client, "db", cmd, NULL, server_id, NULL, &error);
+if (!ok) {
+  printf ("Failed to send 'killCursors': %s\n", error.message);
+}
+bson_destroy (cmd);
+```
+
+### `mongoc_client_get_server_status`
+
+`mongoc_client_get_server_status` is removed. Use a command helper to run the "serverStatus" command instead:
+
+```c
+bson_t *cmd = BCON_NEW("serverStatus", BCON_INT32(1));
+if (!mongoc_client_command_simple(client, "db", cmd, NULL, &reply, &error)) {
+    printf("Failed to send 'serverStatus': %s\n", error.message);
+} else {
+  // TODO: use `reply`
+}
+bson_destroy(&reply);
+bson_destroy(cmd);
+```
 
-  Programs that link to BSON libraries directly should also use the new target
-  names `bson::static`, `bson::shared`, or `bson::bson`.
+## Contributors
 
 Thanks to everyone who contributed to the development of this release.
 
   * Kevin Albertson
   * Ezra Chung
   * Colby Pike
+  * Micah Scott
+  * Jeroen Ooms
 
 
 libmongoc 1.30.2
@@ -1535,6 +1707,7 @@ Features:
     and all bson headers are under bson/. The preferred way of including the
     headers are mongoc/mongoc.h and bson/bson.h respectively.
     Forwarding headers in the root are provided for backwards compatibility.
+    (**Update**: These headers were removed in the 2.0 release)
   * The default CMake build type had been unspecified, now it is RelWithDebInfo.
   * Support LibreSSL 2.7+.
 
diff -pruN 1.30.4-1/VERSION_CURRENT 2.0.2-1/VERSION_CURRENT
--- 1.30.4-1/VERSION_CURRENT	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/VERSION_CURRENT	2025-06-19 15:42:22.000000000 +0000
@@ -1 +1 @@
-1.30.4
+2.0.2
diff -pruN 1.30.4-1/build/calc_release_version.py 2.0.2-1/build/calc_release_version.py
--- 1.30.4-1/build/calc_release_version.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/calc_release_version.py	1970-01-01 00:00:00.000000000 +0000
@@ -1,403 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-#
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-A script that calculates the release version number (based on the current Git
-branch and/or recent tags in history) to assign to a tarball generated from the
-current Git commit.
-
-This script needs to remain compatible with its target platforms, which currently
-includes RHEL 6, which uses Python 2.6!
-"""
-
-# XXX NOTE XXX NOTE XXX NOTE XXX
-# After modifying this script it is advisable to execute the self-tests in this directory:
-# - calc_release_version_selftest.sh
-# - calc_release_version_selftest.py
-# XXX NOTE XXX NOTE XXX NOTE XXX
-
-# pyright: reportTypeCommentUsage=false
-
-import datetime
-import errno
-import re
-import subprocess
-import optparse  # No 'argparse' on Python 2.6
-import sys
-
-
-class Version:
-    def __init__(self, s):
-        pat = r'(\d+)\.(\d+)\.(\d+)(\-\S+)?'
-        match = re.match(pat, s)
-        assert match, "Unrecognized version string %s" % s
-        self.major, self.minor, self.micro = (
-            map(int, (match.group(1), match.group(2), match.group(3))))
-
-        if match.group(4):
-            self.prerelease = match.group(4)[1:]
-        else:
-            self.prerelease = ''
-
-    def __lt__(self, other):
-        if self.major != other.major:
-            return self.major < other.major
-        if self.minor != other.minor:
-            return self.minor < other.minor
-        if self.micro != other.micro:
-            return self.micro < other.micro
-        if self.prerelease != other.prerelease:
-            if self.prerelease != '' and other.prerelease == '':
-                # Consider a prerelease less than non-prerelease.
-                return True
-            # For simplicity, compare prerelease versions lexicographically.
-            return self.prerelease < other.prerelease
-
-        # Versions are equal.
-        return False
-
-    def __eq__(self, other):
-        self_tuple = self.major, self.minor, self.micro, self.prerelease
-        other_tuple = other.major, other.minor, other.micro, other.prerelease
-        return self_tuple == other_tuple
-
-
-def parse_version(ver):
-    return Version(ver)
-
-
-parser = optparse.OptionParser(description=__doc__)
-parser.add_option("--debug", "-d", action="store_true", help="Enable debug output")
-parser.add_option("--previous", "-p", action="store_true", help="Calculate the previous version instead of the current")
-parser.add_option("--next-minor", action="store_true", help="Calculate the next minor version instead of the current")
-args, pos = parser.parse_args()
-assert not pos, "No positional arguments are expected"
-
-
-_DEBUG = args.debug  # type: bool
-
-
-def debug(msg):  # type: (str) -> None
-    if _DEBUG:
-        sys.stderr.write(msg)
-        sys.stderr.write("\n")
-        sys.stderr.flush()
-
-
-debug("Debugging output enabled.")
-
-# This option indicates we are to determine the previous release version
-PREVIOUS = args.previous  # type: bool
-# This options indicates to output the next minor release version
-NEXT_MINOR = args.next_minor  # type: bool
-
-# fmt: off
-
-PREVIOUS_TAG_RE = re.compile('(?P<ver>(?P<vermaj>[0-9]+)\\.(?P<vermin>[0-9]+)'
-                             '\\.(?P<verpatch>[0-9]+)(?:-(?P<verpre>.*))?)')
-RELEASE_TAG_RE = re.compile('(?P<ver>(?P<vermaj>[0-9]+)\\.(?P<vermin>[0-9]+)'
-                            '\\.(?P<verpatch>[0-9]+)(?:-(?P<verpre>.*))?)')
-RELEASE_BRANCH_RE = re.compile('(?:(?:refs/remotes/)?origin/)?(?P<brname>r'
-                               '(?P<vermaj>[0-9]+)\\.(?P<vermin>[0-9]+))')
-
-
-def check_output(args):  # type: (list[str]) -> str
-    """
-    Delegates to subprocess.check_output() if it is available, otherwise
-    provides a reasonable facsimile.
-    """
-    debug('Run command: {0}'.format(args))
-    try:
-        proc = subprocess.Popen(args, stdout=subprocess.PIPE)
-    except OSError as e:
-        suppl = ''
-        if e.errno == errno.ENOENT:
-            suppl = 'Does the executable “{0}” not exist?'.format(args[0])
-        raise RuntimeError("Failed to execute subprocess {0}: {1} [{2}]".format(args, e, suppl))
-    out = proc.communicate()[0]
-    ret = proc.poll()
-    if ret:
-        raise subprocess.CalledProcessError(ret, args[0])
-
-    # git isn't guaranteed to always return UTF-8, but for our purposes
-    # this should be fine as tags and hashes should be ASCII only.
-    out = out.decode('utf-8')
-
-    return out
-
-
-def check_head_tag():  # type: () -> str | None
-    """
-    Checks the current HEAD to see if it has been tagged with a tag that matches
-    the pattern for a release tag.  Returns release version calculated from the
-    tag, or None if there is no matching tag associated with HEAD.
-    """
-
-    found_tag = False
-    version_str = '0.0.0'
-    version_parsed = parse_version(version_str)
-
-    # have git tell us if any tags that look like release tags point at HEAD;
-    # based on our policy, a commit should never have more than one release tag
-    tags = check_output(['git', 'tag', '--points-at', 'HEAD', '--list', '1.*']).split()
-    tag = ''
-    if len(tags) == 1:
-        tag = tags[0]
-    elif len(tags) > 1:
-        raise Exception('Expected 1 or 0 tags on HEAD, got: {}'.format(tags))
-
-    release_tag_match = RELEASE_TAG_RE.match(tag)
-    if release_tag_match:
-        new_version_str = release_tag_match.group('ver')
-        new_version_parsed = parse_version(new_version_str)
-        if new_version_parsed > version_parsed: # type: ignore
-            debug('HEAD release tag: ' + new_version_str)
-            version_str = new_version_str
-            version_parsed = new_version_parsed
-            found_tag = True
-
-    if found_tag:
-        debug('Calculated version: ' + version_str)
-        return version_str
-
-    return None
-
-def get_next_minor(prerelease_marker):  # type: (str) -> str
-    """
-    get_next_minor does the following:
-        - Inspect the branches that fit the convention for a release branch.
-        - Choose the latest and increment the minor version.
-        - Append .0 to form the new version (e.g., r1.21 becomes 1.22.0)
-        - Append a pre-release marker. (e.g. 1.22.0 becomes 1.22.0-20220201+gitf6e6a7025d)
-    """
-
-    version_str = '0.0.0'
-    version_parsed = parse_version(version_str)
-
-    version_new = {}
-    # Use refs (not branches) to get local branches plus remote branches
-    refs = check_output(['git', 'show-ref']).splitlines()
-    for ref in refs:
-        release_branch_match = RELEASE_BRANCH_RE.match(ref.split()[1])
-        if release_branch_match:
-            # Construct a candidate version from this branch name
-            version_new['major'] = int(release_branch_match.group('vermaj'))
-            version_new['minor'] = int(release_branch_match.group('vermin')) + 1
-            version_new['patch'] = 0
-            version_new['prerelease'] = prerelease_marker
-            new_version_str = str(version_new['major']) + '.' + \
-                              str(version_new['minor']) + '.' + \
-                              str(version_new['patch']) + '-' + \
-                              version_new['prerelease']
-            new_version_parsed = parse_version(new_version_str)
-            if new_version_parsed > version_parsed: # type: ignore
-                version_str = new_version_str
-                version_parsed = new_version_parsed
-                debug('Found new best version "' + version_str \
-                            + '" based on branch "' \
-                            + release_branch_match.group('brname') + '"')
-    return version_str
-
-def get_branch_tags(active_branch_name):  # type: (str) -> list[str]
-    """
-    Returns a list of tags corresponding to the current branch, which must not
-    be master.  If the specified branch is a release branch then return all tags
-    based on the major/minor X.Y release version.  If the specified branch is
-    neither master nor a release branch, then walk backwards in history until
-    the first tag matching the glob '1.*' and return that tag.
-    """
-
-    if active_branch_name == 'master':
-        raise Exception('this method is not meant to be called while on "master"')
-
-    release_branch_match = RELEASE_BRANCH_RE.match(active_branch_name)
-    if release_branch_match:
-        # This is a release branch, so look for tags only on this branch
-        tag_glob = release_branch_match.group('vermaj') + '.' \
-                + release_branch_match.group('vermin') + '.*'
-        return check_output(['git', 'tag', '--list', tag_glob]).splitlines()
-
-    # Not a release branch, so look for the most recent tag in history
-    commits = check_output(['git', 'log', '--pretty=format:%H', '--no-merges'])
-    tags_by_obj = get_object_tags()
-    for commit in commits.splitlines():
-        got = tags_by_obj.get(commit)
-        if got:
-            return got
-    # No tags
-    return []
-
-
-def iter_tag_lines():
-    """
-    Generate a list of pairs of strings, where the first is a commit hash, and
-    the second is a tag that is associated with that commit. Duplicate commits
-    are possible.
-    """
-    output = check_output(['git', 'tag', '--list', '1.*', '--format=%(*objectname)|%(tag)'])
-    lines = output.splitlines()
-    for l in lines:
-        obj, tag = l.split('|', 1)
-        if tag:
-            yield obj, tag
-
-
-def get_object_tags():  # type: () -> dict[str, list[str]]
-    """
-    Obtain a mapping between commit hashes and a list of tags that point to
-    that commit. Untagged commits will not be included in the resulting map.
-    """
-    ret = {}  # type: dict[str, list[str]]
-    for obj, tag in iter_tag_lines():
-        ret.setdefault(obj, []).append(tag)
-    return ret
-
-
-def process_and_sort_tags(tags):  # type: (list[str]) -> list[str]
-    """
-    Given a string (as returned from get_branch_tags), return a sorted list of
-    zero or more tags (sorted based on the Version comparison) which meet
-    the following criteria:
-        - a final release tag (i.e., 1.x.y without any pre-release suffix)
-        - a pre-release tag which is not superseded by a release tag (i.e.,
-          1.x.y-preX iff 1.x.y does not already exist)
-    """
-
-    processed_and_sorted_tags = []  # type: list[str]
-    if not tags or len(tags) == 0:
-        return processed_and_sorted_tags
-
-    # find all the final release tags
-    for tag in tags:
-        release_tag_match = RELEASE_TAG_RE.match(tag)
-        if release_tag_match and not release_tag_match.group('verpre'):
-            processed_and_sorted_tags.append(tag)
-    # collect together final release tags and pre-release tags for
-    # versions that have not yet had a final release
-    for tag in tags:
-        tag_parts = tag.split('-')
-        if len(tag_parts) >= 2 and tag_parts[0] not in processed_and_sorted_tags:
-            processed_and_sorted_tags.append(tag)
-    processed_and_sorted_tags.sort(key=Version)  # type: ignore
-
-    return processed_and_sorted_tags
-
-def main():
-    """
-    The algorithm is roughly:
-
-        - Is the --next-minor flag passed? If "yes", then return the next minor
-           release with a pre-release marker.
-        - Is the current HEAD associated with a tag that looks like a release
-           version?
-        - If "yes" then use that as the version
-        - If "no" then is the current branch master?
-        - If "yes" the current branch is master, then return the next minor
-           release with a pre-release marker.
-        - If "no" the current branch is not master, then determine the most
-           recent tag in history; strip any pre-release marker, increment the
-           patch version, and append a new pre-release marker
-    """
-
-    version_str = '0.0.0'
-    version_parsed = parse_version(version_str)
-    head_commit_short = check_output(['git', 'rev-parse', '--revs-only',
-                                      '--short=10', 'HEAD^{commit}']).strip()
-    prerelease_marker = datetime.date.today().strftime('%Y%m%d') \
-            + '+git' + head_commit_short
-
-    if NEXT_MINOR:
-        debug('Calculating next minor release')
-        return get_next_minor(prerelease_marker)
-
-    head_tag_ver = check_head_tag()
-    if head_tag_ver:
-        return head_tag_ver
-
-    active_branch_name = check_output(['git', 'rev-parse',
-                                       '--abbrev-ref', 'HEAD']).strip()
-    debug('Calculating release version for branch: ' + active_branch_name)
-    if active_branch_name == 'master':
-        return get_next_minor(prerelease_marker)
-
-    branch_tags = get_branch_tags(active_branch_name)
-    tags = process_and_sort_tags(branch_tags)
-
-    tag = tags[-1] if len(tags) > 0 else ''
-    # at this point the RE match is redundant, but convenient for accessing
-    # the components of the version string
-    release_tag_match = RELEASE_TAG_RE.match(tag)
-    if release_tag_match:
-        version_new = {}
-        version_new['major'] = int(release_tag_match.group('vermaj'))
-        version_new['minor'] = int(release_tag_match.group('vermin'))
-        version_new['patch'] = int(release_tag_match.group('verpatch')) + 1
-        version_new['prerelease'] = prerelease_marker
-        new_version_str = str(version_new['major']) + '.' + \
-                          str(version_new['minor']) + '.' + \
-                          str(version_new['patch']) + '-' + \
-                          version_new['prerelease']
-        new_version_parsed = parse_version(new_version_str)
-        if new_version_parsed > version_parsed: # type: ignore
-            version_str = new_version_str
-            version_parsed = new_version_parsed
-            debug('Found new best version "' + version_str \
-                        + '" from tag "' + release_tag_match.group('ver') + '"')
-
-    return version_str
-
-def previous(rel_ver):  # type: (str) -> str
-    """
-    Given a release version, find the previous version based on the latest Git
-    tag that is strictly a lower version than the given release version.
-    """
-    debug('Calculating previous release version (option -p was specified).')
-    version_str = '0.0.0'
-    version_parsed = parse_version(version_str)
-    rel_ver_str = rel_ver
-    rel_ver_parsed = parse_version(rel_ver_str)
-    tags = check_output(['git', 'tag', '--list', '1.*']).splitlines()
-    processed_and_sorted_tags = process_and_sort_tags(tags)
-    for tag in processed_and_sorted_tags:
-        previous_tag_match = PREVIOUS_TAG_RE.match(tag)
-        if previous_tag_match:
-            version_new = {}
-            version_new['major'] = int(previous_tag_match.group('vermaj'))
-            version_new['minor'] = int(previous_tag_match.group('vermin'))
-            version_new['patch'] = int(previous_tag_match.group('verpatch'))
-            version_new['prerelease'] = previous_tag_match.group('verpre')
-            new_version_str = str(version_new['major']) + '.' + \
-                              str(version_new['minor']) + '.' + \
-                              str(version_new['patch'])
-            if version_new['prerelease'] is not None:
-                new_version_str += '-' + version_new['prerelease']
-            new_version_parsed = parse_version(new_version_str)
-            if new_version_parsed < rel_ver_parsed and new_version_parsed > version_parsed: # type: ignore
-                version_str = new_version_str
-                version_parsed = new_version_parsed
-                debug('Found new best version "' + version_str \
-                            + '" from tag "' + tag + '"')
-
-    return version_str
-
-if __name__ == "__main__":
-    RELEASE_VER = previous(main()) if PREVIOUS else main()
-
-    debug('Final calculated release version:')
-    print(RELEASE_VER)
diff -pruN 1.30.4-1/build/cmake/.gitignore 2.0.2-1/build/cmake/.gitignore
--- 1.30.4-1/build/cmake/.gitignore	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/.gitignore	1970-01-01 00:00:00.000000000 +0000
@@ -1,4 +0,0 @@
-libmongoc-1.0-config.cmake
-libmongoc-1.0-config-version.cmake
-libmongoc-static-1.0-config.cmake
-libmongoc-static-1.0-config-version.cmake
diff -pruN 1.30.4-1/build/cmake/FindLibreSSL.cmake 2.0.2-1/build/cmake/FindLibreSSL.cmake
--- 1.30.4-1/build/cmake/FindLibreSSL.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/FindLibreSSL.cmake	1970-01-01 00:00:00.000000000 +0000
@@ -1,236 +0,0 @@
-#[=======================================================================[
-
-Copyright (c) 2019 John Norrbin <jlnorrbin@johnex.se>
-
-Permission to use, copy, modify, and distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-FindLibreSSL
-------------
-
-Find the LibreSSL encryption library.
-
-Optional Components
-^^^^^^^^^^^^^^^^^^^
-
-This module supports two optional components: SSL and TLS.  Both
-components have associated imported targets, as described below.
-
-Imported Targets
-^^^^^^^^^^^^^^^^
-
-This module defines the following imported targets:
-
-LibreSSL::Crypto
-    The LibreSSL crypto library, if found.
-
-LibreSSL::SSL
-    The LibreSSL ssl library, if found. Requires and includes LibreSSL::Crypto automatically.
-
-LibreSSL::TLS
-    The LibreSSL tls library, if found. Requires and includes LibreSSL::SSL and LibreSSL::Crypto automatically.
-
-Result Variables
-^^^^^^^^^^^^^^^^
-
-This module will set the following variables in your project:
-
-LIBRESSL_FOUND
-    System has the LibreSSL library. If no components are requested it only requires the crypto library.
-LIBRESSL_INCLUDE_DIR
-    The LibreSSL include directory.
-LIBRESSL_CRYPTO_LIBRARY
-    The LibreSSL crypto library.
-LIBRESSL_SSL_LIBRARY
-    The LibreSSL SSL library.
-LIBRESSL_TLS_LIBRARY
-    The LibreSSL TLS library.
-LIBRESSL_LIBRARIES
-    All LibreSSL libraries.
-LIBRESSL_VERSION
-    This is set to $major.$minor.$revision (e.g. 2.6.8).
-
-Hints
-^^^^^
-
-Set LIBRESSL_ROOT_DIR to the root directory of an LibreSSL installation.
-
-XXX: Note! This file differs somewhat from the upstream FindLibreSSL and has
-been modified with fixes used by mongo-c-driver. Such differences are noted
-where they appear.
-
-]=======================================================================]
-
-INCLUDE(FindPackageHandleStandardArgs)
-
-# Set Hints
-set(_LIBRESSL_ROOT_HINTS
-    ${LIBRESSL_ROOT_DIR}
-    ENV LIBRESSL_ROOT_DIR
-)
-
-# Set Paths
-if (WIN32)
-    file(TO_CMAKE_PATH "$ENV{PROGRAMFILES}" _programfiles)
-    set(_LIBRESSL_ROOT_PATHS
-        "${_programfiles}/LibreSSL"
-    )
-    unset(_programfiles)
-else()
-    set(_LIBRESSL_ROOT_PATHS
-        "/usr/local/"
-    )
-endif()
-
-# Combine
-set(_LIBRESSL_ROOT_HINTS_AND_PATHS
-    HINTS ${_LIBRESSL_ROOT_HINTS}
-    PATHS ${_LIBRESSL_ROOT_PATHS}
-    # XXX: Changed from upstream FindLibreSSL:
-    #   Some platforms (e.g. Arch) install LibreSSL in a qualified path so as not to
-    #   collide with OpenSSL. Add path suffixies that match such distributions
-    PATH_SUFFIXES
-        include
-        lib
-        libressl
-        libressl/include
-        libressl/lib
-)
-
-# Find Include Path
-find_path(LIBRESSL_INCLUDE_DIR
-    NAMES
-        tls.h
-    ${_LIBRESSL_ROOT_HINTS_AND_PATHS}
-)
-
-# Find Crypto Library
-find_library(LIBRESSL_CRYPTO_LIBRARY
-    NAMES
-        libcrypto
-        crypto
-        NAMES_PER_DIR
-    ${_LIBRESSL_ROOT_HINTS_AND_PATHS}
-)
-
-# Find SSL Library
-find_library(LIBRESSL_SSL_LIBRARY
-    NAMES
-        libssl
-        ssl
-        NAMES_PER_DIR
-    ${_LIBRESSL_ROOT_HINTS_AND_PATHS}
-)
-
-# Find TLS Library
-find_library(LIBRESSL_TLS_LIBRARY
-    NAMES
-        libtls
-        tls
-        NAMES_PER_DIR
-    ${_LIBRESSL_ROOT_HINTS_AND_PATHS}
-)
-
-# Set Libraries
-set(LIBRESSL_LIBRARIES ${LIBRESSL_CRYPTO_LIBRARY} ${LIBRESSL_SSL_LIBRARY} ${LIBRESSL_TLS_LIBRARY})
-
-# Mark Variables As Advanced
-mark_as_advanced(LIBRESSL_INCLUDE_DIR LIBRESSL_LIBRARIES LIBRESSL_CRYPTO_LIBRARY LIBRESSL_SSL_LIBRARY LIBRESSL_TLS_LIBRARY)
-
-# Find Version File
-if(LIBRESSL_INCLUDE_DIR AND EXISTS "${LIBRESSL_INCLUDE_DIR}/openssl/opensslv.h")
-
-    # Get Version From File
-    file(STRINGS "${LIBRESSL_INCLUDE_DIR}/openssl/opensslv.h" OPENSSLV.H REGEX "#define LIBRESSL_VERSION_TEXT[ \t]+\".*\"")
-    # XXX: The above line differs from upstream FindLibreSSL, which does not contain the "\t" regex element.
-    #      Newer LibreSSL uses a tab character at this point in the file, which otherwise causes the above
-    #      regex to fail. Newer LibreSSL versions ship full config-file packages, with will remove the
-    #      need to use this file.
-
-    # Match Version String
-    string(REGEX REPLACE ".*\".*([0-9]+)\\.([0-9]+)\\.([0-9]+)\"" "\\1;\\2;\\3" LIBRESSL_VERSION_LIST "${OPENSSLV.H}")
-
-    # Split Parts
-    list(GET LIBRESSL_VERSION_LIST 0 LIBRESSL_VERSION_MAJOR)
-    list(GET LIBRESSL_VERSION_LIST 1 LIBRESSL_VERSION_MINOR)
-    list(GET LIBRESSL_VERSION_LIST 2 LIBRESSL_VERSION_REVISION)
-
-    # Set Version String
-    set(LIBRESSL_VERSION "${LIBRESSL_VERSION_MAJOR}.${LIBRESSL_VERSION_MINOR}.${LIBRESSL_VERSION_REVISION}")
-
-endif()
-
-# Set Find Package Arguments
-find_package_handle_standard_args(LibreSSL
-    REQUIRED_VARS
-        LIBRESSL_CRYPTO_LIBRARY
-        LIBRESSL_INCLUDE_DIR
-    VERSION_VAR
-        LIBRESSL_VERSION
-    HANDLE_COMPONENTS
-        FAIL_MESSAGE
-        "Could NOT find LibreSSL, try setting the path to LibreSSL using the LIBRESSL_ROOT_DIR environment variable"
-)
-
-# LibreSSL Found
-if(LIBRESSL_FOUND)
-
-    # Set LibreSSL::Crypto
-    if(NOT TARGET LibreSSL::Crypto AND EXISTS "${LIBRESSL_CRYPTO_LIBRARY}")
-
-        # Add Library
-        add_library(LibreSSL::Crypto UNKNOWN IMPORTED)
-
-        # Set Properties
-        set_target_properties(
-            LibreSSL::Crypto
-            PROPERTIES
-                INTERFACE_INCLUDE_DIRECTORIES "${LIBRESSL_INCLUDE_DIR}"
-                IMPORTED_LINK_INTERFACE_LANGUAGES "C"
-                IMPORTED_LOCATION "${LIBRESSL_CRYPTO_LIBRARY}"
-        )
-
-    endif() # LibreSSL::Crypto
-
-    # Set LibreSSL::SSL
-    if(NOT TARGET LibreSSL::SSL AND EXISTS "${LIBRESSL_SSL_LIBRARY}")
-
-        # Add Library
-        add_library(LibreSSL::SSL UNKNOWN IMPORTED)
-
-        # Set Properties
-        set_target_properties(
-            LibreSSL::SSL
-            PROPERTIES
-                INTERFACE_INCLUDE_DIRECTORIES "${LIBRESSL_INCLUDE_DIR}"
-                IMPORTED_LINK_INTERFACE_LANGUAGES "C"
-                IMPORTED_LOCATION "${LIBRESSL_SSL_LIBRARY}"
-                INTERFACE_LINK_LIBRARIES LibreSSL::Crypto
-        )
-
-    endif() # LibreSSL::SSL
-
-    # Set LibreSSL::TLS
-    if(NOT TARGET LibreSSL::TLS AND EXISTS "${LIBRESSL_TLS_LIBRARY}")
-        add_library(LibreSSL::TLS UNKNOWN IMPORTED)
-        set_target_properties(
-            LibreSSL::TLS
-            PROPERTIES
-                INTERFACE_INCLUDE_DIRECTORIES "${LIBRESSL_INCLUDE_DIR}"
-                IMPORTED_LINK_INTERFACE_LANGUAGES "C"
-                IMPORTED_LOCATION "${LIBRESSL_TLS_LIBRARY}"
-                INTERFACE_LINK_LIBRARIES LibreSSL::SSL
-        )
-
-    endif() # LibreSSL::TLS
-
-endif(LIBRESSL_FOUND)
diff -pruN 1.30.4-1/build/cmake/GeneratePkgConfig.cmake 2.0.2-1/build/cmake/GeneratePkgConfig.cmake
--- 1.30.4-1/build/cmake/GeneratePkgConfig.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/GeneratePkgConfig.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -278,8 +278,11 @@ function(_generate_pkg_config_content ou
     set(libs)
     # Link options:
     set(gx_libs
-        "-L\${libdir}"
-        "-l$<TARGET_PROPERTY:OUTPUT_NAME>"
+        $<IF:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,STATIC_LIBRARY>,
+            # If linking static, emit the full path to the static library file
+            \${libdir}/$<TARGET_FILE_NAME:${target}>,
+            # Otherwise, link to the dynamic library namelink
+            -L\${libdir} -l$<TARGET_PROPERTY:OUTPUT_NAME>>
         $<GENEX_EVAL:$<TARGET_PROPERTY:pkg_config_LIBS>>
         $<REMOVE_DUPLICATES:$<TARGET_PROPERTY:INTERFACE_LINK_OPTIONS>>
         )
diff -pruN 1.30.4-1/build/cmake/LLDLinker.cmake 2.0.2-1/build/cmake/LLDLinker.cmake
--- 1.30.4-1/build/cmake/LLDLinker.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/LLDLinker.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -56,5 +56,7 @@ endif ()
 
 if (MONGO_USE_LLD)
     message (STATUS "Linking using LLVM lld. Disable by setting MONGO_USE_LLD to OFF")
-    add_link_options (-fuse-ld=lld)
+    # We only tested with C, so only use LLD on C (some platforms don't support lld with g++)
+    # XXX: This should use $<LINK_LANGUAGE:C> when we can require CMake 3.18+
+    add_link_options ($<$<COMPILE_LANGUAGE:C>:-fuse-ld=lld>)
 endif ()
diff -pruN 1.30.4-1/build/cmake/LegacyPackage.cmake 2.0.2-1/build/cmake/LegacyPackage.cmake
--- 1.30.4-1/build/cmake/LegacyPackage.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/LegacyPackage.cmake	1970-01-01 00:00:00.000000000 +0000
@@ -1,31 +0,0 @@
-include (CMakePackageConfigHelpers)
-
-# These aren't pkg-config files, they're CMake package configuration files.
-function (install_package_config_file prefix)
-   foreach (suffix "config.cmake")
-      configure_package_config_file (
-         ${CMAKE_CURRENT_LIST_DIR}/${PROJECT_NAME}-${prefix}-${suffix}.in
-         ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-${prefix}-${suffix}
-         INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${prefix}
-      )
-
-      install (
-         FILES
-            ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-${prefix}-${suffix}
-         DESTINATION
-            ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${prefix}
-      )
-   endforeach ()
-   write_basic_package_version_file(
-      ${PROJECT_NAME}-${prefix}-config-version.cmake
-      VERSION "${PROJECT_VERSION}"
-      COMPATIBILITY SameMajorVersion
-   )
-   install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-${prefix}-config-version.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${prefix})
-endfunction ()
-
-install_package_config_file ("1.0")
-
-if (ENABLE_STATIC)
-   install_package_config_file ("static-1.0")
-endif ()
diff -pruN 1.30.4-1/build/cmake/MongoPlatform.cmake 2.0.2-1/build/cmake/MongoPlatform.cmake
--- 1.30.4-1/build/cmake/MongoPlatform.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/MongoPlatform.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -8,9 +8,9 @@ Use mongo_platform_compile_options and m
 requirements to this library.
 
 The mongo::detail::c_platform library is installed and exported with the
-bson-targets export set as an implementation detail. It is installed with this
+mongo-platform-targets export set as an implementation detail. It is installed with this
 export set so that it is available to both libbson and libmongoc (attempting to
-install this target in both bson-targets and mongoc-targets export sets would
+install this target in both mongo-platform-targets and mongoc-targets export sets would
 lead to duplicate definitions of mongo::detail::c_platform for downstream
 users).
 
@@ -23,9 +23,9 @@ else ()
    # The system libbson exports the `mongo::detail::c_platform` target.
    # Do not define the `mongo::detail::c_platform` target, to prevent an "already defined" error.
 endif ()
-set_property(TARGET _mongo-platform PROPERTY EXPORT_NAME detail::c_platform)
-install(TARGETS _mongo-platform EXPORT bson-targets)
-
+set_property(TARGET _mongo-platform PROPERTY EXPORT_NAME mongo::detail::c_platform)
+# This export set is installed as part of libbson. Search: PLATFORM-EXPORT-TARGET-INSTALL
+install(TARGETS _mongo-platform EXPORT mongo-platform-targets)
 
 #[[
 Define additional platform-support compile options
diff -pruN 1.30.4-1/build/cmake/TestProject.cmake 2.0.2-1/build/cmake/TestProject.cmake
--- 1.30.4-1/build/cmake/TestProject.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/TestProject.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -160,15 +160,20 @@ function(__do_test_project)
     set(tmp_install_prefix "${TEST_PROJECT_PARENT_BINARY_DIR}/TestProject-install/${test_name_hash}")
     file(REMOVE_RECURSE "${tmp_install_prefix}")
     list(APPEND TEST_PROJECT_SETTINGS/CMAKE_INSTALL_PREFIX "${tmp_install_prefix}")
+    list(APPEND TEST_PROJECT_SETTINGS/CMAKE_PREFIX_PATH "${tmp_install_prefix}")
 
     if(TEST_PROJECT_INSTALL_PARENT)
         cmake_path(ABSOLUTE_PATH tmp_install_prefix NORMALIZE)
         message(STATUS "Installing parent project into [${tmp_install_prefix}]")
         execute_process(
-            COMMAND ${CMAKE_COMMAND}
-                --install "${TEST_PROJECT_PARENT_BINARY_DIR}"
-                --prefix "${tmp_install_prefix}"
-                --config "${TEST_PROJECT_CONFIG}"
+            COMMAND
+                # Suppress DESTDIR
+                ${CMAKE_COMMAND} -E env --unset=DESTDIR
+                # Do the install:
+                ${CMAKE_COMMAND}
+                    --install "${TEST_PROJECT_PARENT_BINARY_DIR}"
+                    --prefix "${tmp_install_prefix}"
+                    --config "${TEST_PROJECT_CONFIG}"
             COMMAND_ERROR_IS_FATAL LAST
         )
     endif()
diff -pruN 1.30.4-1/build/cmake/libbson-1.0-config.cmake.in 2.0.2-1/build/cmake/libbson-1.0-config.cmake.in
--- 1.30.4-1/build/cmake/libbson-1.0-config.cmake.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/libbson-1.0-config.cmake.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-if(NOT libbson-1.0_FIND_QUIETLY)
-    message(WARNING "This CMake package is deprecated. Prefer instead to use the \"bson-1.0\" package and link to mongo::bson_shared.")
-endif()
-
-set (BSON_MAJOR_VERSION @libbson_VERSION_MAJOR@)
-set (BSON_MINOR_VERSION @libbson_VERSION_MINOR@)
-set (BSON_MICRO_VERSION @libbson_VERSION_PATCH@)
-set (BSON_VERSION @libbson_VERSION@)
-set (BSON_VERSION_FULL @libbson_VERSION_FULL@)
-
-include(CMakeFindDependencyMacro)
-find_dependency(bson-1.0)
-
-set (BSON_LIBRARY mongo::bson_shared)
-set (BSON_LIBRARIES mongo::bson_shared)
diff -pruN 1.30.4-1/build/cmake/libbson-static-1.0-config.cmake.in 2.0.2-1/build/cmake/libbson-static-1.0-config.cmake.in
--- 1.30.4-1/build/cmake/libbson-static-1.0-config.cmake.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/libbson-static-1.0-config.cmake.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-if(NOT libbson-static-1.0_FIND_QUIETLY)
-    message(WARNING "This CMake package is deprecated. Prefer instead to use the \"bson-1.0\" package and link to mongo::bson_static.")
-endif()
-
-set (BSON_STATIC_MAJOR_VERSION @libbson_VERSION_MAJOR@)
-set (BSON_STATIC_MINOR_VERSION @libbson_VERSION_MINOR@)
-set (BSON_STATIC_MICRO_VERSION @libbson_VERSION_PATCH@)
-set (BSON_STATIC_VERSION @libbson_VERSION@)
-set (BSON_STATIC_VERSION_FULL @libbson_VERSION_FULL@)
-
-include(CMakeFindDependencyMacro)
-find_dependency(bson-1.0)
-
-set (BSON_STATIC_LIBRARY mongo::bson_static)
-set (BSON_STATIC_LIBRARIES mongo::bson_static)
diff -pruN 1.30.4-1/build/cmake/libmongoc-1.0-config.cmake.in 2.0.2-1/build/cmake/libmongoc-1.0-config.cmake.in
--- 1.30.4-1/build/cmake/libmongoc-1.0-config.cmake.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/libmongoc-1.0-config.cmake.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-if(NOT libmongoc-1.0_FIND_QUIETLY)
-    message(WARNING "This CMake package is deprecated. Prefer instead to use the \"mongoc-1.0\" package and link to mongo::mongoc_shared.")
-endif()
-
-set (MONGOC_MAJOR_VERSION @libmongoc_VERSION_MAJOR@)
-set (MONGOC_MINOR_VERSION @libmongoc_VERSION_MINOR@)
-set (MONGOC_MICRO_VERSION @libmongoc_VERSION_PATCH@)
-set (MONGOC_VERSION @libmongoc_VERSION@)
-set (MONGOC_VERSION_FULL @libmongoc_VERSION_FULL@)
-
-include(CMakeFindDependencyMacro)
-find_dependency (mongoc-1.0)
-
-set(MONGOC_LIBRARY mongo::mongoc_shared)
-set(MONGOC_LIBRARIES mongo::mongoc_shared)
diff -pruN 1.30.4-1/build/cmake/libmongoc-static-1.0-config.cmake.in 2.0.2-1/build/cmake/libmongoc-static-1.0-config.cmake.in
--- 1.30.4-1/build/cmake/libmongoc-static-1.0-config.cmake.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/cmake/libmongoc-static-1.0-config.cmake.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-if(NOT libmongoc-static-1.0_FIND_QUIETLY)
-    message(WARNING "This CMake package is deprecated. Prefer instead to use the \"mongoc-1.0\" package and link to mongo::mongoc_static.")
-endif()
-
-set (MONGOC_STATIC_MAJOR_VERSION @libmongoc_VERSION_MAJOR@)
-set (MONGOC_STATIC_MINOR_VERSION @libmongoc_VERSION_MINOR@)
-set (MONGOC_STATIC_MICRO_VERSION @libmongoc_VERSION_PATCH@)
-set (MONGOC_STATIC_VERSION @libmongoc_VERSION@)
-set (MONGOC_STATIC_VERSION_FULL @libmongoc_VERSION_FULL@)
-
-include(CMakeFindDependencyMacro)
-find_dependency (mongoc-1.0)
-
-set(MONGOC_STATIC_LIBRARY mongo::mongoc_static)
-set(MONGOC_STATIC_LIBRARIES mongo::mongoc_static)
diff -pruN 1.30.4-1/build/generate-future-functions.py 2.0.2-1/build/generate-future-functions.py
--- 1.30.4-1/build/generate-future-functions.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/generate-future-functions.py	2025-06-19 15:42:22.000000000 +0000
@@ -87,7 +87,6 @@ typedef_list = [
     typedef("mongoc_iovec_ptr", "mongoc_iovec_t *"),
     typedef("mongoc_server_stream_ptr", "mongoc_server_stream_t *"),
     typedef("mongoc_query_flags_t", None),
-    typedef("const_mongoc_index_opt_t", "const mongoc_index_opt_t *"),
     typedef("mongoc_server_description_ptr", "mongoc_server_description_t *"),
     typedef("mongoc_ss_optype_t", None),
     typedef("mongoc_topology_ptr", "mongoc_topology_t *"),
@@ -104,6 +103,7 @@ typedef_list = [
             "const mongoc_write_concern_t *"),
     typedef("const_mongoc_ss_log_context_ptr",
             "const mongoc_ss_log_context_t *"),
+    typedef("mongoc_index_model_t_ptr_const_ptr", "mongoc_index_model_t *const *")
 ]
 
 type_list = [T.name for T in typedef_list]
@@ -201,11 +201,6 @@ future_functions = [
                      param("bson_ptr", "reply"),
                      param("bson_error_ptr", "error")]),
 
-    future_function("void",
-                    "mongoc_client_kill_cursor",
-                    [param("mongoc_client_ptr", "client"),
-                     param("int64_t", "cursor_id")]),
-
     future_function("mongoc_change_stream_ptr",
                     "mongoc_client_watch",
                     [param("mongoc_client_ptr", "client"),
@@ -220,32 +215,11 @@ future_functions = [
                      param("const_bson_ptr", "options"),
                      param("const_mongoc_read_prefs_ptr", "read_prefs")]),
 
-    future_function("int64_t",
-                    "mongoc_collection_count",
-                    [param("mongoc_collection_ptr", "collection"),
-                     param("mongoc_query_flags_t", "flags"),
-                     param("const_bson_ptr", "query"),
-                     param("int64_t", "skip"),
-                     param("int64_t", "limit"),
-                     param("const_mongoc_read_prefs_ptr", "read_prefs"),
-                     param("bson_error_ptr", "error")]),
-
-    future_function("int64_t",
-                    "mongoc_collection_count_with_opts",
-                    [param("mongoc_collection_ptr", "collection"),
-                     param("mongoc_query_flags_t", "flags"),
-                     param("const_bson_ptr", "query"),
-                     param("int64_t", "skip"),
-                     param("int64_t", "limit"),
-                     param("const_bson_ptr", "opts"),
-                     param("const_mongoc_read_prefs_ptr", "read_prefs"),
-                     param("bson_error_ptr", "error")]),
-
     future_function("bool",
-                    "mongoc_collection_create_index_with_opts",
+                    "mongoc_collection_create_indexes_with_opts",
                     [param("mongoc_collection_ptr", "collection"),
-                     param("const_bson_ptr", "keys"),
-                     param("const_mongoc_index_opt_t", "opt"),
+                     param("mongoc_index_model_t_ptr_const_ptr", "models"),
+                     param("size_t", "num_models"),
                      param("const_bson_ptr", "opts"),
                      param("bson_ptr", "reply"),
                      param("bson_error_ptr", "error")]),
@@ -290,13 +264,6 @@ future_functions = [
                      param("const_bson_ptr", "opts")]),
 
     future_function("bool",
-                    "mongoc_collection_stats",
-                    [param("mongoc_collection_ptr", "collection"),
-                     param("const_bson_ptr", "options"),
-                     param("bson_ptr", "stats"),
-                     param("bson_error_ptr", "error")]),
-
-    future_function("bool",
                     "mongoc_collection_insert_many",
                     [param("mongoc_collection_ptr", "collection"),
                      param("const_bson_ptr_ptr", "documents"),
@@ -340,15 +307,6 @@ future_functions = [
                      param("bson_error_ptr", "error")]),
 
     future_function("bool",
-                    "mongoc_collection_insert_bulk",
-                    [param("mongoc_collection_ptr", "collection"),
-                     param("mongoc_insert_flags_t", "flags"),
-                     param("const_bson_ptr_ptr", "documents"),
-                     param("uint32_t", "n_documents"),
-                     param("const_mongoc_write_concern_ptr", "write_concern"),
-                     param("bson_error_ptr", "error")]),
-
-    future_function("bool",
                     "mongoc_cluster_run_command_parts",
                     [param("mongoc_cluster_ptr", "cluster"),
                      param("mongoc_server_stream_ptr", "server_stream"),
@@ -420,12 +378,6 @@ future_functions = [
                      param("size_t", "min_bytes"),
                      param("uint32_t", "timeout_msec")]),
 
-    future_function("mongoc_gridfs_file_ptr",
-                    "mongoc_gridfs_find_one",
-                    [param("mongoc_gridfs_ptr", "gridfs"),
-                     param("const_bson_ptr", "query"),
-                     param("bson_error_ptr", "error")]),
-
     future_function("bool",
                     "mongoc_gridfs_file_remove",
                     [param("mongoc_gridfs_file_ptr", "file"),
@@ -573,7 +525,7 @@ def future_function_name(fn):
         # E.g. future_cursor_next().
         return 'future' + fn.name[len('mongoc'):]
     else:
-        # E.g. future__mongoc_client_kill_cursor().
+        # E.g. future_mongoc_client_command_simple().
         return 'future_' + fn.name
 
 
diff -pruN 1.30.4-1/build/generate-opts.py 2.0.2-1/build/generate-opts.py
--- 1.30.4-1/build/generate-opts.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/generate-opts.py	2025-06-19 15:42:22.000000000 +0000
@@ -49,7 +49,7 @@ def flatten(items):
 
 class Struct(OrderedDict):
     def __init__(self, items, opts_name='opts', generate_rst=True,
-                 generate_code=True, allow_extra=True, **defaults):
+                 generate_code=True, allow_extra=True, rst_prelude=None, **defaults):
         """Define an options struct.
 
         - items: List of pairs: (optionName, info)
@@ -64,6 +64,7 @@ class Struct(OrderedDict):
         self.generate_code = generate_code
         self.allow_extra = allow_extra
         self.defaults = defaults
+        self.rst_prelude = rst_prelude
 
     def default(self, item, fallback):
         return self.defaults.get(item, fallback)
@@ -293,7 +294,7 @@ opts_structs = OrderedDict([
     ], limit=0, allow_extra=False)),
 
     ('mongoc_change_stream_opts_t', Struct([
-        ('batchSize', {'type': 'int32_t', 'help': 'An ``int32`` representing number of documents requested to be returned on each call to :symbol:`mongoc_change_stream_next`'}),
+        ('batchSize', {'type': 'int32_t', 'help': 'An ``int32`` requesting a limit of documents returned in each server reply. If positive, the ``batchSize`` is applied to both ``aggregate`` and ``getMore`` commands. If 0, the ``batchSize`` is only applied to the ``aggregate`` command (Useful to request an immediate cursor without significant server-side work. See `Aggregate Data Specifying Batch Size <https://www.mongodb.com/docs/manual/reference/command/aggregate/#aggregate-data-specifying-batch-size>`_). If omitted or negative, the value is ignored and server defaults are used (See `Cursor Batches <https://www.mongodb.com/docs/manual/core/cursors/#cursor-batches>`_ for a description of server defaults).'}),
         ('resumeAfter', {'type': 'document', 'help': 'A ``Document`` representing the logical starting point of the change stream. The result of :symbol:`mongoc_change_stream_get_resume_token()` or the ``_id`` field  of any change received from a change stream can be used here. This option is mutually exclusive with ``startAfter`` and ``startAtOperationTime``.'}),
         ('startAfter', {'type': 'document', 'help': 'A ``Document`` representing the logical starting point of the change stream. Unlike ``resumeAfter``, this can resume notifications after an "invalidate" event. The result of :symbol:`mongoc_change_stream_get_resume_token()` or the ``_id`` field  of any change received from a change stream can be used here.  This option is mutually exclusive with ``resumeAfter`` and ``startAtOperationTime``.'}),
         ('startAtOperationTime', {'type': 'timestamp', 'help': 'A ``Timestamp``. The change stream only provides changes that occurred at or after the specified timestamp. Any command run against the server will return an operation time that can be used here. This option is mutually exclusive with ``resumeAfter`` and ``startAfter``.'}),
@@ -317,7 +318,7 @@ opts_structs = OrderedDict([
         }),
         ('showExpandedEvents', { 'type': 'bool', 'help': 'Set to ``true`` to return an expanded list of change stream events. Available only on MongoDB versions >=6.0'}),
         comment_option_string_pre_4_4,
-    ], fullDocument=None, fullDocumentBeforeChange=None)),
+    ], fullDocument=None, fullDocumentBeforeChange=None, batchSize=-1, rst_prelude=".. versionchanged:: 2.0.0 ``batchSize`` of 0 is applied to the ``aggregate`` command. 0 was previously ignored.")),
 
     ('mongoc_create_index_opts_t', Struct([
         write_concern_option,
@@ -474,6 +475,9 @@ for struct_name, struct in opts_structs.
     print(file_name)
     f = open(joinpath(doc_includes, file_name), 'w')
     f.write (disclaimer)
+    if struct.rst_prelude is not None:
+        f.write(struct.rst_prelude)
+        f.write("\n\n")
     f.write(
         "``%s`` may be NULL or a BSON document with additional"
         " command options:\n\n" % struct.opts_name)
diff -pruN 1.30.4-1/build/opts_templates/mongoc-opts.c.template 2.0.2-1/build/opts_templates/mongoc-opts.c.template
--- 1.30.4-1/build/opts_templates/mongoc-opts.c.template	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/build/opts_templates/mongoc-opts.c.template	2025-06-19 15:42:22.000000000 +0000
@@ -1,6 +1,6 @@
 #include <mongoc/mongoc-opts-helpers-private.h>
 #include <mongoc/mongoc-opts-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-client-private.h>
 
@@ -54,10 +54,10 @@ _{{ struct_name }}_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -100,18 +100,18 @@ _{{ struct_name }}_parse (
                &{{ struct_name }}->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
 {% else %}
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
 {% endif %}
       }
diff -pruN 1.30.4-1/debian/changelog 2.0.2-1/debian/changelog
--- 1.30.4-1/debian/changelog	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/changelog	2025-06-17 21:04:34.000000000 +0000
@@ -1,3 +1,9 @@
+mongo-c-driver (2.0.2-1) experimental; urgency=medium
+
+  * New upstream release
+
+ -- Roberto C. Sanchez <roberto@connexer.com>  Tue, 17 Jun 2025 17:04:34 -0400
+
 mongo-c-driver (1.30.4-1) unstable; urgency=medium
 
   * New upstream release
diff -pruN 1.30.4-1/debian/control 2.0.2-1/debian/control
--- 1.30.4-1/debian/control	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/control	2025-06-17 21:04:34.000000000 +0000
@@ -26,7 +26,7 @@ Package: libmongoc-dev
 Section: libdevel
 Architecture: any
 Build-Profiles: <!pkg.mongo-c-driver.no-libmongocrypt>
-Depends: libmongoc-1.0-0t64 (= ${binary:Version}),
+Depends: libmongoc2-2 (= ${binary:Version}),
          libbson-dev (= ${binary:Version}),
          libmongocrypt-dev (>= 1.12.0),
          libssl-dev,
@@ -43,10 +43,7 @@ Description: MongoDB C client library -
  This package contains all files necessary to develop applications which
  use libmongoc.
 
-Package: libmongoc-1.0-0t64
-Provides: ${t64:Provides}
-Replaces: libmongoc-1.0-0
-Breaks: libmongoc-1.0-0 (<< ${source:Version})
+Package: libmongoc2-2
 Architecture: any
 Build-Profiles: <!pkg.mongo-c-driver.no-libmongocrypt>
 Depends: ${misc:Depends},
@@ -73,7 +70,7 @@ Description: MongoDB C client library -
 Package: libbson-dev
 Section: libdevel
 Architecture: any
-Depends: libbson-1.0-0t64 (= ${binary:Version}),
+Depends: libbson2-2 (= ${binary:Version}),
          ${misc:Depends}
 Description: Library to parse and generate BSON documents - dev files
  libbson parses and generates BSON documents, the data format for
@@ -84,10 +81,7 @@ Description: Library to parse and genera
  This package contains all files necessary to develop applications which
  use libbson.
 
-Package: libbson-1.0-0t64
-Provides: ${t64:Provides}
-Replaces: libbson-1.0-0
-Breaks: libbson-1.0-0 (<< ${source:Version})
+Package: libbson2-2
 Architecture: any
 Depends: ${misc:Depends},
          ${shlibs:Depends}
diff -pruN 1.30.4-1/debian/copyright 2.0.2-1/debian/copyright
--- 1.30.4-1/debian/copyright	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/copyright	2025-06-17 21:04:34.000000000 +0000
@@ -40,28 +40,6 @@ Files: debian/*
 Copyright: 2015-2018 MongoDB, Inc.
 License: Apache-2.0
 
-Files: src/libbson/src/bson/bson-md5.h
-Copyright: 1999, 2002 Aladdin Enterprises.
-License: ZLib
- This software is provided 'as-is', without any express or implied
- warranty.  In no event will the authors be held liable for any damages
- arising from the use of this software.
- .
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
- .
- 1. The origin of this software must not be misrepresented; you must not
-    claim that you wrote the original software. If you use this software
-    in a product, an acknowledgment in the product documentation would be
-    appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
-    misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
- .
- L. Peter Deutsch
- ghost@aladdin.com
-
 License: Apache-2.0
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
diff -pruN 1.30.4-1/debian/gbp.conf 2.0.2-1/debian/gbp.conf
--- 1.30.4-1/debian/gbp.conf	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/gbp.conf	2025-06-17 21:04:34.000000000 +0000
@@ -14,7 +14,7 @@ prebuild = bash -c "
     utf8proc_rm_files=\"$(find src/utf8proc-* -printf '%p ')\" &&
     # Create upstream tarball from reference, exclude items that do not belong
     pushd $GBP_GIT_DIR/.. &&
-    git archive --format=tar --prefix=mongo-c-driver-\${upstream_version}/ HEAD | tar -f - --delete mongo-c-driver-\${upstream_version}/debian \$zlib_filter_files \$utf8proc_filter_files | gzip > $GBP_BUILD_DIR/../mongo-c-driver_\${upstream_version}.orig.tar.gz &&
+    ( [ -f $GBP_BUILD_DIR/../mongo-c-driver_\${upstream_version}.orig.tar.gz ] || git archive --format=tar --prefix=mongo-c-driver-\${upstream_version}/ HEAD | tar -f - --delete mongo-c-driver-\${upstream_version}/debian \$zlib_filter_files \$utf8proc_filter_files | gzip > $GBP_BUILD_DIR/../mongo-c-driver_\${upstream_version}.orig.tar.gz ) &&
     popd &&
     rm -rf \$zlib_rm_files \$utf8proc_rm_files"
 
diff -pruN 1.30.4-1/debian/libbson-1.0-0t64.dirs 2.0.2-1/debian/libbson-1.0-0t64.dirs
--- 1.30.4-1/debian/libbson-1.0-0t64.dirs	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libbson-1.0-0t64.dirs	1970-01-01 00:00:00.000000000 +0000
@@ -1 +0,0 @@
-usr/lib
diff -pruN 1.30.4-1/debian/libbson-1.0-0t64.install 2.0.2-1/debian/libbson-1.0-0t64.install
--- 1.30.4-1/debian/libbson-1.0-0t64.install	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libbson-1.0-0t64.install	1970-01-01 00:00:00.000000000 +0000
@@ -1 +0,0 @@
-usr/lib/*/libbson*.so.*
diff -pruN 1.30.4-1/debian/libbson-1.0-0t64.lintian-overrides 2.0.2-1/debian/libbson-1.0-0t64.lintian-overrides
--- 1.30.4-1/debian/libbson-1.0-0t64.lintian-overrides	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libbson-1.0-0t64.lintian-overrides	1970-01-01 00:00:00.000000000 +0000
@@ -1,4 +0,0 @@
-# Chosen not to maintain a symbols file, we'll check ABI stability with other
-# tools.
-libbson-1.0-0t64: no-symbols-control-file
-libbson-1.0-0t64: package-name-doesnt-match-sonames libbson-1.0-0
diff -pruN 1.30.4-1/debian/libbson-dev.install 2.0.2-1/debian/libbson-dev.install
--- 1.30.4-1/debian/libbson-dev.install	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libbson-dev.install	2025-06-17 21:04:34.000000000 +0000
@@ -1,6 +1,5 @@
-usr/include/libbson*
+usr/include/bson*
 usr/lib/*/libbson*.a
 usr/lib/*/libbson*.so
-usr/lib/*/pkgconfig/libbson*
-usr/lib/*/cmake/libbson*
+usr/lib/*/pkgconfig/bson*
 usr/lib/*/cmake/bson*
diff -pruN 1.30.4-1/debian/libbson2-2.dirs 2.0.2-1/debian/libbson2-2.dirs
--- 1.30.4-1/debian/libbson2-2.dirs	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libbson2-2.dirs	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1 @@
+usr/lib
diff -pruN 1.30.4-1/debian/libbson2-2.install 2.0.2-1/debian/libbson2-2.install
--- 1.30.4-1/debian/libbson2-2.install	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libbson2-2.install	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1 @@
+usr/lib/*/libbson*.so.*
diff -pruN 1.30.4-1/debian/libbson2-2.lintian-overrides 2.0.2-1/debian/libbson2-2.lintian-overrides
--- 1.30.4-1/debian/libbson2-2.lintian-overrides	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libbson2-2.lintian-overrides	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1,3 @@
+# Chosen not to maintain a symbols file, we'll check ABI stability with other
+# tools.
+libbson2-2: no-symbols-control-file
diff -pruN 1.30.4-1/debian/libmongoc-1.0-0t64.docs 2.0.2-1/debian/libmongoc-1.0-0t64.docs
--- 1.30.4-1/debian/libmongoc-1.0-0t64.docs	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libmongoc-1.0-0t64.docs	1970-01-01 00:00:00.000000000 +0000
@@ -1,3 +0,0 @@
-debian/tmp/usr/share/mongo-c-driver/NEWS
-debian/tmp/usr/share/mongo-c-driver/README.rst
-debian/tmp/usr/share/mongo-c-driver/THIRD_PARTY_NOTICES
diff -pruN 1.30.4-1/debian/libmongoc-1.0-0t64.install 2.0.2-1/debian/libmongoc-1.0-0t64.install
--- 1.30.4-1/debian/libmongoc-1.0-0t64.install	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libmongoc-1.0-0t64.install	1970-01-01 00:00:00.000000000 +0000
@@ -1 +0,0 @@
-usr/lib/*/libmongoc-[0-9]*.so.*
diff -pruN 1.30.4-1/debian/libmongoc-1.0-0t64.lintian-overrides 2.0.2-1/debian/libmongoc-1.0-0t64.lintian-overrides
--- 1.30.4-1/debian/libmongoc-1.0-0t64.lintian-overrides	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libmongoc-1.0-0t64.lintian-overrides	1970-01-01 00:00:00.000000000 +0000
@@ -1,4 +0,0 @@
-# Chosen not to maintain a symbols file, we'll check ABI stability with other
-# tools.
-libmongoc-1.0-0t64: no-symbols-control-file
-libmongoc-1.0-0t64: package-name-doesnt-match-sonames libmongoc-1.0-0
diff -pruN 1.30.4-1/debian/libmongoc-dev.install 2.0.2-1/debian/libmongoc-dev.install
--- 1.30.4-1/debian/libmongoc-dev.install	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/libmongoc-dev.install	2025-06-17 21:04:34.000000000 +0000
@@ -1,7 +1,4 @@
-usr/include/libmongoc*
-usr/lib/*/libmongoc-static-[0-9]*.a
-usr/lib/*/libmongoc-[0-9]*.so
-usr/lib/*/pkgconfig/libmongoc-[0-9]*
-usr/lib/*/pkgconfig/libmongoc-ssl-[0-9]*
-usr/lib/*/cmake/libmongoc*
+usr/include/mongoc*
+usr/lib/*/libmongoc*.so
+usr/lib/*/pkgconfig/mongoc*
 usr/lib/*/cmake/mongoc*
diff -pruN 1.30.4-1/debian/libmongoc2-2.docs 2.0.2-1/debian/libmongoc2-2.docs
--- 1.30.4-1/debian/libmongoc2-2.docs	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libmongoc2-2.docs	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1,3 @@
+debian/tmp/usr/share/mongo-c-driver/*/NEWS
+debian/tmp/usr/share/mongo-c-driver/*/README.rst
+debian/tmp/usr/share/mongo-c-driver/*/THIRD_PARTY_NOTICES
diff -pruN 1.30.4-1/debian/libmongoc2-2.install 2.0.2-1/debian/libmongoc2-2.install
--- 1.30.4-1/debian/libmongoc2-2.install	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libmongoc2-2.install	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1 @@
+usr/lib/*/libmongoc*.so.*
diff -pruN 1.30.4-1/debian/libmongoc2-2.lintian-overrides 2.0.2-1/debian/libmongoc2-2.lintian-overrides
--- 1.30.4-1/debian/libmongoc2-2.lintian-overrides	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/debian/libmongoc2-2.lintian-overrides	2025-06-17 21:04:34.000000000 +0000
@@ -0,0 +1,3 @@
+# Chosen not to maintain a symbols file, we'll check ABI stability with other
+# tools.
+libmongoc2-2: no-symbols-control-file
diff -pruN 1.30.4-1/debian/rules 2.0.2-1/debian/rules
--- 1.30.4-1/debian/rules	2025-05-07 19:11:43.000000000 +0000
+++ 2.0.2-1/debian/rules	2025-06-17 21:04:34.000000000 +0000
@@ -35,11 +35,11 @@ override_dh_auto_configure:
 	[ "$(DOCS)" = "ON" ] || echo "Found 'nodoc' in 'DEB_BUILD_OPTIONS'; not building documentation"
 	echo $(DEB_VERSION_UPSTREAM) > VERSION_CURRENT
 	dh_auto_configure -- \
-	-DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF \
 	-DENABLE_MONGOC=ON \
 	-DENABLE_MAN_PAGES=$(DOCS) \
 	-DENABLE_HTML_DOCS=$(DOCS) \
 	-DENABLE_MAINTAINER_FLAGS=ON \
+	-DENABLE_PIC=OFF \
 	-DENABLE_TESTS=OFF \
 	-DENABLE_ZLIB=SYSTEM \
 	-DUSE_BUNDLED_UTF8PROC=OFF
diff -pruN 1.30.4-1/docs/dev/deps.rst 2.0.2-1/docs/dev/deps.rst
--- 1.30.4-1/docs/dev/deps.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/docs/dev/deps.rst	2025-06-19 15:42:22.000000000 +0000
@@ -47,10 +47,9 @@ copyright statements, URLs, and license
 
 .. file:: etc/cyclonedx.sbom.json
 
-   The `SBOM-lite`_ for the C driver project. This is injested automatically and
-   asynchronously by Silk to produce the `augmented SBOM`_. This file is
-   generated semi-automatically from `etc/purls.txt` and the `+sbom-generate`
-   Earthly target.
+   The `SBOM-lite`_ for the C driver project. This file is generated
+   semi-automatically from `etc/purls.txt` and the `+sbom-generate` Earthly
+   target. This file is used by SilkBomb to produce an `augmented SBOM`_.
 
    .. warning:: This file is **partially generated**! Prefer to edit `etc/purls.txt`!
       Refer to: `sbom-lite-updating`
@@ -98,38 +97,10 @@ The augmented SBOM contains extra data a
 `SBOM-lite <sbom-lite>`, including vulnerabilities known at the time of the
 augmented SBOM's generation. [#asbom-vulns]_
 
-The augmented SBOM is produced automatically and asynchronously as part of an
-external process that is not contained within the repository itself. The
-augmented SBOM is downloaded from an internal service using the `+sbom-download`
-Earthly target, which is automatically included in the release archive for the
-`+release-archive` target.
-
-.. _silk-asset-group:
-
-Silk Asset Groups
-*****************
-
-.. note:: A Silk asset group will be created automatically for each branch that
-   is executed in CI.
-
-We use Silk's *asset groups* to allow tracking of multiple versions of the
-SBOM-lite_ simultaneously (i.e. one for each release branch). These asset groups
-correspond to branches within the repository, and are created automatically when
-CI executes for the first time on a particular branch. If you need an asset
-group for a branch that has not run in CI, use the `+create-silk-asset-group`
-Earthly target to create the asset group on-demand.
-
-Note that Silk pulls from the upstream Git repository for an asset group, so
-creating an asset group for a branch that does not exist in the main upstream
-repository will not work.
-
-.. file:: tools/create-silk-asset-group.py
-
-   A Python script that will create an `asset group <silk-asset-group>` in Silk
-   based on a set of parameters. Execute with ``--help`` for more information.
-   For the C driver, it is easier to use the `+create-silk-asset-group` Earthly
-   target.
-
+The augmented SBOM is produced by an external process that is not contained
+within the repository itself. The augmented SBOM must be downloaded from a
+recent execution of the ``sbom`` task in an Evergreen patch or commit build.
+This file is included in the release archive for the `+release-archive` target.
 
 .. _snyk scanning:
 
@@ -152,8 +123,7 @@ detect the other dependencies within the
 target is written to avoid this issue and allow Snyk to accurately detect other
 dependencies within the project.
 
-Due to difficulty coordinating the behavior of Snyk and Silk at time of
-writing, vulnerability collection is partially a manual process. This is
+For now, vulnerability collection is partially a manual process. This is
 especially viable as the native code contains a very small number of
 dependencies and it is trivial to validate the output of Snyk by hand.
 
diff -pruN 1.30.4-1/docs/dev/earthly.rst 2.0.2-1/docs/dev/earthly.rst
--- 1.30.4-1/docs/dev/earthly.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/docs/dev/earthly.rst	2025-06-19 15:42:22.000000000 +0000
@@ -90,11 +90,6 @@ enumerated using ``earthly ls`` or ``ear
       `+sign-file/signature.asc` for the release. The exported filenames are
       based on the `--version` argument.
 
-   .. rubric:: Parameters
-   .. option:: --sbom_branch <branch>
-
-      Forwarded to `+release-archive --sbom_branch`
-
    .. option:: --version <version>
 
       Affects the output filename and archive prefix paths in
@@ -108,22 +103,22 @@ enumerated using ``earthly ls`` or ``ear
 
    .. rubric:: Secrets
 
-   Secrets for the `+sbom-download`, `+snyk-test`, and `+sign-file` targets are
-   required for this target.
+   Secrets for the `+snyk-test` and `+sign-file` targets are required for this
+   target.
 
 
 .. program:: +release-archive
 .. earthly-target:: +release-archive
 
-   Generate a source release archive of the repository at a specifiy branch.
-   Requires the secrets for `+sbom-download` and `+snyk-test`.
+   Generate a source release archive of the repository for the specified branch.
+   Requires the secrets for `+snyk-test`.
+   Requires ``etc/augmented-sbom.json`` is present (obtained from Evergreen).
 
    .. earthly-artifact:: +release-archive/release.tar.gz
 
       The resulting source distribution archive for the specified branch. The
       generated archive includes the source tree, but also includes other
-      release artifacts that are generated on-the-fly when invoked e.g. the
-      `+sbom-download/augmented-sbom.json` artifact.
+      release artifacts that are generated on-the-fly when invoked.
 
    .. earthly-artifact:: +release-archive/ssdlc_compliance_report.md
 
@@ -131,11 +126,6 @@ enumerated using ``earthly ls`` or ``ear
       content of ``etc/ssdlc.md``, which has certain substrings replaced based
       on attributes of the release.
 
-   .. rubric:: Parameters
-   .. option:: --sbom_branch <branch>
-
-      Forwarded as `+sbom-download --branch` to download the augmented SBOM.
-
    .. option:: --ref <git-ref>
 
       Specifies the Git revision that is used when we use ``git archive`` to
@@ -150,38 +140,10 @@ enumerated using ``earthly ls`` or ``ear
       no effect on the files archived, which is selected by
       `+release-archive --ref`.
 
+.. program:: +sbom-validate
+.. earthly-target:: +sbom-validate
 
-.. program:: +sbom-download
-.. earthly-target:: +sbom-download
-
-   Download an `augmented SBOM <augmented-sbom>` from Silk for a given project
-   branch. This target explicitly disables caching, because the upstream SBOM
-   file can change arbitrarily.
-
-   .. earthly-artifact:: +sbom-download/augmented-sbom.json
-
-      The `augmented SBOM <augmented-sbom>` downloaded from Silk for the requested branch.
-
-   .. rubric:: Parameters
-   .. option:: --branch <branch>
-
-      **Required**. Specifies the branch of the repository from which we are
-      requesting an SBOM.
-
-      .. note::
-
-         It is *required* that the `Silk asset group <silk-asset-group>` has
-         been created for the given branch before the `+sbom-download` target
-         can succeed. See: `+create-silk-asset-group`
-
-   .. rubric:: Secrets
-   .. envvar::
-      SILK_CLIENT_ID
-      SILK_CLIENT_SECRET
-
-      **Required**. [#creds]_
-
-      .. seealso:: `earthly.secrets`
+   Validate the `etc/cyclonedx.sbom.json`.
 
 .. program:: +sign-file
 .. earthly-target:: +sign-file
@@ -241,32 +203,15 @@ enumerated using ``earthly ls`` or ``ear
 
    .. seealso:: `sbom-lite` and `sbom-lite-updating`
 
+.. earthly-target:: +sbom-generate-new-serial-number
 
-.. program:: +create-silk-asset-group
-.. earthly-target:: +create-silk-asset-group
-
-   Creates a new `Silk asset group <silk-asset-group>` for a branch in the
-   repository. This target executes the `tools/create-silk-asset-group.py`
-   script with the appropriate arguments.
-
-   .. note:: For branches that execute in CI, running this target manually is
-      not necessary, as it is run automatically for every build.
-
-   .. rubric:: Parameters
-   .. option:: --branch <branch>
-
-      The repository branch for which to create the new asset group. If not
-      specified, the branch name will be inferred by asking Git.
+   Equivalent to `+sbom-generate` but uses the ``--generate-new-serial-number``
+   flag to generate a new unique serial number and reset the SBOM version to 1.
 
-   .. rubric:: Secrets
-   .. envvar::
-         SILK_CLIENT_ID
-         SILK_CLIENT_SECRET
-      :noindex:
-
-      **Required**. [#creds]_
+   After running this target, the contents of the `etc/cyclonedx.sbom.json` file
+   may change.
 
-      .. seealso:: `earthly.secrets`
+   .. seealso:: `sbom-lite` and `sbom-lite-updating`
 
 .. program:: +snyk-monitor-snapshot
 .. earthly-target:: +snyk-monitor-snapshot
diff -pruN 1.30.4-1/docs/dev/releasing.rst 2.0.2-1/docs/dev/releasing.rst
--- 1.30.4-1/docs/dev/releasing.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/docs/dev/releasing.rst	2025-06-19 15:42:22.000000000 +0000
@@ -381,15 +381,15 @@ running :any:`+signed-release`, one will
 required for it to succeed:
 
 1. :ref:`Authenticate with Artifactory <earthly.artifactory-auth>`
-2. Set the Earthly secrets required for the :any:`+sign-file` and
-   :any:`+sbom-download` targets.
+2. Set the Earthly secrets required for the :any:`+sign-file` target.
+3. Download an augmented SBOM from a recent execution of the ``sbom`` task in
+   an Evergreen patch or commit build and save it to ``etc/augmented-sbom.json``.
 
 Once these prerequesites are met, creating the release archive can be done using
 the :any:`+signed-release` target.::
 
-   $ ./tools/earthly.sh --artifact +signed-release/dist dist --sbom_branch=$SBOM_BRANCH --version=$NEW_VERSION
+   $ ./tools/earthly.sh --artifact +signed-release/dist dist --version=$NEW_VERSION
 
-.. note:: `$SBOM_BRANCH` must be ``master`` for a minor release, or ``$RELEASE_BRANCH`` for a patch release.
 .. note:: `$NEW_VERSION` must correspond to the Git tag created by the release.
 
 The above command will create a `dist/` directory in the working directory that
@@ -638,4 +638,3 @@ updating the mongo-cxx-driver container
 version. `Details for this process are documented here`__
 
 __ https://github.com/mongodb/mongo-cxx-driver/blob/5f2077f98140ea656983ea5881de31d73bb3f735/etc/releasing.md#docker-image-build-and-publish
-
diff -pruN 1.30.4-1/etc/cyclonedx.sbom.json 2.0.2-1/etc/cyclonedx.sbom.json
--- 1.30.4-1/etc/cyclonedx.sbom.json	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/etc/cyclonedx.sbom.json	2025-06-19 15:42:22.000000000 +0000
@@ -121,7 +121,7 @@
     }
   ],
   "metadata": {
-    "timestamp": "2025-02-24T17:36:21.321776+00:00",
+    "timestamp": "2025-02-19T20:15:38.178269+00:00",
     "tools": [
       {
         "externalReferences": [
@@ -164,7 +164,7 @@
       }
     ]
   },
-  "serialNumber": "urn:uuid:1005307f-2f33-45f2-a5fb-bfa9f2bf2fc1",
+  "serialNumber": "urn:uuid:298714b7-1628-44c5-90a2-3c351f3626c5",
   "version": 1,
   "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
   "bomFormat": "CycloneDX",
diff -pruN 1.30.4-1/etc/prior_version.txt 2.0.2-1/etc/prior_version.txt
--- 1.30.4-1/etc/prior_version.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/etc/prior_version.txt	2025-06-19 15:42:22.000000000 +0000
@@ -1 +1 @@
-1.30.3
\ No newline at end of file
+2.0.1
\ No newline at end of file
diff -pruN 1.30.4-1/src/CMakeLists.txt 2.0.2-1/src/CMakeLists.txt
--- 1.30.4-1/src/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -13,20 +13,20 @@ if (CMAKE_CXX_COMPILER)
    # Add a C++ source file that will #include the main C headers. This "library"
    # does nothing other than validate that the C headers are valid C++ headers.
    add_library (mongoc-cxx-check OBJECT cpp-check.cpp)
-   if (TARGET mongoc_static)
-      target_link_libraries (mongoc-cxx-check PRIVATE mongoc_static)
+   if (TARGET mongoc::static)
+      target_link_libraries (mongoc-cxx-check PRIVATE mongoc::static)
    else ()
-      target_link_libraries (mongoc-cxx-check PRIVATE mongoc_shared)
+      target_link_libraries (mongoc-cxx-check PRIVATE mongoc::shared)
    endif ()
 endif ()
 
 # public-header-warnings
 add_executable(public-header-warnings EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/c-check.c)
 
-if (TARGET mongoc_static)
-   target_link_libraries(public-header-warnings PRIVATE mongoc_static)
+if (TARGET mongoc::static)
+   target_link_libraries(public-header-warnings PRIVATE mongoc::static)
 else ()
-   target_link_libraries(public-header-warnings PRIVATE mongoc_shared)
+   target_link_libraries(public-header-warnings PRIVATE mongoc::shared)
 endif ()
 
 target_compile_options(public-header-warnings PRIVATE
@@ -35,6 +35,9 @@ target_compile_options(public-header-war
   $<$<C_COMPILER_ID:AppleClang,Clang,GNU>:-Werror>
   $<$<C_COMPILER_ID:AppleClang,Clang,GNU>:-Wno-declaration-after-statement>
   $<$<C_COMPILER_ID:AppleClang,Clang,GNU>:-Wno-disabled-macro-expansion>
+  $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-c++98-compat-pedantic>
+  $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-pre-c2x-compat>
+  $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-unsafe-buffer-usage>
   $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-padded>
   $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-reserved-identifier>
   $<$<C_COMPILER_ID:AppleClang,Clang>:-Wno-documentation-unknown-command>
diff -pruN 1.30.4-1/src/common/CMakeLists.txt 2.0.2-1/src/common/CMakeLists.txt
--- 1.30.4-1/src/common/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -9,3 +9,20 @@ configure_file (
         "${CMAKE_CURRENT_SOURCE_DIR}/src/common-config.h.in"
         "${CMAKE_CURRENT_BINARY_DIR}/src/common-config.h"
 )
+
+add_library(mongo-mlib INTERFACE)
+add_library(mongo::mlib ALIAS mongo-mlib)
+target_include_directories(mongo-mlib INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/src>)
+set_property(TARGET mongo-mlib PROPERTY EXPORT_NAME mongo::mlib)
+
+if(CMAKE_CXX_COMPILER)
+    add_executable(mlib-ckdint-test src/mlib/ckdint.test.cpp)
+    set_target_properties(mlib-ckdint-test PROPERTIES
+        COMPILE_FEATURES cxx_std_11
+        LINK_LIBRARIES mongo::mlib
+        # Enable -fPIC, required for some build configurations
+        POSITION_INDEPENDENT_CODE TRUE
+        )
+    add_test(NAME mongoc/mlib/ckdint COMMAND mlib-ckdint-test)
+    set_property(TEST mongoc/mlib/ckdint PROPERTY SKIP_REGULAR_EXPRESSION "@@ctest-skipped@@")
+endif()
diff -pruN 1.30.4-1/src/common/src/bson-dsl.md 2.0.2-1/src/common/src/bson-dsl.md
--- 1.30.4-1/src/common/src/bson-dsl.md	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/bson-dsl.md	2025-06-19 15:42:22.000000000 +0000
@@ -203,7 +203,7 @@ satisfies `cond` into the parent documen
 The *Predicate* `cond` will be evaluated for every element in `b`. Refer:
 [*Predicate*](#Predicate).
 
-To copy *all* elements from `b`, simply use the bare `true` predicate.
+To copy *all* elements from `b`, simply use the bare `always` predicate.
 
 
 #### `insertFromIter()`
@@ -618,7 +618,7 @@ Each `when` is considered in the listed
 After any `when` clause matches an element, no subsequent `when` clauses are
 considered.
 
-An `else(ops...)` clause is equivalent to `when(true, ops...)`.
+An `else(ops...)` clause is equivalent to `when(always, ops...)`.
 
 If no clause matches the element, nothing happens.
 
@@ -670,12 +670,12 @@ The `isNumeric` predicate matches if the
 Matches only the final element in a document.
 
 
-#### `true`
+#### `always`
 
 Always matches.
 
 
-#### `false`
+#### `never`
 
 Never matches.
 
@@ -1032,4 +1032,3 @@ by a single `AGAIN(f)`.
 
 There are additional tricks required to make `EVAL`, `MAP`, and token pasting
 play nice, but those details are not necessary here.
-
diff -pruN 1.30.4-1/src/common/src/common-b64.c 2.0.2-1/src/common/src/common-b64.c
--- 1.30.4-1/src/common/src/common-b64.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-b64.c	2025-06-19 15:42:22.000000000 +0000
@@ -42,6 +42,7 @@
 
 #include <bson/bson.h>
 #include <common-b64-private.h>
+#include <mlib/loop.h>
 
 #define Assert(Cond) \
    if (!(Cond))      \
@@ -118,21 +119,21 @@ mcommon_b64_ntop (uint8_t const *src, si
    size_t datalength = 0;
    uint8_t input[3];
    uint8_t output[4];
-   size_t i;
 
    if (!target) {
       return -1;
    }
 
-   while (2 < srclength) {
+   // While we have at least three chars to read:
+   while (srclength > 2) {
       input[0] = *src++;
       input[1] = *src++;
       input[2] = *src++;
       srclength -= 3;
 
       output[0] = input[0] >> 2;
-      output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
-      output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
+      output[1] = (uint8_t) (((input[0] & 0x03) << 4) + (input[1] >> 4));
+      output[2] = (uint8_t) (((input[1] & 0x0f) << 2) + (input[2] >> 6));
       output[3] = input[2] & 0x3f;
       Assert (output[0] < 64);
       Assert (output[1] < 64);
@@ -153,12 +154,10 @@ mcommon_b64_ntop (uint8_t const *src, si
       /* Get what's left. */
       input[0] = input[1] = input[2] = '\0';
 
-      for (i = 0; i < srclength; i++) {
-         input[i] = *src++;
-      }
+      memcpy (input, src, srclength);
       output[0] = input[0] >> 2;
-      output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
-      output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
+      output[1] = (uint8_t) (((input[0] & 0x03) << 4) + (input[1] >> 4));
+      output[2] = (uint8_t) (((input[1] & 0x0f) << 2) + (input[2] >> 6));
       Assert (output[0] < 64);
       Assert (output[1] < 64);
       Assert (output[2] < 64);
@@ -277,27 +276,24 @@ static const uint8_t mongoc_b64rmap_inva
 
 static MONGOC_COMMON_ONCE_FUN (bson_b64_initialize_rmap)
 {
-   int i;
-   unsigned char ch;
-
    /* Null: end of string, stop parsing */
    mongoc_b64rmap[0] = mongoc_b64rmap_end;
 
-   for (i = 1; i < 256; ++i) {
-      ch = (unsigned char) i;
+   mlib_foreach_urange (i, 1, 256) {
+      const uint8_t ch = (uint8_t) i;
       /* Whitespaces */
       if (bson_isspace (ch))
-         mongoc_b64rmap[i] = mongoc_b64rmap_space;
+         mongoc_b64rmap[ch] = mongoc_b64rmap_space;
       /* Padding: stop parsing */
       else if (ch == Pad64)
-         mongoc_b64rmap[i] = mongoc_b64rmap_end;
+         mongoc_b64rmap[ch] = mongoc_b64rmap_end;
       /* Non-base64 char */
       else
-         mongoc_b64rmap[i] = mongoc_b64rmap_invalid;
+         mongoc_b64rmap[ch] = mongoc_b64rmap_invalid;
    }
 
    /* Fill reverse mapping for base64 chars */
-   for (i = 0; Base64[i] != '\0'; ++i)
+   for (uint8_t i = 0; Base64[i] != '\0'; ++i)
       mongoc_b64rmap[(uint8_t) Base64[i]] = i;
 
    MONGOC_COMMON_ONCE_RETURN;
@@ -313,7 +309,7 @@ mongoc_b64_pton_do (char const *src, uin
    tarindex = 0;
 
    while (1) {
-      ch = *src++;
+      ch = (uint8_t) *src++;
       ofs = mongoc_b64rmap[ch];
 
       if (ofs >= mongoc_b64rmap_special) {
@@ -367,8 +363,8 @@ mongoc_b64_pton_do (char const *src, uin
     * on a byte boundary, and/or with erroneous trailing characters.
     */
 
-   if (ch == Pad64) { /* We got a pad char. */
-      ch = *src++;    /* Skip it, get next. */
+   if (ch == Pad64) {        /* We got a pad char. */
+      ch = (uint8_t) *src++; /* Skip it, get next. */
       switch (state) {
       case 0: /* Invalid = in first position */
       case 1: /* Invalid = in second position */
@@ -376,13 +372,13 @@ mongoc_b64_pton_do (char const *src, uin
 
       case 2: /* Valid, means one byte of info */
          /* Skip any number of spaces. */
-         for ((void) NULL; ch != '\0'; ch = *src++)
+         for ((void) NULL; ch != '\0'; ch = (uint8_t) *src++)
             if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
                break;
          /* Make sure there is another trailing = sign. */
          if (ch != Pad64)
             return (-1);
-         ch = *src++; /* Skip the = */
+         ch = (uint8_t) *src++; /* Skip the = */
          /* Fall through to "single trailing =" case. */
          /* FALLTHROUGH */
 
@@ -391,7 +387,7 @@ mongoc_b64_pton_do (char const *src, uin
           * We know this char is an =.  Is there anything but
           * whitespace after it?
           */
-         for ((void) NULL; ch != '\0'; ch = *src++)
+         for ((void) NULL; ch != '\0'; ch = (uint8_t) *src++)
             if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
                return (-1);
 
@@ -422,14 +418,13 @@ mongoc_b64_pton_do (char const *src, uin
 static int
 mongoc_b64_pton_len (char const *src)
 {
-   int tarindex, state;
-   uint8_t ch, ofs;
-
-   state = 0;
-   tarindex = 0;
+   uint8_t ch = 0;
+   uint8_t ofs = 0;
+   int state = 0;
+   int tarindex = 0;
 
    while (1) {
-      ch = *src++;
+      ch = (uint8_t) *src++;
       ofs = mongoc_b64rmap[ch];
 
       if (ofs >= mongoc_b64rmap_special) {
@@ -469,8 +464,8 @@ mongoc_b64_pton_len (char const *src)
     * on a byte boundary, and/or with erroneous trailing characters.
     */
 
-   if (ch == Pad64) { /* We got a pad char. */
-      ch = *src++;    /* Skip it, get next. */
+   if (ch == Pad64) {        /* We got a pad char. */
+      ch = (uint8_t) *src++; /* Skip it, get next. */
       switch (state) {
       case 0: /* Invalid = in first position */
       case 1: /* Invalid = in second position */
@@ -478,13 +473,13 @@ mongoc_b64_pton_len (char const *src)
 
       case 2: /* Valid, means one byte of info */
          /* Skip any number of spaces. */
-         for ((void) NULL; ch != '\0'; ch = *src++)
+         for ((void) NULL; ch != '\0'; ch = (uint8_t) *src++)
             if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
                break;
          /* Make sure there is another trailing = sign. */
          if (ch != Pad64)
             return (-1);
-         ch = *src++; /* Skip the = */
+         ch = (uint8_t) *src++; /* Skip the = */
          /* Fall through to "single trailing =" case. */
          /* FALLTHROUGH */
 
@@ -493,7 +488,7 @@ mongoc_b64_pton_len (char const *src)
           * We know this char is an =.  Is there anything but
           * whitespace after it?
           */
-         for ((void) NULL; ch != '\0'; ch = *src++)
+         for (; ch != '\0'; ch = (uint8_t) *src++)
             if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
                return (-1);
 
diff -pruN 1.30.4-1/src/common/src/common-bson-dsl-private.h 2.0.2-1/src/common/src/common-bson-dsl-private.h
--- 1.30.4-1/src/common/src/common-bson-dsl-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-bson-dsl-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -14,7 +14,7 @@
  */
 
 #include <bson/bson.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 enum {
    /// Toggle this value to enable/disable debug output for all bsonDSL
@@ -119,7 +119,7 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnost
    _bsonDSL_begin ("\"%s\" => [%s]", String, _bsonDSL_strElide (30, Element)); \
    const char *_bbString = (String);                                           \
    const uint64_t length = (Len);                                              \
-   if (mcommon_in_range_unsigned (int, length)) {                              \
+   if (mlib_in_range (int, length)) {                                          \
       _bbCtx.key = _bbString;                                                  \
       _bbCtx.key_len = (int) length;                                           \
       _bsonValueOperation (Element);                                           \
@@ -741,8 +741,8 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnost
 
 #define _bsonPredicate_Condition_1 1
 #define _bsonPredicate_Condition_0 0
-#define _bsonPredicate_Condition_true true
-#define _bsonPredicate_Condition_false false
+#define _bsonPredicate_Condition_always true
+#define _bsonPredicate_Condition_never false
 
 #define _bsonPredicate_Condition_isTrue (bson_iter_as_bool (&bsonVisitIter))
 #define _bsonPredicate_Condition_isFalse (!bson_iter_as_bool (&bsonVisitIter))
diff -pruN 1.30.4-1/src/common/src/common-cmp-private.h 2.0.2-1/src/common/src/common-cmp-private.h
--- 1.30.4-1/src/common/src/common-cmp-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-cmp-private.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,174 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <common-prelude.h>
-
-#ifndef MONGO_C_DRIVER_COMMON_CMP_PRIVATE_H
-#define MONGO_C_DRIVER_COMMON_CMP_PRIVATE_H
-
-
-#include <bson/bson.h> /* ssize_t, BSON_CONCAT */
-
-#include <limits.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-
-BSON_BEGIN_DECLS
-
-
-/* Based on the "Safe Integral Comparisons" proposal merged in C++20:
- * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0586r2.html
- *
- * Due to lack of type deduction in C, relational comparison functions (e.g.
- * `cmp_less`) are defined in sets of four "functions" according to the
- * signedness of each value argument, e.g.:
- *  - mcommon_cmp_less_ss (signed-value, signed-value)
- *  - mcommon_cmp_less_uu (unsigned-value, unsigned-value)
- *  - mcommon_cmp_less_su (signed-value, unsigned-value)
- *  - mcommon_cmp_less_us (unsigned-value, signed-value)
- *
- * Similarly, the `in_range` function is defined as a set of two "functions"
- * according to the signedness of the value argument:
- *  - mcommon_in_range_signed (Type, signed-value)
- *  - mcommon_in_range_unsigned (Type, unsigned-value)
- *
- * The user must take care to use the correct signedness for the provided
- * argument(s). Enabling compiler warnings for implicit sign conversions is
- * recommended.
- */
-
-
-#define MCOMMON_CMP_SET(op, ss, uu, su, us)                                              \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_cmp_, op, _ss) (int64_t t, int64_t u)   \
-   {                                                                                     \
-      return (ss);                                                                       \
-   }                                                                                     \
-                                                                                         \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_cmp_, op, _uu) (uint64_t t, uint64_t u) \
-   {                                                                                     \
-      return (uu);                                                                       \
-   }                                                                                     \
-                                                                                         \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_cmp_, op, _su) (int64_t t, uint64_t u)  \
-   {                                                                                     \
-      return (su);                                                                       \
-   }                                                                                     \
-                                                                                         \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_cmp_, op, _us) (uint64_t t, int64_t u)  \
-   {                                                                                     \
-      return (us);                                                                       \
-   }
-
-MCOMMON_CMP_SET (equal, t == u, t == u, t < 0 ? false : (uint64_t) (t) == u, u < 0 ? false : t == (uint64_t) (u))
-
-MCOMMON_CMP_SET (not_equal,
-                 !mcommon_cmp_equal_ss (t, u),
-                 !mcommon_cmp_equal_uu (t, u),
-                 !mcommon_cmp_equal_su (t, u),
-                 !mcommon_cmp_equal_us (t, u))
-
-MCOMMON_CMP_SET (less, t < u, t < u, t < 0 ? true : (uint64_t) (t) < u, u < 0 ? false : t < (uint64_t) (u))
-
-MCOMMON_CMP_SET (greater,
-                 mcommon_cmp_less_ss (u, t),
-                 mcommon_cmp_less_uu (u, t),
-                 mcommon_cmp_less_us (u, t),
-                 mcommon_cmp_less_su (u, t))
-
-MCOMMON_CMP_SET (less_equal,
-                 !mcommon_cmp_greater_ss (t, u),
-                 !mcommon_cmp_greater_uu (t, u),
-                 !mcommon_cmp_greater_su (t, u),
-                 !mcommon_cmp_greater_us (t, u))
-
-MCOMMON_CMP_SET (greater_equal,
-                 !mcommon_cmp_less_ss (t, u),
-                 !mcommon_cmp_less_uu (t, u),
-                 !mcommon_cmp_less_su (t, u),
-                 !mcommon_cmp_less_us (t, u))
-
-#undef MCOMMON_CMP_SET
-
-
-/* Return true if the given value is within the range of the corresponding
- * signed type. The suffix must match the signedness of the given value. */
-#define MCOMMON_IN_RANGE_SET_SIGNED(Type, min, max)                                               \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_in_range, _##Type, _signed) (int64_t value)      \
-   {                                                                                              \
-      return mcommon_cmp_greater_equal_ss (value, min) && mcommon_cmp_less_equal_ss (value, max); \
-   }                                                                                              \
-                                                                                                  \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_in_range, _##Type, _unsigned) (uint64_t value)   \
-   {                                                                                              \
-      return mcommon_cmp_greater_equal_us (value, min) && mcommon_cmp_less_equal_us (value, max); \
-   }
-
-/* Return true if the given value is within the range of the corresponding
- * unsigned type. The suffix must match the signedness of the given value. */
-#define MCOMMON_IN_RANGE_SET_UNSIGNED(Type, max)                                                 \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_in_range, _##Type, _signed) (int64_t value)     \
-   {                                                                                             \
-      return mcommon_cmp_greater_equal_su (value, 0u) && mcommon_cmp_less_equal_su (value, max); \
-   }                                                                                             \
-                                                                                                 \
-   static BSON_INLINE bool BSON_CONCAT3 (mcommon_in_range, _##Type, _unsigned) (uint64_t value)  \
-   {                                                                                             \
-      return mcommon_cmp_less_equal_uu (value, max);                                             \
-   }
-
-MCOMMON_IN_RANGE_SET_SIGNED (signed_char, SCHAR_MIN, SCHAR_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (short, SHRT_MIN, SHRT_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (int, INT_MIN, INT_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (long, LONG_MIN, LONG_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (long_long, LLONG_MIN, LLONG_MAX)
-
-MCOMMON_IN_RANGE_SET_UNSIGNED (unsigned_char, UCHAR_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (unsigned_short, USHRT_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (unsigned_int, UINT_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (unsigned_long, ULONG_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (unsigned_long_long, ULLONG_MAX)
-
-MCOMMON_IN_RANGE_SET_SIGNED (int8_t, INT8_MIN, INT8_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (int16_t, INT16_MIN, INT16_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (int32_t, INT32_MIN, INT32_MAX)
-MCOMMON_IN_RANGE_SET_SIGNED (int64_t, INT64_MIN, INT64_MAX)
-
-MCOMMON_IN_RANGE_SET_UNSIGNED (uint8_t, UINT8_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (uint16_t, UINT16_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (uint32_t, UINT32_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (uint64_t, UINT64_MAX)
-
-MCOMMON_IN_RANGE_SET_SIGNED (ssize_t, SSIZE_MIN, SSIZE_MAX)
-MCOMMON_IN_RANGE_SET_UNSIGNED (size_t, SIZE_MAX)
-
-#undef MCOMMON_IN_RANGE_SET_SIGNED
-#undef MCOMMON_IN_RANGE_SET_UNSIGNED
-
-
-/* Return true if the value with *signed* type is in the representable range of
- * Type and false otherwise. */
-#define mcommon_in_range_signed(Type, value) BSON_CONCAT3 (mcommon_in_range, _##Type, _signed) (value)
-
-/* Return true if the value with *unsigned* type is in the representable range
- * of Type and false otherwise. */
-#define mcommon_in_range_unsigned(Type, value) BSON_CONCAT3 (mcommon_in_range, _##Type, _unsigned) (value)
-
-
-BSON_END_DECLS
-
-
-#endif /* MONGO_C_DRIVER_COMMON_CMP_PRIVATE_H */
diff -pruN 1.30.4-1/src/common/src/common-json.c 2.0.2-1/src/common/src/common-json.c
--- 1.30.4-1/src/common/src/common-json.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-json.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,6 @@
 #include <common-string-private.h>
 #include <common-utf8-private.h>
 #include <common-json-private.h>
-#include <common-cmp-private.h>
 
 
 typedef struct {
@@ -40,7 +39,7 @@ mcommon_json_append_visit_utf8 (
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_utf8_len)) {
+   if (!mlib_in_range (uint32_t, v_utf8_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -124,7 +123,7 @@ mcommon_json_append_visit_binary (const
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_binary_len)) {
+   if (!mlib_in_range (uint32_t, v_binary_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -158,7 +157,7 @@ mcommon_json_append_visit_regex (
    size_t v_options_len = strlen (v_options);
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_regex_len)) {
+   if (!mlib_in_range (uint32_t, v_regex_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -187,7 +186,7 @@ mcommon_json_append_visit_dbpointer (con
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_collection_len)) {
+   if (!mlib_in_range (uint32_t, v_collection_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -233,7 +232,7 @@ mcommon_json_append_visit_before (const
 
    if (state->has_keys) {
       size_t key_len = strlen (key);
-      if (!mcommon_in_range_unsigned (uint32_t, key_len)) {
+      if (!mlib_in_range (uint32_t, key_len)) {
          mcommon_string_append_overflow (state->append);
          return true;
       }
@@ -269,7 +268,7 @@ mcommon_json_append_visit_code (
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_code_len)) {
+   if (!mlib_in_range (uint32_t, v_code_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -283,7 +282,7 @@ mcommon_json_append_visit_symbol (
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_symbol_len)) {
+   if (!mlib_in_range (uint32_t, v_symbol_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
@@ -297,7 +296,7 @@ mcommon_json_append_visit_codewscope (
    mcommon_json_append_visit_t *state = data;
    BSON_UNUSED (iter);
    BSON_UNUSED (key);
-   if (!mcommon_in_range_unsigned (uint32_t, v_code_len)) {
+   if (!mlib_in_range (uint32_t, v_code_len)) {
       mcommon_string_append_overflow (state->append);
       return true;
    }
diff -pruN 1.30.4-1/src/common/src/common-md5-private.h 2.0.2-1/src/common/src/common-md5-private.h
--- 1.30.4-1/src/common/src/common-md5-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-md5-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -23,6 +23,12 @@
 
 BSON_BEGIN_DECLS
 
+typedef struct {
+   uint32_t count[2]; /* message length in bits, lsw first */
+   uint32_t abcd[4];  /* digest buffer */
+   uint8_t buf[64];   /* accumulate block */
+} bson_md5_t;
+
 #define mcommon_md5_init COMMON_NAME (md5_init)
 #define mcommon_md5_append COMMON_NAME (md5_append)
 #define mcommon_md5_finish COMMON_NAME (md5_finish)
diff -pruN 1.30.4-1/src/common/src/common-md5.c 2.0.2-1/src/common/src/common-md5.c
--- 1.30.4-1/src/common/src/common-md5.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-md5.c	2025-06-19 15:42:22.000000000 +0000
@@ -338,8 +338,8 @@ void
 mcommon_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes)
 {
    const uint8_t *p = data;
-   int left = nbytes;
-   int offset = (pms->count[0] >> 3) & 63;
+   uint32_t left = nbytes;
+   uint8_t offset = (pms->count[0] >> 3) & 63;
    uint32_t nbits = (uint32_t) (nbytes << 3);
 
    if (nbytes <= 0)
@@ -353,7 +353,7 @@ mcommon_md5_append (bson_md5_t *pms, con
 
    /* Process an initial partial block. */
    if (offset) {
-      int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+      uint32_t copy = (offset + nbytes > 64u ? 64u - offset : nbytes);
 
       memcpy (pms->buf + offset, p, copy);
       if (offset + copy < 64)
diff -pruN 1.30.4-1/src/common/src/common-string-private.h 2.0.2-1/src/common/src/common-string-private.h
--- 1.30.4-1/src/common/src/common-string-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-string-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -20,13 +20,11 @@
 #define MONGO_C_DRIVER_COMMON_STRING_PRIVATE_H
 
 #include <bson/bson.h>
+#include <mlib/cmp.h>
 #include <string.h>
-#include <common-cmp-private.h>
 
 
-/* Until the deprecated bson_string_t is removed, this must have the same members in the same order, so we can safely
- * cast between the two types. Afterward, we are free to modify the memory layout as needed.
- *
+/*
  * In mcommon_string_t, 'str' is guaranteed to be NUL terminated and SHOULD be valid UTF-8. mcommon_string_t operations
  * MUST maintain the validity of valid UTF-8 strings.
  *
@@ -111,7 +109,7 @@ mcommon_string_new (const char *str)
 {
    BSON_ASSERT_PARAM (str);
    size_t length = strlen (str);
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, length) && (uint32_t) length < UINT32_MAX);
+   BSON_ASSERT (mlib_in_range (uint32_t, length) && (uint32_t) length < UINT32_MAX);
    return mcommon_string_new_with_capacity (str, (uint32_t) length, 0);
 }
 
@@ -181,7 +179,7 @@ mcommon_string_starts_with_str (const mc
    size_t substring_len = strlen (substring);
    uint32_t string_len = string->len;
 
-   if (mcommon_in_range_unsigned (uint32_t, substring_len) && (uint32_t) substring_len <= string_len) {
+   if (mlib_in_range (uint32_t, substring_len) && (uint32_t) substring_len <= string_len) {
       return 0 == memcmp (string->str, substring, substring_len);
    } else {
       return false;
@@ -202,7 +200,7 @@ mcommon_string_ends_with_str (const mcom
    size_t substring_len = strlen (substring);
    uint32_t string_len = string->len;
 
-   if (mcommon_in_range_unsigned (uint32_t, substring_len) && (uint32_t) substring_len <= string_len) {
+   if (mlib_in_range (uint32_t, substring_len) && (uint32_t) substring_len <= string_len) {
       uint32_t offset = string_len - (uint32_t) substring_len;
       return 0 == memcmp (string->str + offset, substring, substring_len);
    } else {
diff -pruN 1.30.4-1/src/common/src/common-string.c 2.0.2-1/src/common/src/common-string.c
--- 1.30.4-1/src/common/src/common-string.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/src/common-string.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,7 +18,7 @@
 #include <common-bits-private.h>
 #include <common-utf8-private.h>
 #include <common-b64-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 mcommon_string_t *
@@ -200,9 +200,9 @@ mcommon_string_append_base64_encode (mco
    if (encoded_target_len <= (size_t) max_append_len) {
       // No truncation needed. Grow the buffer and encode directly.
       mcommon_string_grow_to_capacity (string, old_len + encoded_target_len);
-      BSON_ASSERT (encoded_target_len ==
-                   mcommon_b64_ntop (bytes, (size_t) len, string->str + old_len, encoded_target_len + 1));
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, encoded_target_len));
+      const int tgt = mcommon_b64_ntop (bytes, (size_t) len, string->str + old_len, encoded_target_len + 1);
+      BSON_ASSERT (mlib_cmp (encoded_target_len, ==, tgt));
+      BSON_ASSERT (mlib_in_range (uint32_t, encoded_target_len));
       string->len = old_len + (uint32_t) encoded_target_len;
       return true;
    } else if (max_append_len == 0) {
@@ -227,18 +227,18 @@ mcommon_string_append_base64_encode (mco
       uint32_t direct_input_len = mcommon_b64_pton_calculate_target_size ((size_t) direct_encoded_len);
       BSON_ASSERT (direct_input_len % 3 == 0);
       BSON_ASSERT (direct_input_len < len);
-      BSON_ASSERT (direct_encoded_len ==
-                   mcommon_b64_ntop (bytes, (size_t) direct_input_len, string->str + old_len, direct_encoded_len + 1));
+      const int tgt =
+         mcommon_b64_ntop (bytes, (size_t) direct_input_len, string->str + old_len, direct_encoded_len + 1);
+      BSON_ASSERT (mlib_cmp (direct_encoded_len, ==, tgt));
 
       char remainder_buffer[5];
       uint32_t remainder_input_len = BSON_MIN (3, len - direct_input_len);
       BSON_ASSERT (remainder_input_len > 0);
       uint32_t remainder_encoded_len = mcommon_b64_ntop_calculate_target_size ((size_t) remainder_input_len) - 1;
       BSON_ASSERT (remainder_encoded_len > remainder_truncated_len);
-      BSON_ASSERT (remainder_encoded_len == mcommon_b64_ntop (bytes + direct_input_len,
-                                                              (size_t) remainder_input_len,
-                                                              remainder_buffer,
-                                                              sizeof remainder_buffer));
+      const int t2 = mcommon_b64_ntop (
+         bytes + direct_input_len, (size_t) remainder_input_len, remainder_buffer, sizeof remainder_buffer);
+      BSON_ASSERT (mlib_cmp (remainder_encoded_len, ==, t2));
       memcpy (buffer + old_len + direct_encoded_len, remainder_buffer, remainder_encoded_len);
 
       BSON_ASSERT (old_len + direct_encoded_len + remainder_truncated_len == max_len);
@@ -262,15 +262,15 @@ mcommon_string_append_oid_as_hex (mcommo
 
 bool
 mcommon_string_append_selected_chars (mcommon_string_append_t *append,
-                                      const char *template,
+                                      const char *tmplt,
                                       const char *selector,
                                       size_t selector_len)
 {
    BSON_ASSERT_PARAM (append);
-   BSON_ASSERT_PARAM (template);
+   BSON_ASSERT_PARAM (tmplt);
    BSON_ASSERT_PARAM (selector);
 
-   for (uint8_t template_char; (template_char = (uint8_t) * template); template ++) {
+   for (uint8_t template_char; (template_char = (uint8_t) *tmplt); tmplt++) {
       BSON_ASSERT (template_char <= 0x7f);
       if (memchr (selector, template_char, selector_len) && !mcommon_string_append_unichar (append, template_char)) {
          return false;
@@ -331,7 +331,7 @@ mcommon_string_append_vprintf (mcommon_s
       int format_result = bson_vsnprintf (format_buffer, format_buffer_alloc, format, args_copy);
       va_end (args_copy);
 
-      if (format_result > -1 && mcommon_in_range_signed (uint32_t, format_result) &&
+      if (format_result > -1 && mlib_in_range (uint32_t, format_result) &&
           (uint32_t) format_result <= actual_format_buffer_capacity) {
          // Successful result, no truncation.
          format_buffer[format_result] = '\0';
@@ -344,8 +344,7 @@ mcommon_string_append_vprintf (mcommon_s
       if (actual_format_buffer_capacity == max_append_len) {
          // No more space to grow into, this must be the final result.
 
-         if (format_result > -1 && mcommon_in_range_signed (uint32_t, format_result) &&
-             (uint32_t) format_result < UINT32_MAX) {
+         if (format_result > -1 && mlib_in_range (uint32_t, format_result) && (uint32_t) format_result < UINT32_MAX) {
             // We have truncated output from vsnprintf. Clean it up by removing
             // any partial UTF-8 sequences that might be left on the end.
             uint32_t truncated_append_len = mcommon_utf8_truncate_len (
@@ -362,8 +361,7 @@ mcommon_string_append_vprintf (mcommon_s
       }
 
       // Choose a larger format_buffer_len and try again. Length will be clamped to max_append_len above.
-      if (format_result > -1 && mcommon_in_range_signed (uint32_t, format_result) &&
-          (uint32_t) format_result < UINT32_MAX) {
+      if (format_result > -1 && mlib_in_range (uint32_t, format_result) && (uint32_t) format_result < UINT32_MAX) {
          min_format_buffer_capacity = (uint32_t) format_result + 1u;
       } else if (min_format_buffer_capacity < UINT32_MAX / 2) {
          min_format_buffer_capacity *= 2;
diff -pruN 1.30.4-1/src/common/src/mlib/ckdint.h 2.0.2-1/src/common/src/mlib/ckdint.h
--- 1.30.4-1/src/common/src/mlib/ckdint.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/ckdint.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,679 @@
+/**
+ * @file mlib/ckdint.h
+ * @brief Checked integer arithmetic
+ * @date 2025-02-04
+ *
+ * This file implements the C23 checked-integer-arithmetic functions as macros.
+ *
+ * The implementation is nearly perfect: The macros necessarily evaluate the
+ * operand expressions more than once, so callers should be aware of this caveat.
+ *
+ * The function-like macros are defined:
+ *
+ * - `mlib_add(Dst, L, R)` / `mlib_add(Dst, A)`
+ * - `mlib_sub(Dst, L, R)` / `mlib_sub(Dst, A)`
+ * - `mlib_mul(Dst, L, R)` / `mlib_mul(Dst, A)`
+ * - `mlib_narrow(Dst, V)` (not from stdckdint, but defined as `mlib_add(Dst, V, 0)`)
+ *
+ * Where `Dst` is a pointer to integral storage, and `L` and `R` are arbitrary
+ * integral expressions. The two-argument variants treat `Dst` as the the left-hand
+ * operand for in-place arithmetic.
+ *
+ * Each macro accepts arguments of arbitrary type at any position, and will "do
+ * the right thing", regardless of the parameter types. No funny integer promotion,
+ * sign extension, sign conversion, nor implicit narrowing. The macros return `false`
+ * if-and-only-if the result was lossless. They return `true` if-and-only-if the
+ * value written to `Dst` does not represent the true arithmetic result.
+ *
+ * The following additional macros are defined:
+ *
+ * - `mlib_assert_add(T, L, R)`
+ * - `mlib_assert_sub(T, L, R)`
+ * - `mlib_assert_mul(T, L, R)`
+ *
+ * Where `T` is an integer type. The macro will yield a value of that type, asserting
+ * that the operation on `L` and `R` does not overflow. If the operation overflows,
+ * the program will be terminated with a diagnostic to `stderr` pointing to the call site.
+ *
+ * For implementation details and a usage guide, see `ckdint.md`
+ *
+ * @copyright Copyright (c) 2025
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <mlib/config.h>
+#include <mlib/intutil.h>
+#include <mlib/test.h>
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+mlib_extern_c_begin ();
+
+/**
+ * @brief Perform integer addition
+ *
+ * @param Out A non-null pointer to a modifiable integer.
+ * @param A The left-hand addend of addition
+ * @param B The right-hand addend of addition
+ * @retval `true` if the value written to `Out` does not represent the true arithmetic sum.
+ * @retval `false` Otherwise.
+ *
+ * The sum `A + B` is written to `Out`. The operation is commutative.
+ *
+ * If the argument `B` is omitted, computes `*Out + A` (performs in-place addition).
+ */
+#define mlib_add(...) MLIB_ARGC_PICK (_mlib_ckdint, mlib_add, __VA_ARGS__)
+/**
+ * @brief Perform integer subtraction
+ *
+ * @param Out A non-null pointer to a modifiable integer.
+ * @param A The left-hand operand of the subtraction (minuend)
+ * @param B The right-hand operand of subtraction (subtrahend)
+ * @retval `true` if the value written to `Out` does not represent the true arithmetic difference.
+ * @retval `false` Otherwise.
+ *
+ * The difference `A - B` will be written to `Out`.
+ *
+ * If the argument `B` is omitted, computes `*Out - A` (performs in-place subtraction)
+ */
+#define mlib_sub(...) MLIB_ARGC_PICK (_mlib_ckdint, mlib_sub, __VA_ARGS__)
+/**
+ * @brief Perform integer multiplication
+ *
+ * @param Out A non-null pointer to a modifiable integer.
+ * @param A The left-hand factor of multiplication
+ * @param B The right-hand factor of multiplication
+ * @retval `true` if the value written to `Out` does not represent the true arithmetic product.
+ * @retval `false` Otherwise.
+ *
+ * The product `A × B` will be written to `Out`. The operation is commutative.
+ *
+ * If the argument `B` is omitted, computes `Out × A` (performs in-place multiplication)
+ */
+#define mlib_mul(...) MLIB_ARGC_PICK (_mlib_ckdint, mlib_mul, __VA_ARGS__)
+/**
+ * @brief Perform narrowing assignment from one integer value to another.
+ *
+ * @param Out A non-null pointer to a modifiable integer.
+ * @param A The integer value to be narrowed.
+ * @retval `true` if the value written to `Out` is not equivalent to the value of `A`
+ * @retval `false` otherwise
+ */
+#define mlib_narrow(O, A) mlib_add ((O), (A), 0)
+
+/**
+ * @brief Perform an asserting addition, yielding the result
+ *
+ * @param T The target type of the operation
+ * @param A The left-hand addend for the addition
+ * @param B The right-hand addend for the addition
+ * @return The sum `A + B` as type `T`
+ *
+ * If the true arithmetic sum is not representable in `T`, the program terminates.
+ */
+#define mlib_assert_add(T, A, B) \
+   _mlib_assert_ckdint (T, A, B, &mlib_add, "mlib_assert_add", #T, #A, #B, mlib_this_source_location ())
+/**
+ * @brief Perform an asserting subtraction, yielding the result
+ *
+ * @param T The target type of the operation
+ * @param A The left-hand minuend for the subtraction
+ * @param B The right-hand subtrahend for the subtraction
+ * @return The difference `A - B` as type `T`
+ *
+ * If the true arithmetic difference is not representable in `T`, the program terminates.
+ */
+#define mlib_assert_sub(T, A, B) \
+   _mlib_assert_ckdint (T, A, B, &mlib_sub, "mlib_assert_sub", #T, #A, #B, mlib_this_source_location ())
+/**
+ * @brief Perform an asserting multiplication, yielding the result
+ *
+ * @param T The target type of the operation
+ * @param A The left-hand factor for the multiplication
+ * @param B The right-hand factor for the multiplication
+ * @return The product `A × B` as type `T`
+ *
+ * If the true arithmetic product is not representable in `T`, the program terminates.
+ */
+#define mlib_assert_mul(T, A, B) \
+   _mlib_assert_ckdint (T, A, B, &mlib_mul, "mlib_assert_mul", #T, #A, #B, mlib_this_source_location ())
+
+/**
+ * @brief Perform a runtime-checked cast of an integral value to another type.
+ *
+ * @param T A type specifier for a target integral type for the cast.
+ * @param Operand The integral value to be converted.
+ *
+ * If the cast would result in the operand value chaning, the program will be
+ * terminated with a diagnostic.
+ */
+#define mlib_assert_narrow(T, Operand) \
+   (T) _mlib_checked_cast (            \
+      mlib_minof (T), mlib_maxof (T), mlib_upsize_integer (Operand), #T, #Operand, mlib_this_source_location ())
+
+#define _mlib_ckdint_argc_3(Fn, Out, Arg) _mlib_ckdint_argc_4 (Fn, Out, *(Out), Arg)
+#define _mlib_ckdint_argc_4(Fn, O, A, B)                                                                          \
+   _mlib_ckdint (O,                                                                                               \
+                 sizeof (*(O)),                                                                                   \
+                 _mlibClobberIsSigned (*(O), 0) ? (intmax_t) _mlibMinofSigned (*(O)) : _mlibMinofUnsigned (*(O)), \
+                 _mlibClobberIsSigned (*(O), 1) ? _mlibMaxofSigned (*(O)) : _mlibMaxofUnsigned (*(O)),            \
+                 mlib_upsize_integer (A),                                                                         \
+                 mlib_upsize_integer (B),                                                                         \
+                 &Fn)
+
+// Impl macro for the asserting checked arithmetic functions
+#define _mlib_assert_ckdint(T, A, B, Fn, F_str, T_str, A_str, B_str, Here) \
+   ((T) _mlib_assert_ckdint (sizeof (T),                                   \
+                             mlib_minof (T),                               \
+                             mlib_maxof (T),                               \
+                             mlib_upsize_integer (A),                      \
+                             mlib_upsize_integer (B),                      \
+                             Fn,                                           \
+                             F_str,                                        \
+                             T_str,                                        \
+                             A_str,                                        \
+                             B_str,                                        \
+                             Here))
+
+// clang-format off
+// Generates an 0b11111 bit pattern for appropriate size:
+#define _mlibMaxofUnsigned(V) \
+   (sizeof(V) == sizeof(uintmax_t) \
+      ? UINTMAX_MAX /* No funny bit math, just return the max of the max int */ \
+      /* Generate an 0b11111... bit pattern */ \
+      : (UINTMAX_C(1) << ( \
+         /* Guard against an over-shift if V is uintmax_t: */ \
+           (sizeof(V) < sizeof(uintmax_t)) \
+         * (sizeof(V) * CHAR_BIT)) \
+         ) - 1)
+
+// Generates an 0b01111 bit pattern for the two's complement max value:
+#define _mlibMaxofSigned(V) (_mlibMaxofUnsigned (V) >> 1ull)
+// Generates an 0b10000... bit pattern for the two's complement min value:
+#define _mlibMinofSigned(V) ((0 & (V)) - (UINTMAX_C (1) << ((sizeof (V) * CHAR_BIT) - 1)))
+// For completeness:
+#define _mlibMinofUnsigned(V) 0
+// Yields true iff the operand expression has a signed type, but requires that
+// the operand is a modifiable l-value. The `N` must be 0 or 1, arbitrarily (see below).
+#define _mlibClobberIsSigned(V, N) \
+   MLIB_IF_ELSE(mlib_have_typeof()) \
+      /* Prefer using typeof(), if we can. */ \
+      (mlib_is_signed(mlib_typeof(V))) \
+      /* Otherwise, do a dance: */ \
+      (( \
+         /* Save the value of V */ \
+         _mlibSignCheckTmp[N] = 0ull | (uintmax_t) (V), \
+         /* Set V to zero, and check whether decrementing results in a negative value */ \
+         (V) = 0, \
+         _mlibSignCheckResult[N] = (--(V) < 0), \
+         /* Restore the value of V (bit hacks to prevent conversion warnings) */ \
+         (V) = 0, \
+         (V) |= _mlibSignCheckTmp[N], \
+         /* Yield the sign-check result */ \
+         _mlibSignCheckResult[N] \
+      ))
+// Storage for `_mlibClobberIsSigned`. We use more than one storage space to prevent
+// unsequenced-operation warnings when we use `_mlibClobberIsSigned` multiple times
+// in a function argument list. GCC and Clang are able to easily elide these from
+// an optimized TU. MSVC has trouble, but is still able to constant-fold where it matters.
+static mlib_maybe_unused mlib_thread_local uintmax_t _mlibSignCheckTmp[2];
+static mlib_maybe_unused mlib_thread_local bool _mlibSignCheckResult[2];
+// clang-format on
+
+// Compile-time assert that the compiler's integer conversions obey two's complement encoding
+mlib_static_assert ((intmax_t) UINTMAX_MAX == -1 //
+                       && (intmax_t) (UINTMAX_MAX - 5) == -6,
+                    "This file requires two's complement signed integers");
+
+/**
+ * @brief Function signature for checked arithmetic support functions
+ *
+ * The function operates on max-precision integers of either sign, and should
+ * return true iff the arithmetic operation overflows for the given sign configuration.
+ *
+ * @param dst The output parameter for the operation. Never a null pointer.
+ * @param dst_signed Whether to treat the result as a signed integer
+ * @param a_signed Whether to treat the `a` operand as signed
+ * @param a The left-hand operand of the operation
+ * @param b_signed Whether to treat the `b` operand as signed
+ * @param b The right-hand operand of the operation
+ *
+ * @note This was original written to use `mlib_upscaled_integer` for `a/b/dst`, but
+ * this defeats MSVC's ability to inline an indirect call through a constant-folded function
+ * pointer with this signature. GCC and Clang handle this fine, but for MSVC performance
+ * the more verbose signature is used.
+ */
+typedef bool (*_mlib_ckdint_arith_fn) (
+   uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b);
+
+// Support function for the `mlib_add` macro
+static inline bool (mlib_add) (uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
+   mlib_noexcept
+{
+   // Perform regular wrapping arithmetic on the unsigned value. The bit pattern
+   // is equivalent if there is two's complement signed arithmetic.
+   const uintmax_t sum = *dst = a + b;
+   const uintmax_t signbit = (UINTMAX_C (1) << ((sizeof (intmax_t) * CHAR_BIT) - 1));
+   // Now we check whether that overflowed according to the sign configuration.
+   // We use some bit fiddling magic that treat the signbit as a boolean for
+   // "is this number negative?" or "is this number “large” (i.e. bigger than signed-max)?"
+   // The expanded verbose form of each bit-magic is written below the more esoteric cases
+   if (dst_signed) {
+      if (a_signed) {
+         if (b_signed) { // S = S + S
+            return signbit & (sum ^ a) & (sum ^ b);
+            // Expanded:
+            // Test whether the product sign is unequal to both input signs
+            // X ^ Y yields a negative value if the signs are unequal
+            const bool a_signflipped = (intmax_t) (sum ^ a) < 0;
+            const bool b_signflipped = (intmax_t) (sum ^ b) < 0;
+            return a_signflipped && b_signflipped;
+         } else { // S = S + U
+            // Flip the sign bit of a, test whether that sum overflows
+            a ^= signbit;
+            return a + b < a;
+         }
+      } else {
+         if (b_signed) { // S = U + S
+            // Flip the sign bit of `b`, test whether that sum overflows
+            b ^= signbit;
+            return a + b < b;
+         } else { // S = U + U
+            // The signed sum must not be less than the addend, and not negative
+            return sum < a || (signbit & sum);
+         }
+      }
+   } else {
+      if (a_signed) {
+         if (b_signed) { // U = S + S
+            return signbit & (((sum | a) & b) | ((sum & a) & ~b));
+            // Expanded:
+            const bool a_is_negative = (intmax_t) a < 0;
+            const bool b_is_negative = (intmax_t) b < 0;
+            const bool sum_is_large = sum > INTMAX_MAX;
+            if (b_is_negative) {
+               if (a_is_negative) {
+                  // The sum must be negative, and therefore cannot be stored in an unsigned
+                  return true;
+               } else if (sum_is_large) {
+                  // We added a negative value B to a positive value A, but the sum
+                  // ended up larger than the max signed value, so we wrapped
+                  return true;
+               }
+            } else if (a_is_negative) {
+               if (sum_is_large) {
+                  // Same as above case with sum_is_large
+                  return true;
+               }
+            }
+            return false;
+         } else { // U = S + U
+            return signbit & (sum ^ a ^ signbit) & (sum ^ b);
+            // Expanded:
+            const bool sum_is_large = sum > INTMAX_MAX;
+            const bool b_is_large = b > INTMAX_MAX;
+            const bool a_is_negative = (intmax_t) a < 0;
+
+            if (!a_is_negative && b_is_large) {
+               // We are adding a non-negative value to a large number, so the
+               // sum must also be large
+               if (!sum_is_large) {
+                  // We ended up with a smaller value, meaning that we must have wrapped
+                  return true;
+               }
+            }
+            if (a_is_negative && !b_is_large) {
+               // We subtracted a non-negative value from a non-large number, so
+               // the result should not be large
+               if (sum_is_large) {
+                  // We ended up with a large value, so we must have wrapped
+                  return true;
+               }
+            }
+            return false;
+         }
+      } else {
+         if (b_signed) { // U = U + S  --- (See [U = S + U] for an explanation)
+            return signbit & (sum ^ a) & (sum ^ b ^ signbit);
+         } else { // U = U + U (simple case)
+            return sum < a;
+         }
+      }
+   }
+}
+
+// Support for the `mlib_sub` macro
+static inline bool (mlib_sub) (uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
+   mlib_noexcept
+{
+   // Perform the subtraction using regular wrapping arithmetic
+   const uintmax_t diff = *dst = a - b;
+   const uintmax_t signbit = (UINTMAX_C (1) << ((sizeof (intmax_t) * CHAR_BIT) - 1));
+   // Test whether the operation overflowed for the given sign configuration
+   // (See mlib_add for more details on why we do this bit fiddling)
+   if (dst_signed) {
+      const bool diff_is_negative = signbit & diff;
+      if (a_signed) {
+         if (b_signed) { // S = S - S
+            return signbit & (a ^ b) & (diff ^ a);
+            // Explain:
+            const bool a_is_negative = (intmax_t) a < 0;
+            const bool b_is_negative = (intmax_t) b < 0;
+            if (a_is_negative != b_is_negative) {
+               // Given: Pos - Neg = Pos
+               //      ∧ Neg - Pos = Neg
+               // We expect that the difference preserves the sign of the minuend
+               if (diff_is_negative != a_is_negative) {
+                  return true;
+               }
+            }
+            // Otherwise, `Pos - Pos` and `Neg - Neg` cannot possibly overflow
+            return false;
+         } else { // S = S - U
+            // The diff overflows if the sign-bit-flipped minuend is smaller than the subtrahend
+            return (a ^ signbit) < b;
+         }
+      } else {
+         if (b_signed) { // S = U - S
+            // The diff overflows if the sign-bit-flipped subtrahend is greater than or equal to the minuend
+            return a >= (b ^ signbit);
+         } else { // S = U - U
+            const bool expect_negative = a < b;
+            return expect_negative != diff_is_negative;
+         }
+      }
+   } else {
+      if (a_signed) {
+         if (b_signed) { // U = S - S
+            return signbit & (((diff & a) & b) | ((diff | a) & ~b));
+            // Expanded:
+            const bool a_is_negative = (intmax_t) a < 0;
+            const bool b_is_negative = (intmax_t) b < 0;
+            const bool diff_is_large = diff > INTMAX_MAX;
+            if (!b_is_negative) {
+               if (a_is_negative) {
+                  // We subtracted a non-negative from a negative value, so the difference
+                  // must be negative and cannot be stored as unsigned
+                  return true;
+               }
+               if (diff_is_large) {
+                  // We subtracted a positive value from a signed value, so we must not
+                  // end up with a large value
+                  return true;
+               }
+            }
+            if (a_is_negative) {
+               if (diff_is_large) {
+                  // A is negative, and there is no possible value that we can subtract
+                  // from it to obtain this large integer, so we must have overflowed
+                  return true;
+               }
+            }
+            return false;
+         } else { //
+            return (b > a) || (signbit & a);
+         }
+      } else {
+         if (b_signed) { // U = U - S
+            return signbit & (a ^ b ^ signbit) & (diff ^ a);
+            // Explain:
+            const bool a_is_large = a > INTMAX_MAX;
+            const bool b_is_negative = (intmax_t) b < 0;
+            const bool diff_is_large = diff > INTMAX_MAX;
+            if (a_is_large && b_is_negative) {
+               // The difference between a large value and a negative
+               // value must also be a large value
+               if (!diff_is_large) {
+                  // We expected another large value to appear.
+                  return true;
+               }
+            }
+            if (!a_is_large && !b_is_negative) {
+               // The difference between a non-large positive value and a non-negative value
+               // must not be a large value
+               if (diff_is_large) {
+                  // We did not expect a large difference
+                  return true;
+               }
+            }
+            return false;
+         } else {
+            return a < b;
+         }
+      }
+   }
+}
+
+// Support for the `mlib_mul` macro
+static inline bool (mlib_mul) (uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
+   mlib_noexcept
+{
+   // Multiplication is a lot more subtle
+   const uintmax_t signbit = (UINTMAX_C (1) << ((sizeof (intmax_t) * CHAR_BIT) - 1));
+   if (dst_signed) {
+      if (a_signed) {
+         if (b_signed) {
+            // S = S × S
+            *dst = a * b;
+            if (((intmax_t) b == -1 && (intmax_t) a == INTMAX_MIN) ||
+                ((intmax_t) a == -1 && (intmax_t) b == INTMAX_MIN)) {
+               // MIN × -1 is undefined
+               return true;
+            }
+            if (a && (intmax_t) *dst / (intmax_t) a != (intmax_t) b) {
+               // Mult did not preserve the arithmetic identity
+               return true;
+            }
+            return false;
+         } else {
+            // S = S × U
+            *dst = a * b;
+            const bool a_is_negative = signbit & a;
+            const uintmax_t positive_a = a_is_negative ? (0 - a) : a;
+            const uintmax_t positive_prod = positive_a * b;
+            const bool did_overflow = positive_a && positive_prod / positive_a != b;
+            if (did_overflow) {
+               return true;
+            }
+            if (positive_prod > (uintmax_t) INTMAX_MAX + (unsigned) a_is_negative) {
+               return true;
+            }
+            return false;
+         }
+      } else {
+         if (b_signed) {
+            // S = U × S
+            // Swap args: [S = S × U]
+            return (mlib_mul) (dst, dst_signed, b_signed, b, a_signed, a);
+         } else {
+            // S = U × U
+            *dst = a * b;
+            const bool did_overflow = a && *dst / a != b;
+            if (did_overflow) {
+               return true;
+            }
+            if (signbit & *dst) {
+               // A negative product indicates wrapping
+               return true;
+            }
+            return false;
+         }
+      }
+   } else {
+      if (a_signed) {
+         if (b_signed) {
+            // U = S × S
+            // Is either operand the min?
+            bool either_min = false;
+            if (signbit & a & b) {
+               // Both negative: Flip the signs
+               a = 0 - a;
+               b = 0 - b;
+               // MIN is pathological: 0 - MIN = MIN, so we need to check that:
+               either_min = (intmax_t) a == INTMAX_MIN || (intmax_t) b == INTMAX_MIN;
+            }
+            // Check if the product would be a negative number
+            const bool neg_prod = (signbit & (a ^ b)) && a && b && !either_min;
+            *dst = a * b;
+            return neg_prod || (a && *dst / a != b);
+         } else {
+            // U = S × U
+            *dst = a * b;
+            const bool did_ovr = a && *dst / a != b;
+            const bool a_is_negative = signbit & a;
+            if (did_ovr || (a_is_negative && b)) {
+               return true;
+            }
+            return false;
+         }
+      } else {
+         if (b_signed) {
+            // U = U × S
+            // Swap to [U = S × U]
+            return (mlib_mul) (dst, dst_signed, b_signed, b, a_signed, a);
+         } else {
+            // U = U × U: Simple:
+            *dst = a * b;
+            return a && *dst / a != b;
+         }
+      }
+   }
+}
+
+/**
+ * @private
+ * @brief This function performs the narrowing checks around a ckdint funciton
+ *
+ * @param dst Pointer to the target interger
+ * @param dst_sz The size of the target integer, in bytes
+ * @param minval The minimum value for the result. If negative, the target is treated as signed
+ * @param maxval The maximum value for the result
+ * @param a The left-hand operand for the operation
+ * @param b The right-hand operand for the operation
+ * @param fn The arithmetic function that performs arithmetic on the max-precision integer
+ * @return true If the resulting value DOES NOT equal the true arithmetic result
+ * @return false If the resulting value represents the true arithmetic results
+ */
+static inline bool
+_mlib_ckdint (void *dst,
+              int dst_sz,
+              intmax_t minval,
+              uintmax_t maxval,
+              struct mlib_upsized_integer a,
+              struct mlib_upsized_integer b,
+              _mlib_ckdint_arith_fn fn) mlib_noexcept
+{
+   // Perform the arithmetic on uintmax_t, for wrapping behavior
+   uintmax_t tmp;
+   bool ovr = fn (&tmp, minval < 0, a.is_signed, a.i.u, b.is_signed, b.i.u);
+   // Endian-adjusting for writing the result
+   const char *copy_from = (const char *) &tmp;
+   if (!mlib_is_little_endian ()) {
+      // We need to adjust the copy src in order to truncate the integer for big-endian encoding.
+      // Number of high bytes that we need to drop:
+      const int n_drop = (int) sizeof (tmp) - dst_sz;
+      // Adjust the copy pointer to so that we copy from the most significant byte that
+      // we wish to keep
+      copy_from += n_drop;
+   } else {
+      // For little-endian native, we don't need to adjust the bytes, since we can just
+      // truncate using the memcpy()
+   }
+   // Send the result to the destination
+   memcpy (dst, copy_from, (size_t) dst_sz);
+   // Final range check:
+   if (minval < 0) {
+      // Treat the target as signed:
+      intmax_t idst = (intmax_t) tmp;
+      return ovr || idst < minval || (idst > 0 && (uintmax_t) idst > maxval);
+   } else {
+      return ovr || tmp > maxval;
+   }
+}
+
+/**
+ * @internal
+ * @brief Implementation function for the asserting arithmetic functions
+ */
+static inline uintmax_t (_mlib_assert_ckdint) (size_t dst_sz,
+                                               intmax_t minval,
+                                               uintmax_t maxval,
+                                               struct mlib_upsized_integer a,
+                                               struct mlib_upsized_integer b,
+                                               _mlib_ckdint_arith_fn arith,
+                                               const char *fn_str,
+                                               const char *type_str,
+                                               const char *a_str,
+                                               const char *b_str,
+                                               struct mlib_source_location here) mlib_noexcept
+{
+   uintmax_t tmp;
+   bool did_overflow = _mlib_ckdint (&tmp, dst_sz, minval, maxval, a, b, arith);
+   if (did_overflow) {
+      fprintf (stderr,
+               "%s:%d: [in %s]: Call of %s(%s, %s, %s) resulted in arithmetic overflow\n",
+               here.file,
+               here.lineno,
+               here.func,
+               fn_str,
+               type_str,
+               a_str,
+               b_str);
+      abort ();
+   }
+   return tmp;
+}
+
+static inline uintmax_t
+_mlib_checked_cast (intmax_t min_,
+                    uintmax_t max_,
+                    struct mlib_upsized_integer val,
+                    const char *typename_,
+                    const char *expr,
+                    struct mlib_source_location here) mlib_noexcept
+{
+   if (!(mlib_in_range) (min_, max_, val)) {
+      if (val.is_signed) {
+         fprintf (stderr,
+                  "%s:%d: in [%s]: Checked integer cast of “%s” (value = %lld) to “%s” loses information\n",
+                  here.file,
+                  here.lineno,
+                  here.func,
+                  expr,
+                  (long long) val.i.s,
+                  typename_);
+      } else {
+         fprintf (stderr,
+                  "%s:%d: in [%s]: Checked integer cast of “%s” (value = %llu) to “%s” loses information\n",
+                  here.file,
+                  here.lineno,
+                  here.func,
+                  expr,
+                  (unsigned long long) val.i.u,
+                  typename_);
+      }
+      fflush (stderr);
+      abort ();
+   }
+   if (val.is_signed) {
+      return (uintmax_t) val.i.s;
+   }
+   return val.i.u;
+}
+
+mlib_extern_c_end ();
diff -pruN 1.30.4-1/src/common/src/mlib/ckdint.md 2.0.2-1/src/common/src/mlib/ckdint.md
--- 1.30.4-1/src/common/src/mlib/ckdint.md	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/ckdint.md	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,283 @@
+# `mlib/ckdint.h` C23 `stdckdint.h` for C99
+
+The `mlib/ckdint.h` header implements the [C23 checked arithmetic][stdckdint]
+functionality in a C99-compatible manner. There are only three caveats to keep
+in mind:
+
+[stdckdint]: https://en.cppreference.com/w/c/numeric#Checked_integer_arithmetic
+
+- The backport relies assumes two's complement signed integer encoding.
+- The operand expressions of a call to the ckdint function-like macros may be
+  evaluated more than once.
+- The output parameter is read-from before the operation begins, meaning that it
+  must be initialized to some value to prevent an uninitialized-read from being
+  seen by the compiler. (The value isn't used, and the compiler will easily
+  elide the dead store/read.)
+
+Implementing this correctly, especially without the aide of `_Generic`, requires
+quite a few tricks, but the results are correct (tested against GCC's
+`__builtin_<op>_overflow` intrinsic, which is how `glibc` implements C23
+[stdckdint][]).
+
+
+# How to Use
+
+The following function-like macros are defined:
+
+- Regular: `mlib_add`, `mlib_sub`, and `mlib_mul`, with an additional
+  `mlib_narrow` macro.
+- Asserting: `mlib_assert_add`, `mlib_assert_sub`, `mlib_assert_mul`, and
+  `mlib_assert_narrow`
+
+
+## Regular Macros
+
+The "regular" macros have the same API as [stdckdint][], with an additional
+feature: If called with two arguments, the output parameter is used as the
+left-hand operand of the operation:
+
+```c
+int foo = 42;
+mlib_add(&foo, n);  // Equivalent to `foo += n`
+```
+
+`mlib_narrow(Dst, I)` is not from [stdckdint][], but is useful to check that an
+integral cast operation does not modify the value:
+
+```c
+void foo(size_t N) {
+  int a = 0;
+  if (mlib_narrow(&a, N)) {
+    fprintf(stderr, "Invalid operand: N is too large\n");
+    abort();
+  }
+  // …
+}
+```
+
+All of the "regular" macros return a boolean. If they return `true`, then the
+result written to the destination DOES NOT represent the true arithmetic result
+(i.e. the operation overflowed or narrowed). If it returns `false`, then the
+operation succeeded without issue.
+
+This allows one to chain arithmetic operations together with the logical-or
+operator, short-circuiting when the operation fails:
+
+```c
+ssize_t grow_size(size_t sz, size_t elem_size, size_t count) {
+  ssize_t ret = 0;
+  // Compute: ret = sz + (elem_size × count)
+  if (mlib_mul(&elem_size, count) ||   // elem_size *= count
+      mlib_add(&ret, sz, elem_size)) { // ret = sz + elem_size
+    // Overflow. Indicate an error.
+    return SSIZE_MIN;
+  }
+  return ret;
+}
+```
+
+
+## Asserting Macros
+
+The `mlib_assert_…` macros take a type as their first argument instead of a
+destination pointer. The macro yields the result of the operation as a value of
+the specified type, asserting at runtime that no overflow or narrowing occurs.
+If the operation results in information loss, the program terminates at the call
+site.
+
+
+# How it Works
+
+This section details how it works, since it isn't straightforward from reading.
+
+
+## Max-Precision Arithmetic
+
+The basis of the checked arithmetic is to do the math in the maximum width
+unsigned integer type, which is well-defined. We can then treat the unsigned bit
+pattern as a signed or unsigned integer as appropriate to perform the arithmetic
+correctly and check for overflow. This arithmetic is implemented in the
+`mlib_add`, `mlib_sub`, and `mlib_mul` *functions* (not the macros). The bit
+fiddling tricks are a combination of straightforward arithmetic checks and more
+esoteric algorithms. The checks for addition and subtraction are fairly
+straightforward, while the multiplication implementation is substantially more
+complicated since its overflow semantics are much more pernicious.
+
+The bit hacks are described within each function. They are split between each
+combination of signed/unsigned treatment for the dest/left/right operands. The
+basis of the bit checks is in treating the high bit as a special boolean: For
+unsigned types, a set high bit represents a value outside the bounds of the
+signed equivalent. For signed types, a set high bit indicates a negative value
+that cannot be stored in an unsigned integer. Thus, logical-bit operations on
+integers and then comparing the result as less-than-zero effectively treats the
+high bit as a boolean, e.g.:
+
+- For signed X and Y, `(X ^ Y) < 0` yield `true` iff `X` and `Y` have different
+  sign.
+- `(X & Y) < 0` tests that both X and Y are negative.
+- `(X | Y) < 0` tests that either X or Y are negative.
+
+The very terse bit-manipulation expressions are difficult to parse at first, and
+have been expanded below each occurrence to explain what they are actually
+testing. The terse bit-manip tests are left as the main condition for overflow
+checking, as they generate significantly better machine code, even with the
+optimizer enabled.
+
+If the arithmetic overflows in the max precision integer, then we can assume
+that it overflows for any smaller integer types.
+
+For this integer promotion at macro sites, we use `mlib_upscale_integer`,
+defined in `mlib/intutil.h`.
+
+
+## Final Narrowing
+
+While it is simple enough to perform arithmetic in the max precision, we need
+to narrow the result to the target type, and that requires knowing the min/max
+bounds of that type. This was the most difficult challenge, because it requires
+the following:
+
+1. Given a pointer to an integer type $T$, what is the minimum value of $T$?
+2. ... what is the maximum value of $T$?
+3. How do we cast from a `uintmax_t` to $T$ through a generic `void*`?
+
+Point (3) is fairly simple: If we know the byte-size of $T$, we can bit-copy the
+integer representation from `uintmax_t` into the `void*`, preserving
+endian-encoding. For little-endian encoding, this is as simple as copying the first
+$N$ bytes from the `uintmax_t` into the target, truncating to the target size.
+For big-endian encoding, we just adjust a pointer into the object representation
+of the `uintmax_t` to drop the high bytes that we don't need.
+
+Points (1) and (2) are more subtle. We need a way to obtain a bit pattern that
+respects the "min" and "max" two's complement values. While one can easily form
+an aribtrary bit pattern using bit-shifts and `sizeof(*ptr)`, the trouble is
+that the min/max values depend on whether the target is signed, and it is *not
+possible* in C99 to ask whether an arbitrary integer expression is
+signed/unsigned.
+
+
+### Things that Don't Work™
+
+Given a type `T`, we can check whether it is signed with a simple macro:
+
+```c
+#define IS_SIGNED(T) ((T)-1 < 0)
+```
+
+Unfortunately, we don't have a type `T`. We have an expression `V`:
+
+```c
+#define IS_SIGNED_TYPEOF(V) ???
+```
+
+With C23 or GNU's `__typeof__`, we could do this easily (see below).
+
+There is one close call, that allows us to grab a zero and subtract one:
+
+```c
+#define IS_SIGNED_TYPEOF(V) ((0 & V) - 1 < 0)
+```
+
+This seems promising, but this **doesn't work**, because of C's awful,
+horrible, no-good, very-bad integer promotion rules. The expression `0 & V`
+*will* yield zero, but if `V` is smaller than `int`, it will be immediately
+promoted to `signed int` beforehand, regardless of the sign of `V`. This macro
+gives the correct answer for `(unsigned) int` and larger, but `(unsigned) short`
+and `(unsigned) char` will always yield `true`.
+
+
+### How `mlib/ckdint.h` Does It
+
+There is one set of C operators that *don't* perform integer promotion:
+assignment and in-place arithmetic. This macro *does* work:
+
+```c
+#define IS_SIGNED_TYPEOF(V) (((V) = -1) < 0)
+```
+
+But this obviously can't be used, because we're modifying the operand! Right...?
+
+Except: We're only needing to do this check on the *destination* of the
+arithmetic function. We already know that it's modifiable and that we're going
+to reassign to it, so it doesn't matter that we temporarily write a garbage `-1`
+into it!
+
+With this, we can write our needed support macros:
+
+```c
+#define MINOF_TYPEOF(V) \
+    IS_SIGNED_TYPEOF(V) \
+        ? MIN_TYPEOF_SIGNED(V) \
+        : MIN_TYPEOF_UNSIGNED(V)
+```
+
+With this, a call-site of our checked arithmetic macros can inject the
+appropriate min/max values of the destination operand, and the checked
+arithmetic functions can do the final bounds check.
+
+Almost
+
+
+### Big Problem, Though
+
+Suppose the following:
+
+```c
+int a = 42;
+mlib_add(&a, a, 5); // 42 + 5 ?
+```
+
+The correct result of `a` is `47`, but the value is unspecified: It is either
+`4` or `47`, depending on argument evaluation order, because we are silently
+overwriting the value in `a` to `-1` before doing the operation. We need to save
+the value of `a`, do the check, and then restore the value of `a`, all in a
+single go. Thus we have a much hairier macro:
+
+```c
+static thread_local uintmax_t P;
+static thread_local bool S;
+#define IS_SIGNED_TYPEOF(V) \
+  (( \
+    P = 0ull | (uintmax_t) V, \
+    V = 0, \
+    S = (--V < 0), \
+    V = 0, \
+    V |= P, \
+    S \
+  ))
+```
+
+This uses the comma-operator the enforce evaluation of each sub-expression:
+
+1. Save the bit pattern of `V` in a global static temporary $P$.
+2. Set `V` to zero.
+3. Decrement `V` and check if the result is negative. Save that value in a
+   separate global $S$.
+4. Restore the value of `V` by writing the bit pattern stored in $P$ back into
+   `V`. (The use of `= 0` + `|= P` prevents compilers from emitting any
+   integer conversion warnings)
+5. Yield the bool we saved in $S$.
+
+$P$ and $S$ are `thread_local` to allow multiple threads to evaluate the macro
+simultaneously without interfering. The `static` allows the optimizer to delete
+$P$ and $S$ from the translation unit when it can statically determine that the
+values written into these variables are never read from after constant folding
+(usually: MSVC is currently unable to elide the writes, but is still able to
+constant-fold across these assignments, which is the most important optimization
+we need to ensure works to eliminate redundant branches after inlining).
+
+With this modified roundabout definition, we can perform in-place checked
+arithmetic where the output can also be used as an input of the operation.
+
+
+### Optimize: Use `__typeof__`
+
+If we have `__typeof__` (available in GCC, Clang, and MSVC 19.39+) or C23
+`typeof` , we can simplify our macro to a trivial one:
+
+```c
+#define IS_SIGNED_TYPEOF(V) IS_SIGNED(__typeof__(V))
+```
+
+This will yield an equivalent result, but improves debug codegen and gives the
+optimizer an easier time doing constant folding across function calls.
diff -pruN 1.30.4-1/src/common/src/mlib/ckdint.test.cpp 2.0.2-1/src/common/src/mlib/ckdint.test.cpp
--- 1.30.4-1/src/common/src/mlib/ckdint.test.cpp	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/ckdint.test.cpp	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,177 @@
+#include <mlib/test.h>
+#include <mlib/ckdint.h>
+
+#include <cstdlib>
+#include <limits>
+#include <initializer_list>
+
+#define have_ckdint_builtins() 0
+// Check for the stdckdint builtins, but don't use Clang, as it has bugs on some platforms.
+#if defined(__has_builtin) && !defined(__clang__)
+#if __has_builtin(__builtin_add_overflow)
+#undef have_ckdint_builtins
+#define have_ckdint_builtins() 1
+#endif // __has_builtin
+#endif
+
+template <typename... Ts> struct typelist {
+};
+using integer_types = typelist<char,
+                               unsigned char,
+                               signed char,
+                               short,
+                               unsigned short,
+                               int,
+                               unsigned int,
+                               long,
+                               unsigned long,
+                               long long,
+                               unsigned long long>;
+
+/**
+ * @brief For every "interesting" value of integer type `T`, call `F`
+ *
+ * @tparam T An integer type to be inspected
+ * @param fn A function to be called with every "interesting value"
+ */
+template <typename T, typename F>
+void
+with_interesting_values (F &&fn)
+{
+   using lim = std::numeric_limits<T>;
+   // A list of the values of T that are potentially problematic
+   // when combined in various ways.
+   const T interesting_values[] = {
+      0,
+      (T) (-1),
+      (T) (-2),
+      (T) (-10),
+      1,
+      2,
+      10,
+      // Min value
+      lim::min (),
+      // Half min
+      (T) (lim::min () / 2),
+      (T) (lim::min () / 2 + 1),
+      (T) (lim::min () / 2 - 1),
+      // Max value
+      lim::max (),
+      // Half max
+      (T) (lim::max () / 2),
+      (T) (lim::max () / 2 + 1),
+      (T) (lim::max () / 2 - 1),
+   };
+   // Call with each value:
+   for (T v : interesting_values) {
+      fn (v);
+   }
+}
+
+/**
+ * @brief Perform one set of tests with the given integer values
+ *
+ * @tparam Dst The target type for the operation
+ * @param lhs The left-hand operand
+ * @param rhs The right-hand operand
+ *
+ * If you identify a problematic combination, you can call this
+ * directly in `main` with the known-bad values for easier debugging.
+ *
+ * This function is a no-op if the compiler does not provide the checked-arithmetic
+ * builtins.
+ */
+template <typename Dst, typename L, typename R>
+void
+test_case (L lhs, R rhs)
+{
+   (void) lhs;
+   (void) rhs;
+#if have_ckdint_builtins()
+   Dst mres, gres;
+   // Test addition:
+   mlib_check (mlib_add (&mres, lhs, rhs), eq, __builtin_add_overflow (lhs, rhs, &gres));
+   mlib_check (mres, eq, gres);
+
+   // Test subtraction:
+   mlib_check (mlib_sub (&mres, lhs, rhs), eq, __builtin_sub_overflow (lhs, rhs, &gres));
+   mlib_check (mres, eq, gres);
+
+   // Test multiplication
+   mlib_check (mlib_mul (&mres, lhs, rhs), eq, __builtin_mul_overflow (lhs, rhs, &gres));
+   mlib_check (mres, eq, gres);
+
+   // Test narrowing (both operands)
+   mlib_check (mlib_narrow (&mres, lhs), eq, __builtin_add_overflow (lhs, 0, &gres));
+   mlib_check (mres, eq, gres);
+   mlib_check (mlib_narrow (&mres, rhs), eq, __builtin_add_overflow (rhs, 0, &gres));
+   mlib_check (mres, eq, gres);
+#endif
+}
+
+template <typename Dst, typename L, typename R>
+int
+test_arithmetic ()
+{
+   with_interesting_values<L> ([&] (L lhs) {    //
+      with_interesting_values<R> ([&] (R rhs) { //
+         test_case<Dst> (lhs, rhs);
+      });
+   });
+   return 0;
+}
+
+template <typename Dst, typename Lhs, typename... Rhs>
+int
+test_rhs (typelist<Rhs...>)
+{
+   // Call with every Rhs type
+   auto arr = {test_arithmetic<Dst, Lhs, Rhs> ()...};
+   (void) arr;
+   return 0;
+}
+
+template <typename Dest, typename... Lhs>
+int
+test_lhs (typelist<Lhs...>)
+{
+   // Expand to a call of test_rhs for every Lhs type
+   auto arr = {test_rhs<Dest, Lhs> (integer_types{})...};
+   (void) arr;
+   return 0;
+}
+
+template <typename... Dst>
+void
+test_dst_types (typelist<Dst...>)
+{
+   // Expand to a call of test_lhs for each Dst type
+   auto arr = {test_lhs<Dst> (integer_types{})...};
+   (void) arr;
+}
+
+int
+main ()
+{
+   // Test that the dest can be used as an operand simultaneously:
+   int a = 42;
+   mlib_add (&a, a, 5);    // `a` is both an addend and the dst
+   mlib_check (a, eq, 47); // Check that the addition respected the `42`
+
+   // The `check` arithmetic functions should abort the process immediately
+   mlib_assert_aborts () {
+      mlib_assert_add (size_t, 41, -42);
+   }
+   mlib_assert_aborts () {
+      mlib_assert_add (ptrdiff_t, 41, SIZE_MAX);
+   }
+   // Does not abort:
+   const size_t sum = mlib_assert_add (size_t, -32, 33);
+   mlib_check (sum, eq, 1);
+
+   // Test all integer types:
+   test_dst_types (integer_types{});
+   if (!have_ckdint_builtins ()) {
+      puts ("@@ctest-skipped@@ - No __builtin_<op>_overflow builtins to test against");
+   }
+}
diff -pruN 1.30.4-1/src/common/src/mlib/cmp.h 2.0.2-1/src/common/src/mlib/cmp.h
--- 1.30.4-1/src/common/src/mlib/cmp.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/cmp.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,135 @@
+/**
+ * @file mlib/cmp.h
+ * @brief Safe integer comparison and range checking
+ * @date 2024-08-29
+ *
+ * This file provides safe and intuitive integer comparison macros that behave
+ * appropriately, regardless of the sign or precision of the integer operands.
+ *
+ * @copyright Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef MLIB_CMP_H_INCLUDED
+#define MLIB_CMP_H_INCLUDED
+
+#include <mlib/config.h>
+#include <mlib/intutil.h>
+
+#include <stdbool.h>
+#include <stdint.h>
+
+/**
+ * @brief Result type of comparing two integral values with `mlib_cmp`
+ *
+ * The enumerator values are chosen such that they can be compared with zero
+ */
+enum mlib_cmp_result {
+   // The two values are equivalent
+   mlib_equal = 0,
+   // The left-hand operand is less than the right-hand
+   mlib_less = -1,
+   // The left-hand operand is greater than the right-hand
+   mlib_greater = 1,
+};
+
+/**
+ * @brief Compare two integral values safely.
+ *
+ * NOTE: This macro may evaluate the operand expressions more than once! Do not
+ * use expressions that are expensive or have side effects!
+ *
+ * This function can be called with two arguments or with three:
+ *
+ * - `mlib_cmp(a, b)` Returns a value of type `mlib_cmp_result`
+ * - `mlib_cmp(a, Op, b)` where `Op` is a relational operator. Evaluates to a boolean value.
+ */
+#define mlib_cmp(...) MLIB_ARGC_PICK (_mlib_cmp, __VA_ARGS__)
+// Compare two integers, and return the result of that comparison:
+#define _mlib_cmp_argc_2(L, R) mlib_cmp (mlib_upsize_integer ((L)), mlib_upsize_integer ((R)), 0)
+// Compare two integers, but with an infix operator:
+#define _mlib_cmp_argc_3(L, Op, R) (mlib_cmp (mlib_upsize_integer ((L)), mlib_upsize_integer ((R)), 0) Op 0)
+// Impl for mlib_cmp
+mlib_always_inline static enum mlib_cmp_result (mlib_cmp) (struct mlib_upsized_integer x,
+                                                           struct mlib_upsized_integer y,
+                                                           int always_zero) mlib_noexcept
+{
+   (void) always_zero;
+#if mlib_is_optimized_build() && !mlib_is_msvc() && \
+   !(defined(MLIB_DISABLE_INLINING_ASSERTIONS) && MLIB_DISABLE_INLINING_ASSERTIONS)
+   if (always_zero != 0) {
+      // All calls must pass zero for `always_zero`. In optimized builds, we assert that this function
+      // is always inlined, and that dead-code-elim triggers to delete this branch that calls
+      // a never-defined function.
+      extern void __assert_that_mlib_cmp_was_inlined (void);
+      // If you see a call to this function ↑ produce a link error here ↓, it means
+      // that inlining or DCE failed within the relevant translation unit.
+      __assert_that_mlib_cmp_was_inlined ();
+   }
+#endif
+   if (x.is_signed) {
+      if (y.is_signed) {
+         // Both signed
+         if (x.i.s < y.i.s) {
+            return mlib_less;
+         } else if (x.i.s > y.i.s) {
+            return mlib_greater;
+         }
+      } else {
+         // X signed, Y unsigned
+         if (x.i.s < 0 || (uintmax_t) x.i.s < y.i.u) {
+            return mlib_less;
+         } else if ((uintmax_t) x.i.s > y.i.u) {
+            return mlib_greater;
+         }
+      }
+   } else {
+      if (!y.is_signed) {
+         // Both unsigned
+         if (x.i.u < y.i.u) {
+            return mlib_less;
+         } else if (x.i.u > y.i.u) {
+            return mlib_greater;
+         }
+      } else {
+         // X unsigned, Y signed
+         if (y.i.s < 0 || x.i.u > (uintmax_t) y.i.s) {
+            return mlib_greater;
+         } else if (x.i.u < (uintmax_t) y.i.s) {
+            return mlib_less;
+         }
+      }
+   }
+   return mlib_equal;
+}
+
+/**
+ * @brief Test whether the given operand is within the range of some other integral type
+ *
+ * @param T A type specifier of the target integral type
+ * @param Operand the expression that is being inspected.
+ *
+ * @note This macro may evaluate the operand more than once
+ */
+#define mlib_in_range(T, Operand) \
+   mlib_in_range ((intmax_t) mlib_minof (T), (uintmax_t) mlib_maxof (T), mlib_upsize_integer (Operand))
+static inline bool (mlib_in_range) (intmax_t min_, uintmax_t max_, struct mlib_upsized_integer val) mlib_noexcept
+{
+   if (val.is_signed) {
+      return mlib_cmp (val.i.s, >=, min_) && mlib_cmp (val.i.s, <=, max_);
+   } else {
+      return mlib_cmp (val.i.u, >=, min_) && mlib_cmp (val.i.u, <=, max_);
+   }
+}
+
+#endif // MLIB_CMP_H_INCLUDED
diff -pruN 1.30.4-1/src/common/src/mlib/config.h 2.0.2-1/src/common/src/mlib/config.h
--- 1.30.4-1/src/common/src/mlib/config.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/config.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,353 @@
+/**
+ * @file mlib/config.h
+ * @brief Provides utility macros
+ * @date 2024-08-29
+ *
+ * @note This file is intented to be standalone-includable, with no dependencies
+ * other than the standard library and platform headers. This file (and other
+ * `mlib` files), are for internal use only, and should not be used in any public
+ * headers.
+ *
+ * @copyright Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef MLIB_CONFIG_H_INCLUDED
+#define MLIB_CONFIG_H_INCLUDED
+
+#ifndef _WIN32
+#include <sys/param.h> // Endian detection
+#endif
+
+/**
+ * @brief A function-like macro that always expands to nothing
+ */
+#define MLIB_NOTHING(...)
+
+/**
+ * @brief A function macro that simply expands to its arguments unchanged
+ */
+#define MLIB_JUST(...) __VA_ARGS__
+
+// Paste two tokens
+#ifndef _MSC_VER
+#define MLIB_PASTE(A, ...) _mlibPaste1 (A, __VA_ARGS__)
+#else
+#define MLIB_PASTE(A, ...) MLIB_JUST (_mlibPaste1 (A, __VA_ARGS__))
+#endif
+// Paste three tokens
+#define MLIB_PASTE_3(A, B, ...) MLIB_PASTE (A, MLIB_PASTE (B, __VA_ARGS__))
+// Paste four tokens
+#define MLIB_PASTE_4(A, B, C, ...) MLIB_PASTE (A, MLIB_PASTE_3 (B, C, __VA_ARGS__))
+// Paste five tokens
+#define MLIB_PASTE_5(A, B, C, D, ...) MLIB_PASTE (A, MLIB_PASTE_4 (B, C, D, __VA_ARGS__))
+#define _mlibPaste1(A, ...) A##__VA_ARGS__
+
+/**
+ * @brief Convert the token sequence into a string after macro expansion
+ */
+#define MLIB_STR(...) _mlibStr (__VA_ARGS__)
+#define _mlibStr(...) #__VA_ARGS__
+
+#define MLIB_EVAL_32(...) MLIB_EVAL_16 (MLIB_EVAL_16 (__VA_ARGS__))
+#define MLIB_EVAL_16(...) MLIB_EVAL_8 (MLIB_EVAL_8 (__VA_ARGS__))
+#define MLIB_EVAL_8(...) MLIB_EVAL_4 (MLIB_EVAL_4 (__VA_ARGS__))
+#define MLIB_EVAL_4(...) MLIB_EVAL_2 (MLIB_EVAL_2 (__VA_ARGS__))
+#define MLIB_EVAL_2(...) MLIB_EVAL_1 (MLIB_EVAL_1 (__VA_ARGS__))
+#define MLIB_EVAL_1(...) __VA_ARGS__
+
+// clang-format off
+/**
+ * @brief Expand to 1 if given no arguments, otherwise 0.
+ *
+ * This could be done trivially using __VA_OPT__, but we need to work on
+ * older compilers.
+ */
+#define MLIB_IS_EMPTY(...) \
+    _mlibIsEmpty_1( \
+        /* Expands to '1' if __VA_ARGS__ contains any top-level commas */ \
+        _mlibHasComma(__VA_ARGS__), \
+        /* Expands to '1' if __VA_ARGS__ begins with a parenthesis, because \
+         * that will cause an "invocation" of _mlibCommaIfParens, \
+         * which immediately expands to a single comma. */ \
+        _mlibHasComma(_mlibCommaIfParens __VA_ARGS__), \
+        /* Expands to '1' if __VA_ARGS__ expands to a function-like macro name \
+         * that then expands to anything containing a top-level comma */ \
+        _mlibHasComma(__VA_ARGS__ ()), \
+        /* Expands to '1' if __VA_ARGS__ expands to nothing. */ \
+        _mlibHasComma(_mlibCommaIfParens __VA_ARGS__ ()))
+// Expand to 1 if the argument list has a comma. The weird definition is to support
+// old MSVC's bad preprocessor
+#define _mlibHasComma(...) \
+   MLIB_JUST(_mlibPickSixteenth \
+               MLIB_NOTHING("MSVC workaround") \
+            (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, ~))
+#define _mlibCommaIfParens(...) ,
+
+/**
+ * A helper for isEmpty(): If given (0, 0, 0, 1), expands as:
+ *    - first: _mlibHasComma(_mlibIsEmptyCase_0001)
+ *    -  then: _mlibHasComma(,)
+ *    -  then: 1
+ * Given any other aruments:
+ *    - first: _mlibHasComma(_mlibIsEmptyCase_<somethingelse>)
+ *    -  then: 0
+ */
+#define _mlibIsEmpty_1(_1, _2, _3, _4) \
+    _mlibHasComma(MLIB_PASTE_5(_mlibIsEmptyCase_, _1, _2, _3, _4))
+#define _mlibIsEmptyCase_0001 ,
+
+#define MLIB_IS_NOT_EMPTY(...) MLIB_PASTE (_mlibNotEmpty_, MLIB_IS_EMPTY (__VA_ARGS__))
+#define _mlibNotEmpty_1 0
+#define _mlibNotEmpty_0 1
+// clang-format on
+
+/**
+ * @brief If the argument expands to `0`, `false`, or nothing, expands to `0`.
+ * Otherwise expands to `1`.
+ */
+#define MLIB_BOOLEAN(...) MLIB_IS_NOT_EMPTY (MLIB_PASTE_3 (_mlib, Bool_, __VA_ARGS__))
+#define _mlibBool_0
+#define _mlibBool_false
+#define _mlibBool_
+
+/**
+ * @brief A ternary macro. Expects three parenthesized argument lists in
+ * sequence.
+ *
+ * If the first argument list is a truthy value, expands to the second argument
+ * list. Otherwise, expands to the third argument list. The unused argument list
+ * is not expanded and is discarded.
+ */
+#define MLIB_IF_ELSE(...) MLIB_PASTE (_mlibIfElseBranch_, MLIB_BOOLEAN (__VA_ARGS__))
+#define _mlibIfElseBranch_1(...) __VA_ARGS__ _mlibNoExpandNothing
+#define _mlibIfElseBranch_0(...) MLIB_NOTHING (#__VA_ARGS__) MLIB_JUST
+#define _mlibNoExpandNothing(...) MLIB_NOTHING (#__VA_ARGS__)
+
+/**
+ * @brief Expands to an integer literal corresponding to the number of macro
+ * arguments. Supports up to fifteen arguments.
+ */
+#define MLIB_ARG_COUNT(...)                   \
+   MLIB_IF_ELSE (MLIB_IS_EMPTY (__VA_ARGS__)) \
+   (0) (_mlibPickSixteenth (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
+#define _mlibPickSixteenth(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, ...) _16
+
+/**
+ * @brief Expand to a call expression `Prefix##_argc_N(...)`, where `N` is the
+ * number of macro arguments.
+ */
+#define MLIB_ARGC_PICK(Prefix, ...) \
+   MLIB_JUST (MLIB_PASTE_3 (Prefix, _argc_, MLIB_ARG_COUNT (__VA_ARGS__)) (__VA_ARGS__))
+
+#ifdef __cplusplus
+#define mlib_is_cxx() 1
+#define mlib_is_not_cxx() 0
+#define MLIB_IF_CXX(...) __VA_ARGS__
+#define MLIB_IF_NOT_CXX(...)
+#else
+#define mlib_is_cxx() 0
+#define mlib_is_not_cxx() 1
+#define MLIB_IF_CXX(...)
+#define MLIB_IF_NOT_CXX(...) __VA_ARGS__
+#endif
+
+#define MLIB_LANG_PICK MLIB_IF_ELSE (mlib_is_not_cxx ())
+
+/**
+ * @brief Use as the prefix of a braced initializer within C headers, allowing
+ * the initializer to appear as a compound-init in C and an equivalent braced
+ * aggregate-init in C++
+ */
+#define mlib_init(T) MLIB_LANG_PICK ((T)) (T)
+
+/**
+ * @brief Expands to `noexcept` when compiled as C++, otherwise expands to
+ * nothing
+ */
+#define mlib_noexcept MLIB_IF_CXX (noexcept)
+
+#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
+#define mlib_is_little_endian() (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
+#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN)
+#define mlib_is_little_endian() (__BYTE_ORDER == __LITTLE_ENDIAN)
+#elif defined(_WIN32)
+#define mlib_is_little_endian() 1
+#else
+#error "Do not know how to detect endianness on this platform."
+#endif
+
+// clang-format off
+/**
+ * @brief Expands to a static assertion declaration.
+ *
+ * When supported, this can be replaced with `_Static_assert` or `static_assert`
+ */
+#define mlib_static_assert(...) MLIB_ARGC_PICK (_mlib_static_assert, __VA_ARGS__)
+#define _mlib_static_assert_argc_1(Expr) \
+   _mlib_static_assert_argc_2 ((Expr), "Static assertion failed")
+#define _mlib_static_assert_argc_2(Expr, Msg) \
+   extern int \
+   MLIB_PASTE (_mlib_static_assert_placeholder, __COUNTER__)[(Expr) ? 2 : -1] \
+   MLIB_IF_GNU_LIKE (__attribute__ ((unused)))
+// clang-format on
+
+#define mlib_extern_c_begin() MLIB_IF_CXX(extern "C" {) mlib_static_assert(1, "")
+#define mlib_extern_c_end() MLIB_IF_CXX( \
+   }) mlib_static_assert(1, "")
+
+#ifdef __GNUC__
+#define mlib_is_gnu_like() 1
+#ifdef __clang__
+#define mlib_is_gcc() 0
+#define mlib_is_clang() 1
+#else
+#define mlib_is_gcc() 1
+#define mlib_is_clang() 0
+#endif
+#define mlib_is_msvc() 0
+#elif defined(_MSC_VER)
+#define mlib_is_gnu_like() 0
+#define mlib_is_clang() 0
+#define mlib_is_gcc() 0
+#define mlib_is_msvc() 1
+#endif
+
+#if defined(_WIN32)
+#define mlib_is_win32() 1
+#define mlib_is_unix() 0
+#else
+#define mlib_is_unix() 1
+#define mlib_is_win32() 0
+#endif
+
+#define MLIB_IF_CLANG(...) MLIB_IF_ELSE (mlib_is_clang ()) (__VA_ARGS__) (MLIB_NOTHING (#__VA_ARGS__))
+#define MLIB_IF_GCC(...) MLIB_IF_ELSE (mlib_is_gcc ()) (__VA_ARGS__) (MLIB_NOTHING (#__VA_ARGS__))
+#define MLIB_IF_GNU_LIKE(...) MLIB_IF_GCC (__VA_ARGS__) MLIB_IF_CLANG (__VA_ARGS__) MLIB_NOTHING (#__VA_ARGS__)
+#define MLIB_IF_UNIX_LIKE(...) MLIB_IF_ELSE (mlib_is_unix ()) (__VA_ARGS__) (MLIB_NOTHING (#__VA_ARGS__))
+
+// note: Bug on GCC preprocessor prevents us from using if/else trick to omit MSVC code
+#if mlib_is_msvc()
+#define MLIB_IF_MSVC(...) __VA_ARGS__
+#define mlib_pragma(...) __pragma (__VA_ARGS__) mlib_static_assert (1, "")
+#else
+#define MLIB_IF_MSVC(...) MLIB_NOTHING (#__VA_ARGS__)
+#define mlib_pragma(...) _Pragma (#__VA_ARGS__) mlib_static_assert (1, "")
+#endif
+
+#define MLIB_FUNC MLIB_IF_GNU_LIKE (__func__) MLIB_IF_MSVC (__FUNCTION__)
+
+#define mlib_diagnostic_push()                           \
+   MLIB_IF_GNU_LIKE (mlib_pragma (GCC diagnostic push);) \
+   MLIB_IF_MSVC (mlib_pragma (warning (push));)          \
+   mlib_static_assert (true, "")
+
+#define mlib_diagnostic_pop()                           \
+   MLIB_IF_GNU_LIKE (mlib_pragma (GCC diagnostic pop);) \
+   MLIB_IF_MSVC (mlib_pragma (warning (pop));)          \
+   mlib_static_assert (true, "")
+
+#define mlib_gcc_warning_disable(Warning)                      \
+   MLIB_IF_GCC (mlib_pragma (GCC diagnostic ignored Warning);) \
+   mlib_static_assert (true, "")
+
+#define mlib_gnu_warning_disable(Warning)                           \
+   MLIB_IF_GNU_LIKE (mlib_pragma (GCC diagnostic ignored Warning);) \
+   mlib_static_assert (true, "")
+
+#define mlib_msvc_warning(...)                         \
+   MLIB_IF_MSVC (mlib_pragma (warning (__VA_ARGS__));) \
+   mlib_static_assert (true, "")
+
+/**
+ * @brief Attribute macro that forces the function to be inlined at all call sites.
+ *
+ * Don't use this unless you really know that you need it, lest you generate code
+ * bloat when the compiler's heuristics would do a better job.
+ */
+#define mlib_always_inline MLIB_IF_GNU_LIKE (__attribute__ ((always_inline)) inline) MLIB_IF_MSVC (__forceinline)
+
+// Annotate a variable as thread-local
+#define mlib_thread_local MLIB_IF_GNU_LIKE (__thread) MLIB_IF_MSVC (__declspec (thread))
+
+// Annotate an entiry that might be unused
+#define mlib_maybe_unused MLIB_IF_GNU_LIKE (__attribute__ ((unused)))
+
+// clang-format off
+/**
+ * @brief Expand to `1` if the current build configuration matches the given token.
+ *
+ * If the token is not a known valid build configuration, generates a compilation
+ * error (check your spelling!)
+ *
+ * Requires that `_MLIB_BUILD_CONFIG` is defined, otherwise always expands to `0`
+ */
+#define mlib_build_config_is(Config) \
+   /* If `Config` is a recognized config, this line will disappear, */ \
+   /* other wise it will be a "call to undefined macro": */ \
+   MLIB_PASTE_4 (_mlibTestBuildConfig_, Config, _, Config) () \
+   /* If `Config` is the same token as `_MLIB_BUILD_CONFIG`, this will */ \
+   /* expand to `1`, otherwise it will expand to `0` */ \
+   MLIB_IS_EMPTY (MLIB_PASTE_4 (_mlibTestBuildConfig_, Config, _, _MLIB_BUILD_CONFIG) ())
+// clang-format on
+// Known build configurations:
+#define _mlibTestBuildConfig_Release_Release()
+#define _mlibTestBuildConfig_Debug_Debug()
+#define _mlibTestBuildConfig_RelWithDebInfo_RelWithDebInfo()
+#define _mlibTestBuildConfig_MinSizeRel_MinSizeRel()
+
+/**
+ * @brief Emit a _Pragma that will disable warnings about the use of deprecated entities.
+ */
+#define mlib_disable_deprecation_warnings()                \
+   mlib_gnu_warning_disable ("-Wdeprecated-declarations"); \
+   mlib_msvc_warning (disable : 4996)
+
+/**
+ * @brief Function-like macro that expands to `1` if we are certain that we are
+ * compiling with optimizations enabled.
+ *
+ * This may yield `0` if we cannot determine whether optimization is turned on.
+ *
+ * This macro should be used with care, as different translation units can see different values,
+ * but still be linked together in the final program. Beware generating ODR violations.
+ */
+#define mlib_is_optimized_build() _mlibIsOptimizedBuild ()
+
+#if mlib_build_config_is(Release) || mlib_build_config_is(RelWithDebInfo) || mlib_build_config_is(MinSizeRel) || \
+   (defined(__OPTIMIZE__) && __OPTIMIZE__)
+// Preproc definition __OPTIMIZE__set by GCC ang Clang when the optimizer is enabled.
+// MSVC has no such definition, so we rely on CMake to tell us when we are compiling in release mode
+#define _mlibIsOptimizedBuild() 1
+#else
+#define _mlibIsOptimizedBuild() 0
+#endif
+
+#if mlib_is_gnu_like()
+#define mlib_have_typeof() 1
+#elif defined _MSC_VER && _MSC_VER >= 1939 && !__cplusplus
+// We can __typeof__ in MSVC 19.39+
+#define mlib_have_typeof() 1
+#else
+#define mlib_have_typeof() 0
+#endif
+
+/**
+ * @brief Equivalent to C23's `typeof()`, if it is supported by the current compiler.
+ *
+ * This expands to `__typeof__`, which is supported even on newer MSVC compilers,
+ * even when not in C23 mode.
+ */
+#define mlib_typeof(...) MLIB_IF_ELSE (mlib_have_typeof ()) (__typeof__) (__mlib_typeof_is_not_supported) (__VA_ARGS__)
+
+#endif // MLIB_CONFIG_H_INCLUDED
diff -pruN 1.30.4-1/src/common/src/mlib/intencode.h 2.0.2-1/src/common/src/mlib/intencode.h
--- 1.30.4-1/src/common/src/mlib/intencode.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/intencode.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,167 @@
+/**
+ * @file mlib/intencode.h
+ * @brief Integer encoding functions
+ * @date 2025-01-31
+ *
+ * @copyright Copyright (c) 2025
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <mlib/config.h>
+#include <mlib/loop.h>
+
+#include <stdint.h>
+#include <string.h>
+
+/**
+ * @brief Decode an unsigned 32-bit little-endian integer from a memory buffer
+ */
+static inline uint32_t
+mlib_read_u32le (const void *buf)
+{
+   uint32_t ret = 0;
+   if (mlib_is_little_endian ()) {
+      // Optimize: The platform uses a LE encoding already
+      memcpy (&ret, buf, sizeof ret);
+   } else {
+      // Portable decode of an LE integer
+      const uint8_t *cptr = (const uint8_t *) buf;
+      mlib_foreach_urange (i, sizeof ret) {
+         ret <<= 8;
+         ret |= cptr[(sizeof ret) - i - 1];
+      }
+   }
+   return ret;
+}
+
+/**
+ * @brief Decode an signed 32-bit little-endian integer from a memory buffer
+ */
+static inline int32_t
+mlib_read_i32le (const void *buf)
+{
+   const uint32_t u = mlib_read_u32le (buf);
+   int32_t r;
+   memcpy (&r, &u, sizeof r);
+   return r;
+}
+
+/**
+ * @brief Decode an unsigned 64-bit little-endian integer from a memory buffer
+ */
+static inline uint64_t
+mlib_read_u64le (const void *buf)
+{
+   uint64_t ret = 0;
+   if (mlib_is_little_endian ()) {
+      // Optimize: The platform uses a LE encoding already
+      memcpy (&ret, buf, sizeof ret);
+   } else {
+      // Portable decode of an LE integer
+      const uint8_t *cptr = (const uint8_t *) buf;
+      mlib_foreach_urange (i, sizeof ret) {
+         ret <<= 8;
+         ret |= cptr[(sizeof ret) - i - 1];
+      }
+   }
+   return ret;
+}
+
+/**
+ * @brief Decode an signed 64-bit little-endian integer from a memory buffer
+ */
+static inline int64_t
+mlib_read_i64le (const void *buf)
+{
+   const uint64_t u = mlib_read_u64le (buf);
+   int64_t r;
+   memcpy (&r, &u, sizeof r);
+   return r;
+}
+
+/**
+ * @brief Write an unsigned 32-bit little-endian integer into a destination
+ *
+ * @return void* The address after the written value
+ */
+static inline void *
+mlib_write_u32le (void *out, const uint32_t value)
+{
+   uint8_t *o = (uint8_t *) out;
+   if (mlib_is_little_endian ()) {
+      memcpy (o, &value, sizeof value);
+      return o + sizeof value;
+   }
+   mlib_foreach_urange (i, sizeof value) {
+      *o++ = (value >> (8u * i)) & 0xffu;
+   }
+   return o;
+}
+
+/**
+ * @brief Write a signed 32-bit little-endian integer into a destination
+ *
+ * @return void* The address after the written value
+ */
+static inline void *
+mlib_write_i32le (void *out, int32_t value)
+{
+   return mlib_write_u32le (out, (uint32_t) value);
+}
+
+/**
+ * @brief Write an unsigned 64-bit little-endian integer into a destination
+ *
+ * @return void* The address after the written value
+ */
+static inline void *
+mlib_write_u64le (void *out, const uint64_t value)
+{
+   uint8_t *o = (uint8_t *) out;
+   if (mlib_is_little_endian ()) {
+      memcpy (o, &value, sizeof value);
+      return o + sizeof value;
+   }
+   mlib_foreach_urange (i, sizeof value) {
+      *o++ = (value >> (8u * i)) & 0xffu;
+   }
+   return o;
+}
+
+/**
+ * @brief Write an signed 64-bit little-endian integer into a destination
+ *
+ * @return void* The address after the written value
+ */
+static inline void *
+mlib_write_i64le (void *out, int64_t value)
+{
+   return mlib_write_u64le (out, (uint64_t) value);
+}
+
+/**
+ * @brief Write a little-endian 64-bit floating point (double) to the given
+ * memory location
+ *
+ * @return void* The address after the written value.
+ */
+static inline void *
+mlib_write_f64le (void *out, double d)
+{
+   mlib_static_assert (sizeof (double) == sizeof (uint64_t));
+   uint64_t bits;
+   memcpy (&bits, &d, sizeof d);
+   return mlib_write_u64le (out, bits);
+}
diff -pruN 1.30.4-1/src/common/src/mlib/intutil.h 2.0.2-1/src/common/src/mlib/intutil.h
--- 1.30.4-1/src/common/src/mlib/intutil.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/intutil.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,93 @@
+/**
+ * @file mlib/intutil.h
+ * @brief Integer utilities
+ * @date 2025-01-28
+ *
+ * @copyright Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef MLIB_INTUTIL_H_INCLUDED
+#define MLIB_INTUTIL_H_INCLUDED
+
+#include <limits.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @brief Given an integral type, evaluates to `true` if that type is signed,
+ * otherwise `false`
+ */
+#define mlib_is_signed(T) (!((T) (-1) > 0))
+
+// clang-format off
+/**
+ * @brief Given an integral type, yield an integral constant value representing
+ * the maximal value of that type.
+ */
+#define mlib_maxof(T) \
+   ((T) (mlib_is_signed (T) \
+        ? ((T) ((((T) 1 << (sizeof (T) * CHAR_BIT - 2)) - 1) * 2 + 1)) \
+        : ((T) ~(T) 0)))
+
+/**
+ * @brief Given an integral type, yield an integral constant value for the
+ * minimal value of that type.
+ */
+#define mlib_minof(T) \
+   ((T) (!mlib_is_signed (T) \
+        ? (T) 0 \
+        : (T) (-((((T) 1 << (sizeof (T) * CHAR_BIT - 2)) - 1) * 2 + 1) - 1)))
+// clang-format on
+
+/**
+ * @brief A container for an integer that has been "scaled up" to maximum precision
+ *
+ * Don't create this manually. Instead, use `mlib_upsize_integer` to do it automatically
+ */
+typedef struct mlib_upsized_integer {
+   union {
+      // The signed value of the integer
+      intmax_t s;
+      // The unsigned value of the integer
+      uintmax_t u;
+   } i;
+   // Whether the upscaled integer is stored in the signed field or the unsigned field
+   bool is_signed;
+} mlib_upsized_integer;
+
+// clang-format off
+/**
+ * @brief Create an "upsized" version of an integer, normalizing all integral
+ * values into a single type so that we can deduplicate functions that operate
+ * on disparate integer types.
+ *
+ * Details: The integer is upcast into the maximum precision integer type (intmax_t). If
+ * the operand is smaller than `intmax_t`, we assume that casting to the signed `intmax_t`
+ * is always safe, even if the operand is unsigned, since e.g. a u32 can always be cast to
+ * an i64 losslessly.
+ *
+ * If the integer to upcast is the same size as `intmax_t`, we need to decide whether to store
+ * it as unsigned. The expression `(0 & Value) - 1 < 0` will be `true` iff the operand is signed,
+ * otherwise false. If the operand is signed, we can safely cast to `intmax_t` (it probably already
+ * is of that type), otherwise, we can to `uintmax_t` and the returned `mlib_upsized_integer` will
+ * indicate that the stored value is unsigned.
+ */
+#define mlib_upsize_integer(Value) \
+   /* NOLINTNEXTLINE(bugprone-sizeof-expression) */ \
+   ((sizeof ((Value)) < sizeof (intmax_t) || ((0 & (Value)) - 1) < 0) \
+      ? mlib_init(mlib_upsized_integer) {{(intmax_t) (Value)}, true} \
+      : mlib_init(mlib_upsized_integer) {{(intmax_t) (uintmax_t) (Value)}})
+// clang-format on
+
+#endif // MLIB_INTUTIL_H_INCLUDED
diff -pruN 1.30.4-1/src/common/src/mlib/loop.h 2.0.2-1/src/common/src/mlib/loop.h
--- 1.30.4-1/src/common/src/mlib/loop.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/loop.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,165 @@
+/**
+ * @file mlib/loop.h
+ * @brief Looping utility macros
+ * @date 2025-01-29
+ *
+ * @copyright Copyright (c) 2025
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef MLIB_LOOP_H_INCLUDED
+#define MLIB_LOOP_H_INCLUDED
+
+#include <mlib/config.h>
+
+#include <stdbool.h>
+#include <stdint.h> // u/intmax_t
+
+/**
+ * @brief Begin a loop over a range of integer values. Supports:
+ *
+ * - `mlib_foreach_{u,i}range(Var, Stop)`
+ * - `mlib_foreach_{u,i}range(Var, Start, Stop)`
+ *
+ * If omitted, starts at zero. The loop does not include the `Stop` value. The `Var`
+ * variable cannot be modified within the loop. The loop variable is declared as the maximum
+ * precision type for the requested signedness.
+ */
+#define mlib_foreach_urange(...) MLIB_ARGC_PICK (_mlib_foreach_urange, __VA_ARGS__)
+#define mlib_foreach_irange(...) MLIB_ARGC_PICK (_mlib_foreach_irange, __VA_ARGS__)
+#define _mlib_foreach_urange_argc_2(VarName, Stop) _mlib_foreach_urange_argc_3 (VarName, 0, Stop)
+#define _mlib_foreach_urange_argc_3(VarName, Start, Stop) \
+   _mlibForeachRange (uintmax_t,                          \
+                      VarName,                            \
+                      Start,                              \
+                      Stop,                               \
+                      MLIB_PASTE (VarName, _start),       \
+                      MLIB_PASTE (VarName, _stop),        \
+                      MLIB_PASTE (VarName, _counter))
+#define _mlib_foreach_irange_argc_2(VarName, Stop) _mlib_foreach_irange_argc_3 (VarName, 0, Stop)
+#define _mlib_foreach_irange_argc_3(VarName, Start, Stop) \
+   _mlibForeachRange (intmax_t,                           \
+                      VarName,                            \
+                      Start,                              \
+                      Stop,                               \
+                      MLIB_PASTE (VarName, _start),       \
+                      MLIB_PASTE (VarName, _stop),        \
+                      MLIB_PASTE (VarName, _counter))
+
+/**
+ * @brief Loop over a pointed-to array
+ *
+ * @param T The type of the array elements
+ * @param Var Identifier to declare as the pointer to the current element
+ * @param ArrayPtr A pointer to the beginning of the array
+ * @param Count The number of elements in the array
+ */
+#define mlib_foreach(T, Var, ArrayPtr, Count) \
+   _mlibForeach (T, Var, ArrayPtr, Count, MLIB_PASTE (Var, _start), MLIB_PASTE (Var, _stop), MLIB_PASTE (Var, _iter))
+/**
+ * @brief Loop over the elements of a C array
+ *
+ * @param T the type of the array elements
+ * @param Var Identifier to declare as the pointer to the current element
+ * @param Array An expression of array type (not a pointer)
+ */
+#define mlib_foreach_arr(T, Var, Array) mlib_foreach (T, Var, Array, (sizeof Array / sizeof Array[0]))
+
+// clang-format off
+#define _mlibForeachRange(VarType, VarName, StartValue, StopValue, StartVar, StopVar, Counter) \
+    _mlibLoopMagicBegin() \
+    /* Capture the starting and stopping value first */ \
+    for (VarType StartVar = (StartValue), StopVar = (StopValue); !_mlibLoopIsDone;) \
+    _mlibLoopMagicEnd( \
+        /* Init counter to the start value */ \
+        VarType Counter = StartVar, \
+        /* Stop when the counter is not less than the stop value */ \
+        (_mlibLoopState.first = Counter == StartVar, \
+         _mlibLoopState.last = Counter + 1 == StopVar, \
+         Counter < StopVar), \
+        /* Increment the counter at loop end */ \
+        ++Counter, \
+        /* Declare the loop variable as const at the start of each iteraiton */ \
+        const VarType VarName = Counter)
+
+#define _mlibForeach(T, VarName, ArrayPtr, Count, StartVar, StopVar, Iter) \
+    _mlibLoopMagicBegin() \
+    /* Capture the starting and stopping position so we only evaluate them once */ \
+    for (T* const StartVar = (ArrayPtr) + 0; !_mlibLoopIsDone;) \
+    for (T* const StopVar = StartVar + (Count); !_mlibLoopIsDone;) \
+    _mlibLoopMagicEnd( \
+        /* Init the iteration pointer to the array start */ \
+        T* Iter = StartVar, \
+        /* Stop when the iterator points to the stop position */ \
+        (_mlibLoopState.first = Iter == StartVar, \
+         _mlibLoopState.last = Iter + 1 == StopVar, \
+         Iter != StopVar), \
+        /* Advance the iterator on each loop */ \
+        ++Iter, \
+        /* Declare a constant pointer to the current element at the top of the loop */ \
+        T* const VarName = Iter)
+
+
+#define _mlibLoopDidBreak MLIB_PASTE(_mlibLoopDidBreak_lno_, __LINE__)
+#define _mlibLoopOnce MLIB_PASTE(_mlibLoopOnce_lno_, __LINE__)
+#define _mlibLoopIsDone MLIB_PASTE(_mlibLoopIsDone_lno_, __LINE__)
+#define _mlibLoopIsState MLIB_PASTE(_mlibLoopIsState_lno_, __LINE__)
+#define _mlibLoopMagicBegin() \
+    /* Loop stop condition */ \
+    for (int _mlibLoopIsDone = 0; !_mlibLoopIsDone;) \
+    /* Track if the user broke out of the inner loop */ \
+    for (int _mlibLoopDidBreak = 0; !_mlibLoopIsDone;) \
+    /* Loop variables */ \
+    for (struct mlib_loop_state _mlibLoopState = {0, 0, 0}; !_mlibLoopIsDone;)
+
+/**
+ * @brief Struct type declared within the scope of an `mlib_foreach` loop, which
+ * contains information about the running loop.
+ */
+struct mlib_loop_state {
+    // The current zero-based index of the loop
+    size_t index;
+    // Whether the current iteration is the first in the loop
+    bool first;
+    // Whether the current iteration will be the last in the loop
+    bool last;
+};
+
+/// InitStmt: Statement that executes once at the top of the loop
+/// ContinueCond: Condition at which the loop will stop
+/// StepExpr: Expression for the loop step
+/// HeadStmt: A statement that appears at the head of the loop, executed once on each iteration
+#define _mlibLoopMagicEnd(InitStmt, ContinueCond, StepExpr, HeadStmt) \
+    for (\
+        /* Run the init statement */ \
+        InitStmt; \
+        /* Test the loop condition, unless we `break` out of the loop */ \
+        !(_mlibLoopIsDone = _mlibLoopIsDone || !(ContinueCond)); \
+        /* Run the step expression, unless we `break` from the loop */ \
+        (void)(_mlibLoopIsDone || ((void)(StepExpr), 1))) \
+    /* `break` detection: */ \
+    for (int _mlibLoopOnce = 0; !_mlibLoopOnce; _mlibLoopOnce = 1, _mlibLoopIsDone = _mlibLoopDidBreak) \
+    /* Loop state information */ \
+    for (const struct mlib_loop_state loop = _mlibLoopState; \
+         !_mlibLoopOnce; \
+         ((void)loop, _mlibLoopOnce = 1, ++_mlibLoopState.index)) \
+    for (HeadStmt; \
+        /* Set `_mlibLoopDidBreak` to true at the start of the loop: */ \
+        !_mlibLoopOnce && (_mlibLoopDidBreak = 1); \
+        /* If loop exits normally, set `_mlibLoopDidBreak` to false */ \
+        _mlibLoopDidBreak = 0, _mlibLoopOnce = 1)
+
+
+// clang-format on
+
+#endif // MLIB_LOOP_H_INCLUDED
diff -pruN 1.30.4-1/src/common/src/mlib/test.h 2.0.2-1/src/common/src/mlib/test.h
--- 1.30.4-1/src/common/src/mlib/test.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/src/mlib/test.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,247 @@
+/**
+ * @file mlib/test.h
+ * @brief Testing utilities
+ * @date 2025-01-30
+ *
+ * @copyright Copyright (c) 2025
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <mlib/cmp.h>
+#include <mlib/intutil.h>
+#include <mlib/config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+/**
+ * @brief Place this macro at the head of a (compound) statement to assert that
+ * executing that statement aborts the program with SIGABRT.
+ *
+ * Internally, this will fork the calling process and wait for the child process
+ * to terminate. It asserts that the child exits abnormally with SIGABRT. This
+ * test assertion is a no-op on Win32, since it does not have a suitable `fork`
+ * API.
+ *
+ * Beware that the child process runs in a forked environment, so it is not
+ * safe to use any non-fork-safe functionality, and any modifications to program
+ * state will not be visible in the parent. Behavior of attempting to escape the
+ * statement (goto/return) is undefined.
+ *
+ * If the child process does not abort, it will call `_Exit(71)` to indicate
+ * to the parent that it did not terminate (the number 71 is chosen arbitrarily)
+ *
+ * If the token `debug` is passed as a macro argument, then the forking behavior
+ * is suppressed, allowing for easier debugging of the statement.
+ */
+#define mlib_assert_aborts(...) MLIB_PASTE_3 (_mlibAssertAbortsStmt, _, __VA_ARGS__) ()
+
+#ifndef _WIN32
+#include <sys/wait.h>
+#include <unistd.h>
+#define _mlibAssertAbortsStmt_()                                                                  \
+   for (int once = 1, other_pid = fork (); once; once = 0)                                        \
+      for (; once; once = 0)                                                                      \
+         if (other_pid != 0) {                                                                    \
+            /* We are the parent */                                                               \
+            int wstatus;                                                                          \
+            waitpid (other_pid, &wstatus, 0);                                                     \
+            if (WIFEXITED (wstatus)) {                                                            \
+               /* Normal exit! */                                                                 \
+               _mlib_stmt_did_not_abort (__FILE__, MLIB_FUNC, __LINE__, WEXITSTATUS (wstatus));   \
+            } else if (WIFSIGNALED (wstatus)) {                                                   \
+               /* Signalled */                                                                    \
+               if (WTERMSIG (wstatus) != SIGABRT) {                                               \
+                  fprintf (stderr,                                                                \
+                           "%s:%d: [%s]: Child process did not exit with SIGABRT! (Exited %d)\n", \
+                           __FILE__,                                                              \
+                           __LINE__,                                                              \
+                           MLIB_FUNC,                                                             \
+                           WTERMSIG (wstatus));                                                   \
+                  fflush (stderr);                                                                \
+                  abort ();                                                                       \
+               }                                                                                  \
+            }                                                                                     \
+         } else /* We are the child */                                                            \
+            if ((fclose (stderr), 1))                                                             \
+               for (;; _Exit (71))                                                                \
+                  for (;; _Exit (71)) /* Double loop to prevent the block from `break`ing out */
+
+#else
+#define _mlibAssertAbortsStmt_() \
+   if (1) {                      \
+   } else
+#endif
+
+// Called when an assert-aborts statement does not terminate
+static inline void
+_mlib_stmt_did_not_abort (const char *file, const char *func, int line, int rc)
+{
+   /* Normal exit! */
+   if (rc == 71) {
+      fprintf (stderr, "%s:%d: [%s]: Test case did not abort. The statement completed normally.\n", file, line, func);
+   } else {
+      fprintf (stderr, "%s:%d: [%s]: Test case did not abort (Exited %d)\n", file, line, func, rc);
+   }
+   fflush (stderr);
+   abort ();
+}
+
+#define _mlibAssertAbortsStmt_debug()                                    \
+   for (;; _mlib_stmt_did_not_abort (__FILE__, MLIB_FUNC, __LINE__, -1)) \
+      for (;; _mlib_stmt_did_not_abort (__FILE__, MLIB_FUNC, __LINE__, -1))
+
+/**
+ * @brief Aggregate type that holds information about a source location
+ */
+typedef struct mlib_source_location {
+   const char *file;
+   int lineno;
+   const char *func;
+} mlib_source_location;
+
+/**
+ * @brief Expands to an `mlib_source_location` for the location in which the macro is expanded
+ */
+#define mlib_this_source_location() (mlib_init (mlib_source_location){(__FILE__), (__LINE__), (MLIB_FUNC)})
+// ↑ The paren wrapping is required on VS2017 to prevent it from deleting the preceding comma (?!)
+
+/**
+ * @brief Evaluate a check, aborting with a diagnostic if that check fails
+ *
+ * Can be called with one argument to test a single boolean condition, or three
+ * arguments for more useful diagnostics with an infix operator.
+ */
+#define mlib_check(...) MLIB_ARGC_PICK (_mlib_check, #__VA_ARGS__, __VA_ARGS__)
+// One arg:
+#define _mlib_check_argc_2(ArgString, Condition) \
+   _mlibCheckConditionSimple (Condition, ArgString, mlib_this_source_location ())
+// Three args:
+#define _mlib_check_argc_4(ArgString, A, Operator, B) \
+   MLIB_NOTHING (#A, #B) MLIB_PASTE (_mlibCheckCondition_, Operator) (A, B)
+// String-compare:
+#define _mlibCheckCondition_str_eq(A, B) _mlibCheckStrEq (A, B, #A, #B, mlib_this_source_location ())
+// Pointer-compare:
+#define _mlibCheckCondition_ptr_eq(A, B) _mlibCheckPtrEq (A, B, #A, #B, mlib_this_source_location ())
+// Integer-equal:
+#define _mlibCheckCondition_eq(A, B) \
+   _mlibCheckIntCmp (                \
+      mlib_equal, true, "==", mlib_upsize_integer (A), mlib_upsize_integer (B), #A, #B, mlib_this_source_location ())
+// Integer not-equal:
+#define _mlibCheckCondition_neq(A, B) \
+   _mlibCheckIntCmp (                 \
+      mlib_equal, false, "!=", mlib_upsize_integer (A), mlib_upsize_integer (B), #A, #B, mlib_this_source_location ())
+
+/// Check evaluator when given a single boolean
+static inline void
+_mlibCheckConditionSimple (bool c, const char *expr, struct mlib_source_location here)
+{
+   if (!c) {
+      fprintf (stderr, "%s:%d: in [%s]: Check condition ⟨%s⟩ failed\n", here.file, here.lineno, here.func, expr);
+      fflush (stderr);
+      abort ();
+   }
+}
+
+// Implement integer comparison checks
+static inline void
+_mlibCheckIntCmp (enum mlib_cmp_result cres, // The cmp result to check
+                  bool cond,                 // Whether we expect the cmp result to match `cres`
+                  const char *operator_str,
+                  struct mlib_upsized_integer left,
+                  struct mlib_upsized_integer right,
+                  const char *left_expr,
+                  const char *right_expr,
+                  struct mlib_source_location here)
+{
+   if (((mlib_cmp) (left, right, 0) == cres) != cond) {
+      fprintf (stderr,
+               "%s:%d: in [%s]: Check [⟨%s⟩ %s ⟨%s⟩] failed:\n",
+               here.file,
+               here.lineno,
+               here.func,
+               left_expr,
+               operator_str,
+               right_expr);
+      fprintf (stderr, "    ");
+      if (left.is_signed) {
+         fprintf (stderr, "%lld", (long long) left.i.s);
+      } else {
+         fprintf (stderr, "%llu", (unsigned long long) left.i.u);
+      }
+      fprintf (stderr, " ⟨%s⟩\n", left_expr);
+      fprintf (stderr, "    ");
+      if (right.is_signed) {
+         fprintf (stderr, "%lld", (long long) right.i.s);
+      } else {
+         fprintf (stderr, "%llu", (unsigned long long) right.i.u);
+      }
+      fprintf (stderr, " ⟨%s⟩\n", right_expr);
+      fflush (stderr);
+      abort ();
+   }
+}
+
+// Pointer-comparison
+static inline void
+_mlibCheckPtrEq (
+   const void *left, const void *right, const char *left_expr, const char *right_expr, struct mlib_source_location here)
+{
+   if (left != right) {
+      fprintf (stderr,
+               "%s:%d: in [%s]: Check [⟨%s⟩ pointer-equal ⟨%s⟩] failed:\n",
+               here.file,
+               here.lineno,
+               here.func,
+               left_expr,
+               right_expr);
+      fprintf (stderr,
+               "    %p ⟨%s⟩\n"
+               "  ≠ %p ⟨%s⟩\n",
+               left,
+               left_expr,
+               right,
+               right_expr);
+      fflush (stderr);
+      abort ();
+   }
+}
+
+// String-comparison
+static inline void
+_mlibCheckStrEq (
+   const char *left, const char *right, const char *left_expr, const char *right_expr, struct mlib_source_location here)
+{
+   if (strcmp (left, right)) {
+      fprintf (stderr,
+               "%s:%d: in [%s]: Check [⟨%s⟩ str-equal ⟨%s⟩] failed:\n",
+               here.file,
+               here.lineno,
+               here.func,
+               left_expr,
+               right_expr);
+      fprintf (stderr,
+               "    “%s” ⟨%s⟩\n"
+               "  ≠ “%s” ⟨%s⟩\n",
+               left,
+               left_expr,
+               right,
+               right_expr);
+      fflush (stderr);
+      abort ();
+   }
+}
diff -pruN 1.30.4-1/src/common/tests/test-common-cmp.c 2.0.2-1/src/common/tests/test-common-cmp.c
--- 1.30.4-1/src/common/tests/test-common-cmp.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/common/tests/test-common-cmp.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,308 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "TestSuite.h"
-
-#include <common-cmp-private.h>
-
-static void
-test_mcommon_cmp_equal (void)
-{
-   ASSERT (mcommon_cmp_equal_ss (0, 0));
-   ASSERT (!mcommon_cmp_equal_ss (0, -1));
-   ASSERT (!mcommon_cmp_equal_ss (0, 1));
-   ASSERT (!mcommon_cmp_equal_ss (-1, 0));
-   ASSERT (mcommon_cmp_equal_ss (-1, -1));
-   ASSERT (!mcommon_cmp_equal_ss (-1, 1));
-   ASSERT (!mcommon_cmp_equal_ss (1, 0));
-   ASSERT (!mcommon_cmp_equal_ss (1, -1));
-   ASSERT (mcommon_cmp_equal_ss (1, 1));
-
-   ASSERT (mcommon_cmp_equal_uu (0u, 0u));
-   ASSERT (!mcommon_cmp_equal_uu (0u, 1u));
-   ASSERT (!mcommon_cmp_equal_uu (1u, 0u));
-   ASSERT (mcommon_cmp_equal_uu (1u, 1u));
-
-   ASSERT (mcommon_cmp_equal_su (0, 0u));
-   ASSERT (!mcommon_cmp_equal_su (0, 1u));
-   ASSERT (!mcommon_cmp_equal_su (-1, 0u));
-   ASSERT (!mcommon_cmp_equal_su (-1, 1u));
-   ASSERT (!mcommon_cmp_equal_su (1, 0u));
-   ASSERT (mcommon_cmp_equal_su (1, 1u));
-
-   ASSERT (mcommon_cmp_equal_us (0u, 0));
-   ASSERT (!mcommon_cmp_equal_us (0u, -1));
-   ASSERT (!mcommon_cmp_equal_us (0u, 1));
-   ASSERT (!mcommon_cmp_equal_us (1u, 0));
-   ASSERT (!mcommon_cmp_equal_us (1u, -1));
-   ASSERT (mcommon_cmp_equal_us (1u, 1));
-}
-
-static void
-test_mcommon_cmp_not_equal (void)
-{
-   ASSERT (!mcommon_cmp_not_equal_ss (0, 0));
-   ASSERT (mcommon_cmp_not_equal_ss (0, -1));
-   ASSERT (mcommon_cmp_not_equal_ss (0, 1));
-   ASSERT (mcommon_cmp_not_equal_ss (-1, 0));
-   ASSERT (!mcommon_cmp_not_equal_ss (-1, -1));
-   ASSERT (mcommon_cmp_not_equal_ss (-1, 1));
-   ASSERT (mcommon_cmp_not_equal_ss (1, 0));
-   ASSERT (mcommon_cmp_not_equal_ss (1, -1));
-   ASSERT (!mcommon_cmp_not_equal_ss (1, 1));
-
-   ASSERT (!mcommon_cmp_not_equal_uu (0u, 0u));
-   ASSERT (mcommon_cmp_not_equal_uu (0u, 1u));
-   ASSERT (mcommon_cmp_not_equal_uu (1u, 0u));
-   ASSERT (!mcommon_cmp_not_equal_uu (1u, 1u));
-
-   ASSERT (!mcommon_cmp_not_equal_su (0, 0u));
-   ASSERT (mcommon_cmp_not_equal_su (0, 1u));
-   ASSERT (mcommon_cmp_not_equal_su (-1, 0u));
-   ASSERT (mcommon_cmp_not_equal_su (-1, 1u));
-   ASSERT (mcommon_cmp_not_equal_su (1, 0u));
-   ASSERT (!mcommon_cmp_not_equal_su (1, 1u));
-
-   ASSERT (!mcommon_cmp_not_equal_us (0u, 0));
-   ASSERT (mcommon_cmp_not_equal_us (0u, -1));
-   ASSERT (mcommon_cmp_not_equal_us (0u, 1));
-   ASSERT (mcommon_cmp_not_equal_us (1u, 0));
-   ASSERT (mcommon_cmp_not_equal_us (1u, -1));
-   ASSERT (!mcommon_cmp_not_equal_us (1u, 1));
-}
-
-static void
-test_mcommon_cmp_less (void)
-{
-   ASSERT (!mcommon_cmp_less_ss (0, 0));
-   ASSERT (!mcommon_cmp_less_ss (0, -1));
-   ASSERT (mcommon_cmp_less_ss (0, 1));
-   ASSERT (mcommon_cmp_less_ss (-1, 0));
-   ASSERT (!mcommon_cmp_less_ss (-1, -1));
-   ASSERT (mcommon_cmp_less_ss (-1, 1));
-   ASSERT (!mcommon_cmp_less_ss (1, 0));
-   ASSERT (!mcommon_cmp_less_ss (1, -1));
-   ASSERT (!mcommon_cmp_less_ss (1, 1));
-
-   ASSERT (!mcommon_cmp_less_uu (0u, 0u));
-   ASSERT (mcommon_cmp_less_uu (0u, 1u));
-   ASSERT (!mcommon_cmp_less_uu (1u, 0u));
-   ASSERT (!mcommon_cmp_less_uu (1u, 1u));
-
-   ASSERT (!mcommon_cmp_less_su (0, 0u));
-   ASSERT (mcommon_cmp_less_su (0, 1u));
-   ASSERT (mcommon_cmp_less_su (-1, 0u));
-   ASSERT (mcommon_cmp_less_su (-1, 1u));
-   ASSERT (!mcommon_cmp_less_su (1, 0u));
-   ASSERT (!mcommon_cmp_less_su (1, 1u));
-
-   ASSERT (!mcommon_cmp_less_us (0u, 0));
-   ASSERT (!mcommon_cmp_less_us (0u, -1));
-   ASSERT (mcommon_cmp_less_us (0u, 1));
-   ASSERT (!mcommon_cmp_less_us (1u, 0));
-   ASSERT (!mcommon_cmp_less_us (1u, -1));
-   ASSERT (!mcommon_cmp_less_us (1u, 1));
-}
-
-static void
-test_mcommon_cmp_greater (void)
-{
-   ASSERT (!mcommon_cmp_greater_ss (0, 0));
-   ASSERT (mcommon_cmp_greater_ss (0, -1));
-   ASSERT (!mcommon_cmp_greater_ss (0, 1));
-   ASSERT (!mcommon_cmp_greater_ss (-1, 0));
-   ASSERT (!mcommon_cmp_greater_ss (-1, -1));
-   ASSERT (!mcommon_cmp_greater_ss (-1, 1));
-   ASSERT (mcommon_cmp_greater_ss (1, 0));
-   ASSERT (mcommon_cmp_greater_ss (1, -1));
-   ASSERT (!mcommon_cmp_greater_ss (1, 1));
-
-   ASSERT (!mcommon_cmp_greater_uu (0u, 0u));
-   ASSERT (!mcommon_cmp_greater_uu (0u, 1u));
-   ASSERT (mcommon_cmp_greater_uu (1u, 0u));
-   ASSERT (!mcommon_cmp_greater_uu (1u, 1u));
-
-   ASSERT (!mcommon_cmp_greater_su (0, 0u));
-   ASSERT (!mcommon_cmp_greater_su (0, 1u));
-   ASSERT (!mcommon_cmp_greater_su (-1, 0u));
-   ASSERT (!mcommon_cmp_greater_su (-1, 1u));
-   ASSERT (mcommon_cmp_greater_su (1, 0u));
-   ASSERT (!mcommon_cmp_greater_su (1, 1u));
-
-   ASSERT (!mcommon_cmp_greater_us (0u, 0));
-   ASSERT (mcommon_cmp_greater_us (0u, -1));
-   ASSERT (!mcommon_cmp_greater_us (0u, 1));
-   ASSERT (mcommon_cmp_greater_us (1u, 0));
-   ASSERT (mcommon_cmp_greater_us (1u, -1));
-   ASSERT (!mcommon_cmp_greater_us (1u, 1));
-}
-
-static void
-test_mcommon_cmp_less_equal (void)
-{
-   ASSERT (mcommon_cmp_less_equal_ss (0, 0));
-   ASSERT (!mcommon_cmp_less_equal_ss (0, -1));
-   ASSERT (mcommon_cmp_less_equal_ss (0, 1));
-   ASSERT (mcommon_cmp_less_equal_ss (-1, 0));
-   ASSERT (mcommon_cmp_less_equal_ss (-1, -1));
-   ASSERT (mcommon_cmp_less_equal_ss (-1, 1));
-   ASSERT (!mcommon_cmp_less_equal_ss (1, 0));
-   ASSERT (!mcommon_cmp_less_equal_ss (1, -1));
-   ASSERT (mcommon_cmp_less_equal_ss (1, 1));
-
-   ASSERT (mcommon_cmp_less_equal_uu (0u, 0u));
-   ASSERT (mcommon_cmp_less_equal_uu (0u, 1u));
-   ASSERT (!mcommon_cmp_less_equal_uu (1u, 0u));
-   ASSERT (mcommon_cmp_less_equal_uu (1u, 1u));
-
-   ASSERT (mcommon_cmp_less_equal_su (0, 0u));
-   ASSERT (mcommon_cmp_less_equal_su (0, 1u));
-   ASSERT (mcommon_cmp_less_equal_su (-1, 0u));
-   ASSERT (mcommon_cmp_less_equal_su (-1, 1u));
-   ASSERT (!mcommon_cmp_less_equal_su (1, 0u));
-   ASSERT (mcommon_cmp_less_equal_su (1, 1u));
-
-   ASSERT (mcommon_cmp_less_equal_us (0u, 0));
-   ASSERT (!mcommon_cmp_less_equal_us (0u, -1));
-   ASSERT (mcommon_cmp_less_equal_us (0u, 1));
-   ASSERT (!mcommon_cmp_less_equal_us (1u, 0));
-   ASSERT (!mcommon_cmp_less_equal_us (1u, -1));
-   ASSERT (mcommon_cmp_less_equal_us (1u, 1));
-}
-
-static void
-test_mcommon_cmp_greater_equal (void)
-{
-   ASSERT (mcommon_cmp_greater_equal_ss (0, 0));
-   ASSERT (mcommon_cmp_greater_equal_ss (0, -1));
-   ASSERT (!mcommon_cmp_greater_equal_ss (0, 1));
-   ASSERT (!mcommon_cmp_greater_equal_ss (-1, 0));
-   ASSERT (mcommon_cmp_greater_equal_ss (-1, -1));
-   ASSERT (!mcommon_cmp_greater_equal_ss (-1, 1));
-   ASSERT (mcommon_cmp_greater_equal_ss (1, 0));
-   ASSERT (mcommon_cmp_greater_equal_ss (1, -1));
-   ASSERT (mcommon_cmp_greater_equal_ss (1, 1));
-
-   ASSERT (mcommon_cmp_greater_equal_uu (0u, 0u));
-   ASSERT (!mcommon_cmp_greater_equal_uu (0u, 1u));
-   ASSERT (mcommon_cmp_greater_equal_uu (1u, 0u));
-   ASSERT (mcommon_cmp_greater_equal_uu (1u, 1u));
-
-   ASSERT (mcommon_cmp_greater_equal_su (0, 0u));
-   ASSERT (!mcommon_cmp_greater_equal_su (0, 1u));
-   ASSERT (!mcommon_cmp_greater_equal_su (-1, 0u));
-   ASSERT (!mcommon_cmp_greater_equal_su (-1, 1u));
-   ASSERT (mcommon_cmp_greater_equal_su (1, 0u));
-   ASSERT (mcommon_cmp_greater_equal_su (1, 1u));
-
-   ASSERT (mcommon_cmp_greater_equal_us (0u, 0));
-   ASSERT (mcommon_cmp_greater_equal_us (0u, -1));
-   ASSERT (!mcommon_cmp_greater_equal_us (0u, 1));
-   ASSERT (mcommon_cmp_greater_equal_us (1u, 0));
-   ASSERT (mcommon_cmp_greater_equal_us (1u, -1));
-   ASSERT (mcommon_cmp_greater_equal_us (1u, 1));
-}
-
-/* Sanity check: ensure ssize_t limits are as expected relative to size_t. */
-BSON_STATIC_ASSERT2 (ssize_t_size_min_check, SSIZE_MIN + 1 == -SSIZE_MAX);
-BSON_STATIC_ASSERT2 (ssize_t_size_max_check, (size_t) SSIZE_MAX <= SIZE_MAX);
-
-static void
-test_mcommon_in_range (void)
-{
-   const int64_t int8_min = INT8_MIN;
-   const int64_t int8_max = INT8_MAX;
-   const int64_t int32_min = INT32_MIN;
-   const int64_t int32_max = INT32_MAX;
-
-   const uint64_t uint8_max = UINT8_MAX;
-   const uint64_t uint32_max = UINT32_MAX;
-
-   const ssize_t ssize_min = SSIZE_MIN;
-   const ssize_t ssize_max = SSIZE_MAX;
-
-   ASSERT (!mcommon_in_range_signed (int8_t, int8_min - 1));
-   ASSERT (mcommon_in_range_signed (int8_t, int8_min));
-   ASSERT (mcommon_in_range_signed (int8_t, 0));
-   ASSERT (mcommon_in_range_signed (int8_t, int8_max));
-   ASSERT (!mcommon_in_range_signed (int8_t, int8_max + 1));
-
-   ASSERT (mcommon_in_range_unsigned (int8_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (int8_t, (uint64_t) int8_max));
-   ASSERT (!mcommon_in_range_unsigned (int8_t, (uint64_t) (int8_max + 1)));
-
-   ASSERT (!mcommon_in_range_signed (uint8_t, int8_min - 1));
-   ASSERT (!mcommon_in_range_signed (uint8_t, int8_min));
-   ASSERT (mcommon_in_range_signed (uint8_t, 0));
-   ASSERT (mcommon_in_range_signed (uint8_t, int8_max));
-   ASSERT (mcommon_in_range_signed (uint8_t, int8_max + 1));
-   ASSERT (mcommon_in_range_signed (uint8_t, (int64_t) uint8_max));
-   ASSERT (!mcommon_in_range_signed (uint8_t, (int64_t) uint8_max + 1));
-
-   ASSERT (mcommon_in_range_unsigned (uint8_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (uint8_t, uint8_max));
-   ASSERT (!mcommon_in_range_unsigned (uint8_t, uint8_max + 1u));
-
-   ASSERT (!mcommon_in_range_signed (int32_t, int32_min - 1));
-   ASSERT (mcommon_in_range_signed (int32_t, int32_min));
-   ASSERT (mcommon_in_range_signed (int32_t, 0));
-   ASSERT (mcommon_in_range_signed (int32_t, int32_max));
-   ASSERT (!mcommon_in_range_signed (int32_t, int32_max + 1));
-
-   ASSERT (mcommon_in_range_unsigned (int32_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (int32_t, (uint64_t) int32_max));
-   ASSERT (!mcommon_in_range_unsigned (int32_t, (uint64_t) (int32_max + 1)));
-
-   ASSERT (!mcommon_in_range_signed (uint32_t, int32_min - 1));
-   ASSERT (!mcommon_in_range_signed (uint32_t, int32_min));
-   ASSERT (mcommon_in_range_signed (uint32_t, 0));
-   ASSERT (mcommon_in_range_signed (uint32_t, int32_max));
-   ASSERT (mcommon_in_range_signed (uint32_t, int32_max + 1));
-   ASSERT (mcommon_in_range_signed (uint32_t, (int64_t) uint32_max));
-   ASSERT (!mcommon_in_range_signed (uint32_t, (int64_t) uint32_max + 1));
-
-   ASSERT (mcommon_in_range_unsigned (uint32_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (uint32_t, uint32_max));
-   ASSERT (!mcommon_in_range_unsigned (uint32_t, uint32_max + 1u));
-
-   ASSERT (mcommon_in_range_signed (ssize_t, ssize_min));
-   ASSERT (mcommon_in_range_signed (ssize_t, 0));
-   ASSERT (mcommon_in_range_signed (ssize_t, ssize_max));
-
-   ASSERT (mcommon_in_range_unsigned (ssize_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (ssize_t, (size_t) ssize_max));
-   ASSERT (!mcommon_in_range_unsigned (ssize_t, (size_t) ssize_max + 1u));
-
-   ASSERT (!mcommon_in_range_signed (size_t, ssize_min));
-   ASSERT (mcommon_in_range_signed (size_t, 0));
-   ASSERT (mcommon_in_range_signed (size_t, ssize_max));
-
-   ASSERT (mcommon_in_range_unsigned (size_t, 0u));
-   ASSERT (mcommon_in_range_unsigned (size_t, (size_t) ssize_max));
-   ASSERT (mcommon_in_range_unsigned (size_t, (size_t) ssize_max + 1u));
-}
-
-void
-test_mcommon_cmp_install (TestSuite *suite)
-{
-   TestSuite_Add (suite, "/mcommon/cmp/equal", test_mcommon_cmp_equal);
-   TestSuite_Add (suite, "/mcommon/cmp/not_equal", test_mcommon_cmp_not_equal);
-   TestSuite_Add (suite, "/mcommon/cmp/less", test_mcommon_cmp_less);
-   TestSuite_Add (suite, "/mcommon/cmp/greater", test_mcommon_cmp_greater);
-   TestSuite_Add (suite, "/mcommon/cmp/less_equal", test_mcommon_cmp_less_equal);
-   TestSuite_Add (suite, "/mcommon/cmp/greater_equal", test_mcommon_cmp_greater_equal);
-   TestSuite_Add (suite, "/mcommon/cmp/in_range", test_mcommon_in_range);
-}
diff -pruN 1.30.4-1/src/common/tests/test-mlib.c 2.0.2-1/src/common/tests/test-mlib.c
--- 1.30.4-1/src/common/tests/test-mlib.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/common/tests/test-mlib.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,662 @@
+#include "TestSuite.h"
+
+#include <mlib/intutil.h>
+#include <mlib/config.h>
+#include <mlib/intencode.h>
+#include <mlib/loop.h>
+#include <mlib/cmp.h>
+#include <mlib/test.h>
+#include <mlib/ckdint.h>
+
+#include <stddef.h>
+
+mlib_diagnostic_push (); // We don't set any diagnostics, we just want to make sure it compiles
+
+// Not relevant, we just want to test that it compiles:
+mlib_msvc_warning (disable : 4507);
+
+static void
+_test_checks (void)
+{
+   // Simple condiion
+   mlib_check (true);
+   mlib_assert_aborts () {
+      mlib_check (false);
+   }
+   // str_eq
+   mlib_check ("foo", str_eq, "foo");
+   mlib_assert_aborts () {
+      mlib_check ("foo", str_eq, "bar");
+   }
+   // ptr_eq
+   const char *s = "foo";
+   mlib_check (s, ptr_eq, s);
+   mlib_assert_aborts () {
+      mlib_check (s, ptr_eq, NULL);
+   }
+   // eq
+   mlib_check (4, eq, 4);
+   mlib_assert_aborts () {
+      mlib_check (1, eq, 4);
+   }
+   // neq
+   mlib_check (1, neq, 4);
+   mlib_assert_aborts () {
+      mlib_check (1, neq, 1);
+   }
+}
+
+static void
+_test_minmax (void)
+{
+   mlib_static_assert (mlib_minof (unsigned) == 0);
+   // Ambiguous signedness, still works:
+   mlib_static_assert (mlib_minof (char) == CHAR_MIN);
+   mlib_static_assert (mlib_maxof (char) == CHAR_MAX);
+
+   mlib_static_assert (mlib_minof (uint8_t) == 0);
+   mlib_static_assert (mlib_maxof (uint8_t) == UINT8_MAX);
+   mlib_static_assert (mlib_minof (uint16_t) == 0);
+   mlib_static_assert (mlib_maxof (uint16_t) == UINT16_MAX);
+   mlib_static_assert (mlib_minof (uint32_t) == 0);
+   mlib_static_assert (mlib_maxof (uint32_t) == UINT32_MAX);
+   mlib_static_assert (mlib_minof (uint64_t) == 0);
+   mlib_static_assert (mlib_maxof (uint64_t) == UINT64_MAX);
+
+   mlib_static_assert (mlib_maxof (size_t) == SIZE_MAX);
+   mlib_static_assert (mlib_maxof (ptrdiff_t) == PTRDIFF_MAX);
+
+   mlib_static_assert (mlib_minof (int) == INT_MIN);
+   mlib_static_assert (mlib_maxof (int) == INT_MAX);
+   mlib_static_assert (mlib_maxof (unsigned) == UINT_MAX);
+
+   mlib_static_assert (mlib_is_signed (int));
+   mlib_static_assert (mlib_is_signed (signed char));
+   mlib_static_assert (mlib_is_signed (int8_t));
+   mlib_static_assert (!mlib_is_signed (uint8_t));
+   mlib_static_assert (mlib_is_signed (int16_t));
+   mlib_static_assert (!mlib_is_signed (uint16_t));
+   mlib_static_assert (mlib_is_signed (int32_t));
+   mlib_static_assert (!mlib_is_signed (uint32_t));
+   mlib_static_assert (mlib_is_signed (int64_t));
+   mlib_static_assert (!mlib_is_signed (uint64_t));
+   // Ambiguous signedness:
+   mlib_static_assert (mlib_is_signed (char) || !mlib_is_signed (char));
+}
+
+static void
+_test_upsize (void)
+{
+   struct mlib_upsized_integer up;
+   up = mlib_upsize_integer (31);
+   ASSERT (up.is_signed);
+   ASSERT (up.i.s == 31);
+
+   // Casting from the max unsigned integer generates an unsigned upsized integer:
+   up = mlib_upsize_integer ((uintmax_t) 1729);
+   ASSERT (!up.is_signed);
+   ASSERT (up.i.u == 1729);
+
+   // Max signed integer makes a signed upsized integer:
+   up = mlib_upsize_integer ((intmax_t) 1729);
+   ASSERT (up.is_signed);
+   ASSERT (up.i.s == 1729);
+
+   // From a literal:
+   up = mlib_upsize_integer (UINTMAX_MAX);
+   ASSERT (!up.is_signed);
+   ASSERT (up.i.u == UINTMAX_MAX);
+}
+
+static void
+_test_cmp (void)
+{
+   mlib_check (mlib_cmp (1, 2) == mlib_less);
+   mlib_check (mlib_cmp (1, 2) < 0);
+   mlib_check (mlib_cmp (1, <, 2));
+   mlib_check (mlib_cmp (2, 1) == mlib_greater);
+   mlib_check (mlib_cmp (2, 1) > 0);
+   mlib_check (mlib_cmp (2, >, 1));
+   mlib_check (mlib_cmp (1, 1) == mlib_equal);
+   mlib_check (mlib_cmp (1, 1) == 0);
+   mlib_check (mlib_cmp (1, ==, 1));
+
+   ASSERT (mlib_cmp (0, ==, 0));
+   ASSERT (!mlib_cmp (0, ==, -1));
+   ASSERT (!mlib_cmp (0, ==, 1));
+   ASSERT (!mlib_cmp (-1, ==, 0));
+   ASSERT (mlib_cmp (-1, ==, -1));
+   ASSERT (!mlib_cmp (-1, ==, 1));
+   ASSERT (!mlib_cmp (1, ==, 0));
+   ASSERT (!mlib_cmp (1, ==, -1));
+   ASSERT (mlib_cmp (1, ==, 1));
+
+   ASSERT (mlib_cmp (0u, ==, 0u));
+   ASSERT (!mlib_cmp (0u, ==, 1u));
+   ASSERT (!mlib_cmp (1u, ==, 0u));
+   ASSERT (mlib_cmp (1u, ==, 1u));
+
+   ASSERT (mlib_cmp (0, ==, 0u));
+   ASSERT (!mlib_cmp (0, ==, 1u));
+   ASSERT (!mlib_cmp (-1, ==, 0u));
+   ASSERT (!mlib_cmp (-1, ==, 1u));
+   ASSERT (!mlib_cmp (1, ==, 0u));
+   ASSERT (mlib_cmp (1, ==, 1u));
+
+   ASSERT (mlib_cmp (0u, ==, 0));
+   ASSERT (!mlib_cmp (0u, ==, -1));
+   ASSERT (!mlib_cmp (0u, ==, 1));
+   ASSERT (!mlib_cmp (1u, ==, 0));
+   ASSERT (!mlib_cmp (1u, ==, -1));
+   ASSERT (mlib_cmp (1u, ==, 1));
+
+   ASSERT (!mlib_cmp (0, !=, 0));
+   ASSERT (mlib_cmp (0, !=, -1));
+   ASSERT (mlib_cmp (0, !=, 1));
+   ASSERT (mlib_cmp (-1, !=, 0));
+   ASSERT (!mlib_cmp (-1, !=, -1));
+   ASSERT (mlib_cmp (-1, !=, 1));
+   ASSERT (mlib_cmp (1, !=, 0));
+   ASSERT (mlib_cmp (1, !=, -1));
+   ASSERT (!mlib_cmp (1, !=, 1));
+
+   ASSERT (!mlib_cmp (0u, !=, 0u));
+   ASSERT (mlib_cmp (0u, !=, 1u));
+   ASSERT (mlib_cmp (1u, !=, 0u));
+   ASSERT (!mlib_cmp (1u, !=, 1u));
+
+   ASSERT (!mlib_cmp (0, !=, 0u));
+   ASSERT (mlib_cmp (0, !=, 1u));
+   ASSERT (mlib_cmp (-1, !=, 0u));
+   ASSERT (mlib_cmp (-1, !=, 1u));
+   ASSERT (mlib_cmp (1, !=, 0u));
+   ASSERT (!mlib_cmp (1, !=, 1u));
+
+   ASSERT (!mlib_cmp (0u, !=, 0));
+   ASSERT (mlib_cmp (0u, !=, -1));
+   ASSERT (mlib_cmp (0u, !=, 1));
+   ASSERT (mlib_cmp (1u, !=, 0));
+   ASSERT (mlib_cmp (1u, !=, -1));
+   ASSERT (!mlib_cmp (1u, !=, 1));
+
+   ASSERT (!mlib_cmp (0, <, 0));
+   ASSERT (!mlib_cmp (0, <, -1));
+   ASSERT (mlib_cmp (0, <, 1));
+   ASSERT (mlib_cmp (-1, <, 0));
+   ASSERT (!mlib_cmp (-1, <, -1));
+   ASSERT (mlib_cmp (-1, <, 1));
+   ASSERT (!mlib_cmp (1, <, 0));
+   ASSERT (!mlib_cmp (1, <, -1));
+   ASSERT (!mlib_cmp (1, <, 1));
+
+   ASSERT (!mlib_cmp (0u, <, 0u));
+   ASSERT (mlib_cmp (0u, <, 1u));
+   ASSERT (!mlib_cmp (1u, <, 0u));
+   ASSERT (!mlib_cmp (1u, <, 1u));
+
+   ASSERT (!mlib_cmp (0, <, 0u));
+   ASSERT (mlib_cmp (0, <, 1u));
+   ASSERT (mlib_cmp (-1, <, 0u));
+   ASSERT (mlib_cmp (-1, <, 1u));
+   ASSERT (!mlib_cmp (1, <, 0u));
+   ASSERT (!mlib_cmp (1, <, 1u));
+
+   ASSERT (!mlib_cmp (0u, <, 0));
+   ASSERT (!mlib_cmp (0u, <, -1));
+   ASSERT (mlib_cmp (0u, <, 1));
+   ASSERT (!mlib_cmp (1u, <, 0));
+   ASSERT (!mlib_cmp (1u, <, -1));
+   ASSERT (!mlib_cmp (1u, <, 1));
+
+   ASSERT (!mlib_cmp (0, >, 0));
+   ASSERT (mlib_cmp (0, >, -1));
+   ASSERT (!mlib_cmp (0, >, 1));
+   ASSERT (!mlib_cmp (-1, >, 0));
+   ASSERT (!mlib_cmp (-1, >, -1));
+   ASSERT (!mlib_cmp (-1, >, 1));
+   ASSERT (mlib_cmp (1, >, 0));
+   ASSERT (mlib_cmp (1, >, -1));
+   ASSERT (!mlib_cmp (1, >, 1));
+
+   ASSERT (!mlib_cmp (0u, >, 0u));
+   ASSERT (!mlib_cmp (0u, >, 1u));
+   ASSERT (mlib_cmp (1u, >, 0u));
+   ASSERT (!mlib_cmp (1u, >, 1u));
+
+   ASSERT (!mlib_cmp (0, >, 0u));
+   ASSERT (!mlib_cmp (0, >, 1u));
+   ASSERT (!mlib_cmp (-1, >, 0u));
+   ASSERT (!mlib_cmp (-1, >, 1u));
+   ASSERT (mlib_cmp (1, >, 0u));
+   ASSERT (!mlib_cmp (1, >, 1u));
+
+   ASSERT (!mlib_cmp (0u, >, 0));
+   ASSERT (mlib_cmp (0u, >, -1));
+   ASSERT (!mlib_cmp (0u, >, 1));
+   ASSERT (mlib_cmp (1u, >, 0));
+   ASSERT (mlib_cmp (1u, >, -1));
+   ASSERT (!mlib_cmp (1u, >, 1));
+
+   ASSERT (mlib_cmp (0, <=, 0));
+   ASSERT (!mlib_cmp (0, <=, -1));
+   ASSERT (mlib_cmp (0, <=, 1));
+   ASSERT (mlib_cmp (-1, <=, 0));
+   ASSERT (mlib_cmp (-1, <=, -1));
+   ASSERT (mlib_cmp (-1, <=, 1));
+   ASSERT (!mlib_cmp (1, <=, 0));
+   ASSERT (!mlib_cmp (1, <=, -1));
+   ASSERT (mlib_cmp (1, <=, 1));
+
+   ASSERT (mlib_cmp (0u, <=, 0u));
+   ASSERT (mlib_cmp (0u, <=, 1u));
+   ASSERT (!mlib_cmp (1u, <=, 0u));
+   ASSERT (mlib_cmp (1u, <=, 1u));
+
+   ASSERT (mlib_cmp (0, <=, 0u));
+   ASSERT (mlib_cmp (0, <=, 1u));
+   ASSERT (mlib_cmp (-1, <=, 0u));
+   ASSERT (mlib_cmp (-1, <=, 1u));
+   ASSERT (!mlib_cmp (1, <=, 0u));
+   ASSERT (mlib_cmp (1, <=, 1u));
+
+   ASSERT (mlib_cmp (0u, <=, 0));
+   ASSERT (!mlib_cmp (0u, <=, -1));
+   ASSERT (mlib_cmp (0u, <=, 1));
+   ASSERT (!mlib_cmp (1u, <=, 0));
+   ASSERT (!mlib_cmp (1u, <=, -1));
+   ASSERT (mlib_cmp (1u, <=, 1));
+
+   ASSERT (mlib_cmp (0, >=, 0));
+   ASSERT (mlib_cmp (0, >=, -1));
+   ASSERT (!mlib_cmp (0, >=, 1));
+   ASSERT (!mlib_cmp (-1, >=, 0));
+   ASSERT (mlib_cmp (-1, >=, -1));
+   ASSERT (!mlib_cmp (-1, >=, 1));
+   ASSERT (mlib_cmp (1, >=, 0));
+   ASSERT (mlib_cmp (1, >=, -1));
+   ASSERT (mlib_cmp (1, >=, 1));
+
+   ASSERT (mlib_cmp (0u, >=, 0u));
+   ASSERT (!mlib_cmp (0u, >=, 1u));
+   ASSERT (mlib_cmp (1u, >=, 0u));
+   ASSERT (mlib_cmp (1u, >=, 1u));
+
+   ASSERT (mlib_cmp (0, >=, 0u));
+   ASSERT (!mlib_cmp (0, >=, 1u));
+   ASSERT (!mlib_cmp (-1, >=, 0u));
+   ASSERT (!mlib_cmp (-1, >=, 1u));
+   ASSERT (mlib_cmp (1, >=, 0u));
+   ASSERT (mlib_cmp (1, >=, 1u));
+
+   ASSERT (mlib_cmp (0u, >=, 0));
+   ASSERT (mlib_cmp (0u, >=, -1));
+   ASSERT (!mlib_cmp (0u, >=, 1));
+   ASSERT (mlib_cmp (1u, >=, 0));
+   ASSERT (mlib_cmp (1u, >=, -1));
+   ASSERT (mlib_cmp (1u, >=, 1));
+
+   size_t big_size = SIZE_MAX;
+   ASSERT (mlib_cmp (42, big_size) == mlib_less);
+   ASSERT (mlib_cmp (big_size, big_size) == mlib_equal);
+   ASSERT (mlib_cmp (big_size, SSIZE_MIN) == mlib_greater);
+   uint8_t smol = 7;
+   ASSERT (mlib_cmp (smol, SIZE_MAX) == mlib_less);
+   int8_t ismol = -4;
+   ASSERT (mlib_cmp (ismol, big_size) == mlib_less);
+
+   /// Example: Getting the correct answer:
+   // Unintuitive result due to integer promotion:
+   mlib_diagnostic_push ();
+   mlib_gnu_warning_disable ("-Wsign-compare");
+   ASSERT (-27 > 20u);
+   mlib_diagnostic_pop ();
+   // mlib_cmp produces the correct answer:
+   ASSERT (mlib_cmp (-27, <, 20u));
+}
+
+static void
+_test_in_range (void)
+{
+   const int64_t int8_min = INT8_MIN;
+   const int64_t int8_max = INT8_MAX;
+   const int64_t int32_min = INT32_MIN;
+   const int64_t int32_max = INT32_MAX;
+
+   const uint64_t uint8_max = UINT8_MAX;
+   const uint64_t uint32_max = UINT32_MAX;
+
+   const ssize_t ssize_min = SSIZE_MIN;
+   const ssize_t ssize_max = SSIZE_MAX;
+
+   ASSERT (!mlib_in_range (int8_t, 1729));
+   ASSERT (!mlib_in_range (int, SIZE_MAX));
+   ASSERT (mlib_in_range (size_t, SIZE_MAX));
+   ASSERT (!mlib_in_range (size_t, -42));
+   ASSERT (mlib_in_range (int8_t, -42));
+   ASSERT (mlib_in_range (int8_t, -128));
+   ASSERT (!mlib_in_range (int8_t, -129));
+
+   ASSERT (!mlib_in_range (int8_t, int8_min - 1));
+   ASSERT (mlib_in_range (int8_t, int8_min));
+   ASSERT (mlib_in_range (int8_t, 0));
+   ASSERT (mlib_in_range (int8_t, int8_max));
+   ASSERT (!mlib_in_range (int8_t, int8_max + 1));
+
+   ASSERT (mlib_in_range (int8_t, 0u));
+   ASSERT (mlib_in_range (int8_t, (uint64_t) int8_max));
+   ASSERT (!mlib_in_range (int8_t, (uint64_t) (int8_max + 1)));
+
+   ASSERT (!mlib_in_range (uint8_t, int8_min - 1));
+   ASSERT (!mlib_in_range (uint8_t, int8_min));
+   ASSERT (mlib_in_range (uint8_t, 0));
+   ASSERT (mlib_in_range (uint8_t, int8_max));
+   ASSERT (mlib_in_range (uint8_t, int8_max + 1));
+   ASSERT (mlib_in_range (uint8_t, (int64_t) uint8_max));
+   ASSERT (!mlib_in_range (uint8_t, (int64_t) uint8_max + 1));
+
+   ASSERT (mlib_in_range (uint8_t, 0u));
+   ASSERT (mlib_in_range (uint8_t, uint8_max));
+   ASSERT (!mlib_in_range (uint8_t, uint8_max + 1u));
+
+   ASSERT (!mlib_in_range (int32_t, int32_min - 1));
+   ASSERT (mlib_in_range (int32_t, int32_min));
+   ASSERT (mlib_in_range (int32_t, 0));
+   ASSERT (mlib_in_range (int32_t, int32_max));
+   ASSERT (!mlib_in_range (int32_t, int32_max + 1));
+
+   ASSERT (mlib_in_range (int32_t, 0u));
+   ASSERT (mlib_in_range (int32_t, (uint64_t) int32_max));
+   ASSERT (!mlib_in_range (int32_t, (uint64_t) (int32_max + 1)));
+
+   ASSERT (!mlib_in_range (uint32_t, int32_min - 1));
+   ASSERT (!mlib_in_range (uint32_t, int32_min));
+   ASSERT (mlib_in_range (uint32_t, 0));
+   ASSERT (mlib_in_range (uint32_t, int32_max));
+   ASSERT (mlib_in_range (uint32_t, int32_max + 1));
+   ASSERT (mlib_in_range (uint32_t, (int64_t) uint32_max));
+   ASSERT (!mlib_in_range (uint32_t, (int64_t) uint32_max + 1));
+
+   ASSERT (mlib_in_range (uint32_t, 0u));
+   ASSERT (mlib_in_range (uint32_t, uint32_max));
+   ASSERT (!mlib_in_range (uint32_t, uint32_max + 1u));
+
+   ASSERT (mlib_in_range (ssize_t, ssize_min));
+   ASSERT (mlib_in_range (ssize_t, 0));
+   ASSERT (mlib_in_range (ssize_t, ssize_max));
+
+   ASSERT (mlib_in_range (ssize_t, 0u));
+   ASSERT (mlib_in_range (ssize_t, (size_t) ssize_max));
+   ASSERT (!mlib_in_range (ssize_t, (size_t) ssize_max + 1u));
+
+   ASSERT (!mlib_in_range (size_t, ssize_min));
+   ASSERT (mlib_in_range (size_t, 0));
+   ASSERT (mlib_in_range (size_t, ssize_max));
+
+   ASSERT (mlib_in_range (size_t, 0u));
+   ASSERT (mlib_in_range (size_t, (size_t) ssize_max));
+   ASSERT (mlib_in_range (size_t, (size_t) ssize_max + 1u));
+}
+
+static void
+_test_assert_aborts (void)
+{
+   int a = 0;
+   mlib_assert_aborts () {
+      a = 4;
+      abort ();
+   }
+   // Parent process is unaffected:
+   ASSERT (a == 0);
+}
+
+static void
+_test_int_encoding (void)
+{
+   {
+      const char *buf = "\x01\x02\x03\x04";
+      const uint32_t val = mlib_read_u32le (buf);
+      mlib_check (val, eq, 0x04030201);
+   }
+
+   {
+      char buf[9] = {0};
+      char *o = mlib_write_i32le (buf, 0x01020304);
+      mlib_check (o, ptr_eq, buf + 4);
+      mlib_check (buf, str_eq, "\x04\x03\x02\x01");
+
+      o = mlib_write_i32le (o, 42);
+      mlib_check (o, ptr_eq, buf + 8);
+      mlib_check (buf, str_eq, "\x04\x03\x02\x01*");
+
+      o = mlib_write_i64le (buf, 0x0102030405060708);
+      mlib_check (o, ptr_eq, buf + 8);
+      mlib_check (buf, str_eq, "\x08\x07\x06\x05\x04\x03\x02\x01");
+   }
+}
+
+static void
+_test_foreach (void)
+{
+   int n_loops = 0;
+   mlib_foreach_urange (i, 10) {
+      fprintf (stderr, "i: %zu\n", i);
+      fprintf (stderr, "counter: %zu\n", i_counter);
+      ASSERT (i == loop.index);
+      ASSERT (loop.first == (i == 0));
+      ASSERT (loop.last == (i == 9));
+      ++n_loops;
+      (void) i;
+      ASSERT (n_loops <= 10);
+   };
+   ASSERT (n_loops == 10);
+
+   n_loops = 0;
+   mlib_foreach_urange (i, 100) {
+      if (i == 42) {
+         break;
+      }
+      ++n_loops;
+   }
+   ASSERT (n_loops == 42);
+
+   n_loops = 0;
+   mlib_foreach_urange (i, 1729) {
+      (void) i;
+      ++n_loops;
+   }
+   ASSERT (n_loops == 1729);
+
+   mlib_foreach_urange (i, 0) {
+      (void) i;
+      ASSERT (false); // Shouldn't ever enter the loop
+   }
+
+   n_loops = 0;
+   mlib_foreach_urange (i, 4, 7) {
+      ++n_loops;
+      ASSERT (i >= 4);
+      ASSERT (i < 7);
+   }
+   ASSERT (n_loops == 3);
+
+   int arr[] = {1, 2, 3};
+   int sum = 0;
+   n_loops = 0;
+   mlib_foreach_arr (int, n, arr) {
+      mlib_check (n_loops, eq, loop.index);
+      n_loops++;
+      sum += *n;
+      ASSERT (loop.first == (n == arr + 0));
+      ASSERT (loop.last == (n == arr + 2));
+   }
+   ASSERT (sum == 6);
+   ASSERT (n_loops == 3);
+}
+
+static void
+_test_cast (void)
+{
+   int a = 1729;
+   // Fine:
+   int16_t i16 = mlib_assert_narrow (int16_t, a);
+   ASSERT (i16 == 1729);
+   // Fine:
+   a = -6;
+   i16 = mlib_assert_narrow (int16_t, a);
+   ASSERT (i16 == -6);
+   // Boundary:
+   size_t sz = mlib_assert_narrow (size_t, SIZE_MAX);
+   ASSERT (sz == SIZE_MAX);
+   sz = mlib_assert_narrow (size_t, 0);
+   ASSERT (sz == 0);
+   // Boundary:
+   sz = mlib_assert_narrow (size_t, SSIZE_MAX);
+   ASSERT (sz == SSIZE_MAX);
+
+   mlib_assert_aborts () {
+      (void) mlib_assert_narrow (size_t, -4);
+   }
+   mlib_assert_aborts () {
+      (void) mlib_assert_narrow (ssize_t, SIZE_MAX);
+   }
+}
+
+// This is a "partial" test of the ckdint APIs. A fully exhaustive test set is defined
+// in `mlib/ckdint.test.cpp`
+static void
+_test_ckdint_partial (void)
+{
+   // Small signed
+   {
+      int a = 42;
+      mlib_check (!mlib_add (&a, a, 5)); // a = a + 5
+      mlib_check (a, eq, 47);
+
+      mlib_check (!mlib_add (&a, 5)); // a += 5
+      mlib_check (a, eq, 52);
+
+      // The `check` arithmetic functions should abort the process immediately
+      mlib_assert_aborts () {
+         mlib_assert_add (size_t, 41, -42);
+      }
+      mlib_assert_aborts () {
+         mlib_assert_add (ptrdiff_t, 41, SIZE_MAX);
+      }
+      // Does not abort:
+      const size_t sum = mlib_assert_add (size_t, -32, 33);
+      mlib_check (sum, eq, 1);
+
+      mlib_check (!mlib_add (&a, a, (size_t) 123456));
+      mlib_check (a, eq, 123508);
+
+      a = 4;
+      mlib_check (mlib_add (&a, a, INT_MAX)); // Indicates overflow
+      mlib_check (a, eq, INT_MIN + 3);        // Result is wrapped
+
+      a = -1;
+      mlib_check (!mlib_add (&a, a, INT_MAX));
+      mlib_check (a, eq, INT_MAX - 1);
+   }
+
+   // Small unsigned
+   {
+      unsigned a = 42;
+      mlib_check (!mlib_add (&a, a, 5));
+      mlib_check (a, eq, 47);
+
+      mlib_check (!mlib_add (&a, a, INT_MAX));
+      mlib_check (a, eq, (unsigned) INT_MAX + 47);
+   }
+
+   // Sub with small signed
+   {
+      int a = -1;
+      mlib_check (mlib_sub (&a, INT_MAX, a)); // MAX - (-1) → MAX + 1
+      mlib_check (a, eq, INT_MIN);
+
+      a = -1;
+      mlib_check (!mlib_sub (&a, INT_MIN, a)); // MIN - (-1) → MIN + 1
+      mlib_check (a, eq, INT_MIN + 1);
+   }
+
+   // Max precision tests are more interesting, because they excercise the bit-manipulation
+   // tricks in the arithmetic functions, while smaller ints are simple bounds checks
+   // ==============
+   // Maximum precision signed
+   {
+      intmax_t a = 42;
+      mlib_check (!mlib_add (&a, a, 5));
+      mlib_check (a, eq, 47);
+
+      mlib_check (mlib_add (&a, 42, INTMAX_MAX)); // Overflows
+      mlib_check (a, eq, INTMAX_MIN + 41);        // Wraps
+
+      mlib_check (!mlib_sub (&a, -1, INTMAX_MIN)); // (-N) - (-M) is always well-defined
+      mlib_check (a, eq, INTMAX_MAX);
+
+      mlib_check (mlib_sub (&a, -2, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX);
+
+      mlib_check (!mlib_sub (&a, 1, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MIN + 2);
+
+      mlib_check (!mlib_mul (&a, 1, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX);
+
+      mlib_check (mlib_mul (&a, 2, INTMAX_MAX));
+      mlib_check (a, eq, -2);
+      mlib_check (mlib_mul (&a, 3, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX - 2);
+   }
+
+   // Maximum precision unsigned
+   {
+      uintmax_t a = 42;
+      mlib_check (!mlib_add (&a, a, 5));
+      mlib_check (a, eq, 47);
+
+      a = 42;
+      mlib_check (mlib_add (&a, a, UINTMAX_MAX)); // Overflows
+      mlib_check (a, eq, 41);                     // Wraps
+
+      a = 1;
+      mlib_check (mlib_sub (&a, a, INTMAX_MAX)); // Overflows (result is negative)
+      mlib_check (a, eq, (uintmax_t) INTMAX_MAX + 3);
+
+      mlib_check (!mlib_sub (&a, -1, INTMAX_MIN)); // (-N) - (-M) is always well-defined
+      mlib_check (a, eq, INTMAX_MAX);
+
+      mlib_check (mlib_sub (&a, -2, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX);
+
+      mlib_check (mlib_sub (&a, 1, INTMAX_MAX));
+      mlib_check (a, eq, (uintmax_t) INTMAX_MAX + 3);
+
+      mlib_check (!mlib_mul (&a, 1, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX);
+
+      // Just barely enough room:
+      mlib_check (!mlib_mul (&a, 2, INTMAX_MAX));
+      mlib_check (a, eq, UINTMAX_MAX - 1);
+      // Too big:
+      mlib_check (mlib_mul (&a, 3, INTMAX_MAX));
+      mlib_check (a, eq, INTMAX_MAX - 2);
+   }
+}
+
+void
+test_mlib_install (TestSuite *suite)
+{
+   TestSuite_Add (suite, "/mlib/checks", _test_checks);
+   TestSuite_Add (suite, "/mlib/intutil/minmax", _test_minmax);
+   TestSuite_Add (suite, "/mlib/intutil/upsize", _test_upsize);
+   TestSuite_Add (suite, "/mlib/cmp", _test_cmp);
+   TestSuite_Add (suite, "/mlib/in-range", _test_in_range);
+   TestSuite_Add (suite, "/mlib/assert-aborts", _test_assert_aborts);
+   TestSuite_Add (suite, "/mlib/int-encoding", _test_int_encoding);
+   TestSuite_Add (suite, "/mlib/foreach", _test_foreach);
+   TestSuite_Add (suite, "/mlib/check-cast", _test_cast);
+   TestSuite_Add (suite, "/mlib/ckdint-partial", _test_ckdint_partial);
+}
+
+mlib_diagnostic_pop ();
diff -pruN 1.30.4-1/src/libbson/CMakeLists.txt 2.0.2-1/src/libbson/CMakeLists.txt
--- 1.30.4-1/src/libbson/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -29,11 +29,6 @@ set(libbson_VERSION_FULL ${mongo-c-drive
 set(CMAKE_C_VISIBILITY_PRESET hidden)
 set(CMAKE_CXX_VISIBILITY_PRESET hidden)
 
-# A tag attached to libbson artifacts, denoting the *major* API version, used to
-# potentially co-locate additional future major versions.
-set (BSON_API_VERSION 1.0)
-
-
 #  .d8888b.           888    888    d8b
 # d88P  Y88b          888    888    Y8P
 # Y88b.               888    888
@@ -130,13 +125,6 @@ configure_file (
    "${PROJECT_BINARY_DIR}/src/bson/bson-version.h"
 )
 
-if (ENABLE_APPLE_FRAMEWORK)
-   configure_file (
-      "${PROJECT_SOURCE_DIR}/src/bson/modules/module.modulemap.in"
-      "${PROJECT_BINARY_DIR}/src/bson/modules/module.modulemap"
-   )
-endif ()
-
 # 8888888b.            .d888 d8b          d8b 888    d8b
 # 888  "Y88b          d88P"  Y8P          Y8P 888    Y8P
 # 888    888          888                     888
@@ -174,13 +162,12 @@ set(bson_libs)
 
 if(ENABLE_STATIC)
    add_library(bson_static STATIC ${all_sources})
+   add_library(bson::static ALIAS bson_static)
+   set_property(TARGET bson_static PROPERTY EXPORT_NAME bson::static)
    list(APPEND bson_libs bson_static)
-   # Define `BSON_STATIC` when building to suppress the annotation __declspec(dllexport).
-   # This prevents consumers of bson_static from exporting the symbols.
-   target_compile_definitions(bson_static PRIVATE BSON_STATIC)
-   # When consumers link against bson_static, suppress the annotation __declspec(dllimport),
-   # since those symbols will be available immediately at the link step:
-   target_compile_definitions(bson_static INTERFACE BSON_STATIC)
+   # Define `BSON_STATIC` to suppress __declspec(dllexport/dllimport) when compiling
+   # and consuming the static library
+   target_compile_definitions(bson_static PUBLIC BSON_STATIC)
 
    if(ENABLE_PIC)
       # User wants static libs to use PIC code.
@@ -189,7 +176,9 @@ if(ENABLE_STATIC)
 endif()
 
 if(ENABLE_SHARED)
-   add_library(bson_shared SHARED  ${all_sources})
+   add_library(bson_shared SHARED ${all_sources})
+   add_library(bson::shared ALIAS bson_shared)
+   set_property(TARGET bson_shared PROPERTY EXPORT_NAME bson::shared)
    if(WIN32)
       # Add resource-definition script for Windows shared library (.dll).
       configure_file(libbson.rc.in libbson.rc)
@@ -231,25 +220,10 @@ mongo_target_requirements(
 )
 
 set_target_properties(${bson_libs} PROPERTIES
-   VERSION "0.0.0"
-   SOVERSION "0"
-   OUTPUT_NAME "${BSON_OUTPUT_BASENAME}-${BSON_API_VERSION}"
+   VERSION "${PROJECT_VERSION}"
+   SOVERSION "${PROJECT_VERSION_MAJOR}"
+   OUTPUT_NAME "${BSON_OUTPUT_BASENAME}${PROJECT_VERSION_MAJOR}"
 )
-if(TARGET bson_static)
-   set_property(TARGET bson_static PROPERTY OUTPUT_NAME "${BSON_OUTPUT_BASENAME}-static-${BSON_API_VERSION}")
-endif()
-
-if (ENABLE_APPLE_FRAMEWORK)
-   set_target_properties(bson_shared PROPERTIES
-      FRAMEWORK TRUE
-      MACOSX_FRAMEWORK_BUNDLE_VERSION ${MONGOC_VERSION}
-      MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MONGOC_VERSION}
-      MACOSX_FRAMEWORK_IDENTIFIER org.mongodb.bson
-      OUTPUT_NAME "${BSON_OUTPUT_BASENAME}"
-      PUBLIC_HEADER "${HEADERS}"
-   )
-endif ()
-
 
 # 8888888888                                          888
 # 888                                                 888
@@ -306,12 +280,22 @@ endif () # ENABLE_EXAMPLES
 #   888   888  888      X88 Y88b.  888  888 888 888
 # 8888888 888  888  88888P'  "Y888 "Y888888 888 888
 
-set (BSON_HEADER_INSTALL_DIR
-   "${CMAKE_INSTALL_INCLUDEDIR}/libbson-${BSON_API_VERSION}"
+# Infix directory for all libbson headers.
+if(NOT DEFINED BSON_INSTALL_INCLUDEDIR)
+   set(BSON_INSTALL_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}/bson-${PROJECT_VERSION}")
+endif()
+# Infix directory for all libbson CMake package files
+if(NOT DEFINED BSON_INSTALL_CMAKEDIR)
+   set(BSON_INSTALL_CMAKEDIR "${MONGO_C_DRIVER_INSTALL_CMAKEDIR}/bson-${PROJECT_VERSION}")
+endif()
+
+# pkg-config properties:
+set_directory_properties(PROPERTIES
+   pkg_config_INCLUDE_DIRECTORIES "${BSON_INSTALL_INCLUDEDIR}"
+   pkg_config_NAME "bson"
 )
+
 function(install_export_target target)
-   # Tell pkg-config where the headers are going:
-   set_property(TARGET ${target} APPEND PROPERTY pkg_config_INCLUDE_DIRECTORIES "${BSON_HEADER_INSTALL_DIR}")
    # Install the target:
    install(
       TARGETS "${target}"
@@ -320,88 +304,53 @@ function(install_export_target target)
       LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
       ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
       RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
-      INCLUDES DESTINATION "${BSON_HEADER_INSTALL_DIR}"
-      FRAMEWORK DESTINATION "${CMAKE_INSTALL_BINDIR}"
+      INCLUDES DESTINATION "${BSON_INSTALL_INCLUDEDIR}"
    )
    # Install the unique export set into a file that is qualified by the name of
    # the target itself. The main config-file package will search for the
-   # possibly-installed exported targets for the known targets. See: bson-config.cmake
+   # possibly-installed exported targets for the known targets.
    install(
       EXPORT "${target}-targets"
-      NAMESPACE mongo::
       FILE "${target}-targets.cmake"
-      DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/bson-${BSON_API_VERSION}"
+      DESTINATION "${BSON_INSTALL_CMAKEDIR}"
    )
 endfunction()
 
 if(ENABLE_STATIC_LIBBSON_INSTALL AND TARGET bson_static)
    install_export_target(bson_static)
-   mongo_generate_pkg_config(bson_static FILENAME libbson-static-1.0.pc INSTALL)
+   mongo_generate_pkg_config(bson_static FILENAME bson${PROJECT_VERSION_MAJOR}-static.pc INSTALL)
 endif()
 if(ENABLE_SHARED_LIBBSON_INSTALL AND TARGET bson_shared)
    install_export_target(bson_shared)
-   mongo_generate_pkg_config(bson_shared FILENAME libbson-1.0.pc INSTALL)
+   mongo_generate_pkg_config(bson_shared FILENAME bson${PROJECT_VERSION_MAJOR}.pc INSTALL)
 endif()
 
-# Install all headers by doing a recursive directory-install.
+# Install all headers by doing a recursive directory-install. In the future, this
+# can be better handled by installing the headers as a file set via target_sources()
 install(
    DIRECTORY
       # Trailing "/" requests directory contents, not the dir itself:
-      src/bson/
+      src/
       # Also get the generated dir:
-      ${PROJECT_BINARY_DIR}/src/bson/
-   DESTINATION "${BSON_HEADER_INSTALL_DIR}/bson"
+      ${PROJECT_BINARY_DIR}/src/
+   DESTINATION "${BSON_INSTALL_INCLUDEDIR}"
    # Only grab the *public* headers.
    FILES_MATCHING
       PATTERN "*.h"
       PATTERN "*-private.h" EXCLUDE
-      # Installed separately below:
-      PATTERN "forwarding" EXCLUDE
-      # Don't generate an empty "modules" directory
-      PATTERN "modules" EXCLUDE
-   )
-
-# The forwarding header is for compatibility with `#include <bson.h>`, so it goes at the top-level:
-install(FILES src/bson/forwarding/bson.h DESTINATION "${BSON_HEADER_INSTALL_DIR}")
-
-if (ENABLE_APPLE_FRAMEWORK)
-   install (
-      FILES "${PROJECT_BINARY_DIR}/src/bson/modules/module.modulemap"
-      DESTINATION "${CMAKE_INSTALL_BINDIR}/bson.framework/Modules/"
+      # Don't install jsonsl headers
+      PATTERN "jsonsl" EXCLUDE
    )
-endif ()
-
-# Generate the config-file package
-include (CMakePackageConfigHelpers)
-write_basic_package_version_file (
-   "${CMAKE_CURRENT_BINARY_DIR}/bson/bson-${BSON_API_VERSION}-config-version.cmake"
-   VERSION ${BSON_VERSION}
-   COMPATIBILITY AnyNewerVersion
-)
-
-configure_file (src/bson-config.cmake
-   "${CMAKE_CURRENT_BINARY_DIR}/bson/bson-${BSON_API_VERSION}-config.cmake"
-   COPYONLY
-)
-
-install (
-   FILES
-      "${CMAKE_CURRENT_BINARY_DIR}/bson/bson-${BSON_API_VERSION}-config.cmake"
-      "${CMAKE_CURRENT_BINARY_DIR}/bson/bson-${BSON_API_VERSION}-config-version.cmake"
-   DESTINATION
-      ${CMAKE_INSTALL_LIBDIR}/cmake/bson-${BSON_API_VERSION}
-   COMPONENT
-      Devel
-)
 
-# Install the base targets. (Prior targets were installed above)
-install (EXPORT bson-targets
-   NAMESPACE mongo::
-   FILE bson-targets.cmake
-   DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bson-${BSON_API_VERSION}
+# Install the platform libraries from MongoPlatform.cmake. Search: PLATFORM-EXPORT-TARGET-INSTALL
+install(EXPORT mongo-platform-targets
+   # The "00" prefix forces the file to sort to the top during globbing, because
+   # we want it to be included first before the libbson targets
+   FILE 00-mongo-platform-targets.cmake
+   DESTINATION "${BSON_INSTALL_CMAKEDIR}"
 )
 
-set(bson_cmake_prefix "${MONGO_C_DRIVER_INSTALL_CMAKEDIR}/bson-${PROJECT_VERSION}")
+# Install the CMake config-mode package
 configure_file(
    ${mongo-c-driver_SOURCE_DIR}/build/cmake/packageConfigVersion.cmake.in
    bsonConfigVersion.cmake
@@ -409,10 +358,9 @@ configure_file(
 )
 install(
    FILES etc/bsonConfig.cmake "${CMAKE_CURRENT_BINARY_DIR}/bsonConfigVersion.cmake"
-   DESTINATION "${bson_cmake_prefix}"
+   DESTINATION "${BSON_INSTALL_CMAKEDIR}"
 )
 
-include (LegacyPackage)
 include (CPack)
 
 if (MONGO_FUZZ)
@@ -434,7 +382,7 @@ if (ENABLE_MAN_PAGES OR ENABLE_HTML_DOCS
    add_custom_target (bson-doc
       ALL
       DEPENDS
-      $<$<BOOL:${ENABLE_MAN_PAGES}>:bson-man>
-      $<$<BOOL:${ENABLE_HTML_DOCS}>:bson-html>
+      $<TARGET_NAME_IF_EXISTS:bson-man>
+      $<TARGET_NAME_IF_EXISTS:bson-html>
    )
 endif ()
diff -pruN 1.30.4-1/src/libbson/NEWS 2.0.2-1/src/libbson/NEWS
--- 1.30.4-1/src/libbson/NEWS	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/NEWS	2025-06-19 15:42:22.000000000 +0000
@@ -1,36 +1,83 @@
-libbson 1.30.4
-==============
+libbson 2.0.2
+=============
 
-No changes since 1.30.3. Version incremented to match the libmongoc version.
+Fixes:
 
+* Various fixes have been applied to the `bson_validate` family of functions,
+  with some minor behavioral changes.
+  * Previously accepted invalid UTF-8 will be rejected when `BSON_VALIDATE_UTF8`
+    is specified.
+  * The scope document in a deprecated "code with scope" element is now
+    validated with a fixed set of rules and is treated as an opaque JavaScript
+    object.
+  * A document nesting limit is now enforced during validation.
 
+Thanks to everyone who contributed to the development of this release.
+
+  * Kevin Albertson
+  * Colby Pike
 
-libbson 1.30.3
-==============
+
+libbson 2.0.1
+=============
 
 Fixes:
 
   * Fix CMake configure error on macOS with CMake 4.
 
-New Features:
+Thanks to everyone who contributed to the development of this release.
+
+  * Kevin Albertson
+
+
+
+libbson 2.0.0
+=============
 
-* In anticipation of the 2.0 release of mongo-c-driver, new CMake packages and
-  imported targets have been defined (for both `bson` and `mongoc`). To import
-  `bson` with the new names, call `find_package` for the `bson` package. The new
-  imported targets are named `bson::static`, `bson::shared`, and `bson::bson`
-  (which points to either the static or the shared library, depending on an
-  import-time configuration option).
-
-  The new package and target names will remain unchanged when upgrading to the
-  2.0 release, allowing consumers to support both major versions without
-  modifying their CMake project. The current imported target names will be
-  removed from the 2.0 release, and should not be used for
-  forward-compatibility.
+## Changes
+
+* `BSON_ERROR_BUFFER_SIZE` is reduced from `504` to `503` to reserve the final byte for internal use.
+    * The data layout of `bson_error_t` remains otherwise unchanged: the size is still 512 bytes and the offset of the `.code`, `.domain`, and `.message` data members remain unchanged.
+* The pkg-config files `libbson-1.0`, have been renamed to `bson2`, and `bson2-static`, respectively.
+
+### CMake Packages and Imported Targets
+
+The `bson-1.0` CMake package have been removed. Instead, use or `bson`, and
+specify a version or version range to be imported:
+
+```cmake
+find_package(bson 1.30...2.0)
+```
+
+The new package imports different target names:
+
+- `mongo::bson_static` → `bson::static`
+- `mongo::bson_shared` → `bson::shared`
+- The target `bson::bson` is a shim target that points to either the shared
+  library or the static library.
+
+
+## Removals
+
+* `bson_as_json` and `bson_array_as_json` are removed due to producing non-portable Legacy Extended JSON. Prefer Canonical Extended JSON or Relaxed Extended JSON for portability. To continue using Legacy Extended JSON, use `bson_as_legacy_extended_json` and `bson_array_as_legacy_extended_json`.
+* Compiling with `BSON_MEMCHECK` defined now has no effect.
+* Remove deprecated integral comparison interfaces: `bson_in_range_*` and `bson_cmp_*`.
+* Remove deprecated atomic and threading interfaces: `bson_atomic_*` and `bson_thrd_yield`.
+* The deprecated `ENABLE_EXTRA_ALIGNMENT` CMake option is removed.
+  * `bson_t` and `bson_iter_t` are now aligned to the size of a pointer instead of `128`.
+  * `bson_error_t`, `bson_value_t`, and `bson_visitor_t` are now aligned to the size of a pointer instead of `8`.
+  * `BSON_ALIGNED_BEGIN` and `BSON_ALIGNED_END` now unconditionally apply their requested alignment.
+* Remove deprecated `bson_copy_to_excluding`. Use `bson_copy_to_excluding_noinit` instead.
+
+## Contributors
 
 Thanks to everyone who contributed to the development of this release.
 
   * Kevin Albertson
+  * Micah Scott
   * Colby Pike
+  * Ezra Chung
+  * Lin Raymond
 
 libbson 1.30.2
 ==============
@@ -85,7 +132,6 @@ Thanks to everyone who contributed to th
   * Jeremy Mikola
   * Colby Pike
 
-
 libbson 1.29.2
 ==============
 
diff -pruN 1.30.4-1/src/libbson/doc/api.rst 2.0.2-1/src/libbson/doc/api.rst
--- 1.30.4-1/src/libbson/doc/api.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/api.rst	2025-06-19 15:42:22.000000000 +0000
@@ -15,7 +15,6 @@ API Reference
   bson_oid_t
   bson_reader_t
   character_and_string_routines
-  bson_string_t
   bson_subtype_t
   bson_type_t
   bson_unichar_t
@@ -25,5 +24,6 @@ API Reference
   bson_writer_t
   bson_get_monotonic_time
   bson_memory
+  binary_vector
   version
   legacy_extended_json
diff -pruN 1.30.4-1/src/libbson/doc/binary_vector.rst 2.0.2-1/src/libbson/doc/binary_vector.rst
--- 1.30.4-1/src/libbson/doc/binary_vector.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/binary_vector.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,149 @@
+:man_page: libbson_binary_vector
+
+BSON Binary Vector subtype
+==========================
+
+In Libbson, we use the term *Vector* to refer to a data representation for compact storage of uniform elements, defined by the `BSON Binary Subtype 9 - Vector <https://github.com/mongodb/specifications/blob/master/source/bson-binary-vector/bson-binary-vector.md>`_ specification.
+
+Libbson includes API support for Vectors:
+
+* The *view* APIs provide an efficient way to access elements of Vector fields that reside within :symbol:`bson_t` storage.
+* Integration between *views* and other Libbson features: append, array builder, iter.
+* Vectors can be converted to and from a plain BSON Array, subject to the specification's type conversion rules.
+
+The specification currently defines three element types, which Libbson interprets as:
+
+* ``int8``: signed integer elements, equivalent to C ``int8_t``.
+* ``float32``: IEEE 754 floating point, 32 bits per element, least-significant byte first. After alignment and byte swapping, elements are equivalent to C ``float``.
+* ``packed_bit``: single-bit integer elements, packed most-significant bit first. Accessible in packed form as C ``uint8_t`` or as unpacked elements using C ``bool``.
+
+Vector Views
+------------
+
+.. toctree::
+  :titlesonly:
+  :maxdepth: 1
+
+  bson_vector_int8_view_t
+  bson_vector_int8_const_view_t
+  bson_vector_float32_view_t
+  bson_vector_float32_const_view_t
+  bson_vector_packed_bit_view_t
+  bson_vector_packed_bit_const_view_t
+
+Integration
+-----------
+
+* Allocating Vectors inside :symbol:`bson_t`:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_append_vector_int8_uninit
+    bson_append_vector_float32_uninit
+    bson_append_vector_packed_bit_uninit
+
+* Accessing an existing Vector via :symbol:`bson_iter_t`:
+
+  .. code-block:: c
+
+    #define BSON_ITER_HOLDS_VECTOR(iter) /* ... */
+    #define BSON_ITER_HOLDS_VECTOR_INT8(iter) /* ... */
+    #define BSON_ITER_HOLDS_VECTOR_FLOAT32(iter) /* ... */
+    #define BSON_ITER_HOLDS_VECTOR_PACKED_BIT(iter) /* ... */
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_int8_view_from_iter
+    bson_vector_int8_const_view_from_iter
+    bson_vector_float32_view_from_iter
+    bson_vector_float32_const_view_from_iter
+    bson_vector_packed_bit_view_from_iter
+    bson_vector_packed_bit_const_view_from_iter
+
+Array Conversion
+----------------
+
+* Polymorphic array-from-vector:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_append_array_from_vector
+
+* Type specific array-from-vector:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_append_array_from_vector_int8
+    bson_append_array_from_vector_float32
+    bson_append_array_from_vector_packed_bit
+
+* Using :symbol:`bson_array_builder_t` for array-from-vector:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_array_builder_append_vector_int8_elements
+    bson_array_builder_append_vector_float32_elements
+    bson_array_builder_append_vector_packed_bit_elements
+    bson_array_builder_append_vector_elements
+
+* Type specific vector-from-array:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_append_vector_int8_from_array
+    bson_append_vector_float32_from_array
+    bson_append_vector_packed_bit_from_array
+
+Additional Definitions
+----------------------
+
+* Binary subtype:
+
+  .. code-block:: c
+
+    typedef enum {
+      BSON_SUBTYPE_VECTOR = 0x09,
+      /* ... */
+    } bson_subtype_t;
+
+* Byte length of the Vector header:
+
+  .. code-block:: c
+
+    // Length of the required header for BSON_SUBTYPE_VECTOR, in bytes
+    #define BSON_VECTOR_HEADER_LEN 2
+
+* Byte length for a Vector with specific element type and count:
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_int8_binary_data_length
+    bson_vector_float32_binary_data_length
+    bson_vector_packed_bit_binary_data_length
+
+* Errors:
+
+  .. code-block:: c
+
+    // Error "domain"
+    #define BSON_ERROR_VECTOR 4
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_error_code_t
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_array_from_vector.rst 2.0.2-1/src/libbson/doc/bson_append_array_from_vector.rst
--- 1.30.4-1/src/libbson/doc/bson_append_array_from_vector.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_array_from_vector.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,40 @@
+:man_page: bson_append_array_from_vector
+
+bson_append_array_from_vector()
+===============================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_ARRAY_FROM_VECTOR(b, key, iter) \
+     bson_append_array_from_vector (b, key, (int) strlen (key), iter)
+
+  bool
+  bson_append_array_from_vector (bson_t *bson,
+                                 const char *key,
+                                 int key_length,
+                                 const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``iter``: A :symbol:`bson_iter_t` pointing to any supported :doc:`binary_vector` field.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``iter`` into a plain BSON Array, written to ``bson`` under the name ``key``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX, or if ``iter`` doesn't point to a valid recognized Vector type.
+
+.. seealso::
+
+  | :symbol:`bson_array_builder_append_vector_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_float32.rst 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_float32.rst
--- 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_float32.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_float32.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,40 @@
+:man_page: bson_append_array_from_vector_float32
+
+bson_append_array_from_vector_float32()
+=======================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_ARRAY_FROM_VECTOR_FLOAT32(b, key, view) \
+     bson_append_array_from_vector_float32 (b, key, (int) strlen (key), view)
+
+  bool
+  bson_append_array_from_vector_float32 (bson_t *bson,
+                                         const char *key,
+                                         int key_length,
+                                         bson_vector_float32_const_view_t view);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``view``: A :symbol:`bson_vector_float32_const_view_t` pointing to validated ``float32`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into a plain BSON Array, written to ``bson`` under the name ``key``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_array_builder_append_vector_float32_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_int8.rst 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_int8.rst
--- 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_int8.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_int8.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,40 @@
+:man_page: bson_append_array_from_vector_int8
+
+bson_append_array_from_vector_int8()
+====================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_ARRAY_FROM_VECTOR_INT8(b, key, view) \
+     bson_append_array_from_vector_int8 (b, key, (int) strlen (key), view)
+
+  bool
+  bson_append_array_from_vector_int8 (bson_t *bson,
+                                      const char *key,
+                                      int key_length,
+                                      bson_vector_int8_const_view_t view);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``view``: A :symbol:`bson_vector_int8_const_view_t` pointing to validated ``int8`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into a plain BSON Array, written to ``bson`` under the name ``key``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_array_builder_append_vector_int8_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_packed_bit.rst 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_packed_bit.rst
--- 1.30.4-1/src/libbson/doc/bson_append_array_from_vector_packed_bit.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_array_from_vector_packed_bit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,40 @@
+:man_page: bson_append_array_from_vector_packed_bit
+
+bson_append_array_from_vector_packed_bit()
+==========================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_ARRAY_FROM_VECTOR_PACKED_BIT(b, key, view) \
+     bson_append_array_from_vector_packed_bit (b, key, (int) strlen (key), view)
+
+  bool
+  bson_append_array_from_vector_packed_bit (bson_t *bson,
+                                            const char *key,
+                                            int key_length,
+                                            bson_vector_packed_bit_const_view_t view);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``view``: A :symbol:`bson_vector_packed_bit_const_view_t` pointing to validated ``packed_bit`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into a plain BSON Array, written to ``bson`` under the name ``key``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_array_builder_append_vector_packed_bit_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_binary.rst 2.0.2-1/src/libbson/doc/bson_append_binary.rst
--- 1.30.4-1/src/libbson/doc/bson_append_binary.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_binary.rst	2025-06-19 15:42:22.000000000 +0000
@@ -38,3 +38,7 @@ Returns
 -------
 
 Returns ``true`` if the operation was applied successfully. The function will fail if appending ``binary`` grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_append_binary_uninit`
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_binary_uninit.rst 2.0.2-1/src/libbson/doc/bson_append_binary_uninit.rst
--- 1.30.4-1/src/libbson/doc/bson_append_binary_uninit.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_binary_uninit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,43 @@
+:man_page: bson_append_binary_uninit
+
+bson_append_binary_uninit()
+===========================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_BINARY_UNINIT(b, key, subtype, val, len) \
+     bson_append_binary_uninit (b, key, (int) strlen (key), subtype, val, len)
+
+  bool
+  bson_append_binary_uninit (bson_t *bson,
+                             const char *key,
+                             int key_length,
+                             bson_subtype_t subtype,
+                             uint8_t **binary,
+                             uint32_t length);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: The key name.
+* ``key_length``: The length of ``key`` in bytes or -1 to use strlen().
+* ``subtype``: A bson_subtype_t indicating the binary subtype.
+* ``binary``: Location for a pointer that will receive a writable pointer to the uninitialized binary data block.
+* ``length``: The length of ``buffer`` in bytes.
+
+Description
+-----------
+
+The :symbol:`bson_append_binary_uninit()` function is an alternative to :symbol:`bson_append_binary()` which allows applications to assemble the contents of the binary field within the :symbol:`bson_t`, without an additional temporary buffer.
+On success, the caller MUST write to every byte of the binary data block if the resulting :symbol:`bson_t` is to be used.
+The buffer that ``binary`` points to is only valid until the iterator's :symbol:`bson_t` is otherwise modified or freed.
+
+
+Returns
+-------
+
+Returns ``true`` if the uninitialized ``binary`` item was appended. The function will fail if appending ``binary`` grows ``bson`` larger than INT32_MAX.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_float32_from_array.rst 2.0.2-1/src/libbson/doc/bson_append_vector_float32_from_array.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_float32_from_array.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_float32_from_array.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,45 @@
+:man_page: bson_append_vector_float32_from_array
+
+bson_append_vector_float32_from_array()
+=======================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_FLOAT32_FROM_ARRAY(b, key, iter, err) \
+     bson_append_vector_float32_from_array (b, key, (int) strlen (key), iter, err)
+
+  bool
+  bson_append_vector_float32_from_array (bson_t *bson,
+                                         const char *key,
+                                         int key_length,
+                                         const bson_iter_t *iter,
+                                         bson_error_t *error);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``iter``: A :symbol:`bson_iter_t` referencing array elements that will be converted.
+* ``error``: Optional :symbol:`bson_error_t` for detail about conversion failures.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by converting an Array to a Vector of ``float32`` elements.
+
+For the conversion to succeed, every item in the Array must be double-precision floating point number. (``BSON_TYPE_DOUBLE``)
+
+The provided ``iter`` must be positioned just prior to the first element of the BSON Array.
+If your input is a bare BSON Array, set up ``iter`` using :symbol:`bson_iter_init`.
+If the input is within a document field, use :symbol:`bson_iter_recurse`.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. On error, returns ``false`` and writes additional error information to ``error`` without modifying ``bson``.
+The error will have a ``domain`` of ``BSON_ERROR_VECTOR`` and a ``code`` from :symbol:`bson_vector_error_code_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_float32_uninit.rst 2.0.2-1/src/libbson/doc/bson_append_vector_float32_uninit.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_float32_uninit.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_float32_uninit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,42 @@
+:man_page: bson_append_vector_float32_uninit
+
+bson_append_vector_float32_uninit()
+===================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_FLOAT32_UNINIT(b, key, count, view) \
+     bson_append_vector_float32_uninit (b, key, (int) strlen (key), count, view)
+
+  bool
+  bson_append_vector_float32_uninit (bson_t *bson,
+                                     const char *key,
+                                     int key_length,
+                                     size_t element_count,
+                                     bson_vector_float32_view_t *view_out);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``element_count``: Number of elements to allocate space for.
+* ``view_out``: Receives a :symbol:`bson_vector_float32_view_t` with uninitialized elements.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by allocating a Vector with the indicated number of ``float32`` elements.
+The elements will be uninitialized.
+On success, the caller must write every element in the Vector if the resulting :symbol:`bson_t` is to be used.
+
+The view written to ``*view_out`` is only valid until ``bson`` is otherwise modified or freed.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_int8_from_array.rst 2.0.2-1/src/libbson/doc/bson_append_vector_int8_from_array.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_int8_from_array.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_int8_from_array.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,46 @@
+:man_page: bson_append_vector_int8_from_array
+
+bson_append_vector_int8_from_array()
+====================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_INT8_FROM_ARRAY(b, key, iter, err) \
+     bson_append_vector_int8_from_array (b, key, (int) strlen (key), iter, err)
+
+  bool
+  bson_append_vector_int8_from_array (bson_t *bson,
+                                      const char *key,
+                                      int key_length,
+                                      const bson_iter_t *iter,
+                                      bson_error_t *error);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``iter``: A :symbol:`bson_iter_t` referencing array elements that will be converted.
+* ``error``: Optional :symbol:`bson_error_t` for detail about conversion failures.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by converting an Array to a Vector of ``int8`` elements.
+
+For the conversion to succeed, every item in the Array must be an integer (``BSON_TYPE_INT32`` or ``BSON_TYPE_INT64``) in the range ``INT8_MIN`` (-128) through ``INT8_MAX`` (127) inclusive.
+If any element has an incorrect type or an out-of-range value, the conversion fails with an ``error`` message providing details, and no changes are made to ``bson``.
+
+The provided ``iter`` must be positioned just prior to the first element of the BSON Array.
+If your input is a bare BSON Array, set up ``iter`` using :symbol:`bson_iter_init`.
+If the input is within a document field, use :symbol:`bson_iter_recurse`.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. On error, returns ``false`` and writes additional error information to ``error`` without modifying ``bson``.
+The error will have a ``domain`` of ``BSON_ERROR_VECTOR`` and a ``code`` from :symbol:`bson_vector_error_code_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_int8_uninit.rst 2.0.2-1/src/libbson/doc/bson_append_vector_int8_uninit.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_int8_uninit.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_int8_uninit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,42 @@
+:man_page: bson_append_vector_int8_uninit
+
+bson_append_vector_int8_uninit()
+================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_INT8_UNINIT(b, key, count, view) \
+     bson_append_vector_int8_uninit (b, key, (int) strlen (key), count, view)
+
+  bool
+  bson_append_vector_int8_uninit (bson_t *bson,
+                                  const char *key,
+                                  int key_length,
+                                  size_t element_count,
+                                  bson_vector_int8_view_t *view_out);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``element_count``: Number of elements to allocate space for.
+* ``view_out``: Receives a :symbol:`bson_vector_int8_view_t` with uninitialized elements.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by allocating a Vector with the indicated number of ``int8`` elements.
+The elements will be uninitialized.
+On success, the caller must write every element in the Vector if the resulting :symbol:`bson_t` is to be used.
+
+The view written to ``*view_out`` is only valid until ``bson`` is otherwise modified or freed.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_packed_bit_from_array.rst 2.0.2-1/src/libbson/doc/bson_append_vector_packed_bit_from_array.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_packed_bit_from_array.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_packed_bit_from_array.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,46 @@
+:man_page: bson_append_vector_packed_bit_from_array
+
+bson_append_vector_packed_bit_from_array()
+==========================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_PACKED_BIT_FROM_ARRAY(b, key, iter, err) \
+     bson_append_vector_packed_bit_from_array (b, key, (int) strlen (key), iter, err)
+
+  bool
+  bson_append_vector_packed_bit_from_array (bson_t *bson,
+                                            const char *key,
+                                            int key_length,
+                                            const bson_iter_t *iter,
+                                            bson_error_t *error);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``iter``: A :symbol:`bson_iter_t` referencing array elements that will be converted.
+* ``error``: Optional :symbol:`bson_error_t` for detail about conversion failures.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by converting an Array to a Vector of ``packed_bit`` elements.
+
+For the conversion to succeed, every item in the Array must be either an integer (``BSON_TYPE_INT32`` or ``BSON_TYPE_INT64``) with the values ``0`` or ``1``, or boolean (``BSON_TYPE_BOOL``).
+If any element has an incorrect type or an out-of-range value, the conversion fails with an ``error`` message providing details, and no changes are made to ``bson``.
+
+The provided ``iter`` must be positioned just prior to the first element of the BSON Array.
+If your input is a bare BSON Array, set up ``iter`` using :symbol:`bson_iter_init`.
+If the input is within a document field, use :symbol:`bson_iter_recurse`.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. On error, returns ``false`` and writes additional error information to ``error`` without modifying ``bson``.
+The error will have a ``domain`` of ``BSON_ERROR_VECTOR`` and a ``code`` from :symbol:`bson_vector_error_code_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_append_vector_packed_bit_uninit.rst 2.0.2-1/src/libbson/doc/bson_append_vector_packed_bit_uninit.rst
--- 1.30.4-1/src/libbson/doc/bson_append_vector_packed_bit_uninit.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_append_vector_packed_bit_uninit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,42 @@
+:man_page: bson_append_vector_packed_bit_uninit
+
+bson_append_vector_packed_bit_uninit()
+======================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_APPEND_VECTOR_PACKED_BIT_UNINIT(b, key, count, view) \
+     bson_append_vector_packed_bit_uninit (b, key, (int) strlen (key), count, view)
+
+  bool
+  bson_append_vector_packed_bit_uninit (bson_t *bson,
+                                        const char *key,
+                                        int key_length,
+                                        size_t element_count,
+                                        bson_vector_packed_bit_view_t *view_out);
+
+Parameters
+----------
+
+* ``bson``: A :symbol:`bson_t`.
+* ``key``: An ASCII C string containing the name of the field.
+* ``key_length``: The length of ``key`` in bytes, or -1 to determine the length with ``strlen()``.
+* ``element_count``: Number of elements to allocate space for.
+* ``view_out``: Receives a :symbol:`bson_vector_packed_bit_view_t` with uninitialized elements.
+
+Description
+-----------
+
+Appends a new field to ``bson`` by allocating a Vector with the indicated number of ``packed_bit`` elements.
+The elements will be uninitialized.
+On success, the caller must write every element in the Vector if the resulting :symbol:`bson_t` is to be used.
+
+The view written to ``*view_out`` is only valid until ``bson`` is otherwise modified or freed.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_as_json.rst 2.0.2-1/src/libbson/doc/bson_array_as_json.rst
--- 1.30.4-1/src/libbson/doc/bson_array_as_json.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_as_json.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,48 +0,0 @@
-:man_page: bson_array_as_json
-
-bson_array_as_json()
-====================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-      Use :symbol:`bson_array_as_canonical_extended_json()` and :symbol:`bson_array_as_relaxed_extended_json()` instead, which use the same `MongoDB Extended JSON format`_ as all other MongoDB drivers.
-
-      To continue producing Legacy Extended JSON, use :symbol:`bson_array_as_legacy_extended_json()`.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  char *
-  bson_array_as_json (const bson_t *bson, size_t *length);
-
-Parameters
-----------
-
-* ``bson``: A :symbol:`bson_t`.
-* ``length``: An optional location for the length of the resulting string.
-
-Description
------------
-
-:symbol:`bson_array_as_json()` encodes ``bson`` as a UTF-8 string using :doc:`libbson's Legacy Extended JSON <legacy_extended_json>`.
-The outermost element is encoded as a JSON array (``[ ... ]``), rather than a JSON document (``{ ... }``).
-
-The caller is responsible for freeing the resulting UTF-8 encoded string by calling :symbol:`bson_free()` with the result.
-
-If non-NULL, ``length`` will be set to the length of the result in bytes.
-
-Returns
--------
-
-If successful, a newly allocated UTF-8 encoded string and ``length`` is set.
-
-Upon failure, NULL is returned.
-
-.. only:: html
-
-  .. include:: includes/seealso/bson-as-json.txt
-
-.. _MongoDB Extended JSON format: https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_elements.rst 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_elements.rst
--- 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_elements.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_elements.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,38 @@
+:man_page: bson_array_builder_append_vector_elements
+
+bson_array_builder_append_vector_elements()
+===========================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_array_builder_append_vector_elements (bson_array_builder_t *builder,
+                                             const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``builder``: A valid :symbol:`bson_array_builder_t`.
+* ``iter``: A :symbol:`bson_iter_t` pointing to any supported :doc:`binary_vector` field.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``iter`` into elements of a plain BSON Array, written to ``builder``.
+This conversion is polymorphic: A converted element type will be chosen based on the type of the input Vector.
+For details, see the type-specific versions of this function.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX, or if ``iter`` doesn't point to a valid recognized Vector type.
+
+.. seealso::
+
+  | :symbol:`bson_append_array_from_vector`
+  | :symbol:`bson_array_builder_append_vector_int8_elements`
+  | :symbol:`bson_array_builder_append_vector_float32_elements`
+  | :symbol:`bson_array_builder_append_vector_packed_bit_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_float32_elements.rst 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_float32_elements.rst
--- 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_float32_elements.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_float32_elements.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,35 @@
+:man_page: bson_array_builder_append_vector_float32_elements
+
+bson_array_builder_append_vector_float32_elements()
+===================================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_array_builder_append_vector_float32_elements (bson_array_builder_t *builder,
+                                                     bson_vector_float32_const_view_t view);
+
+Parameters
+----------
+
+* ``builder``: A valid :symbol:`bson_array_builder_t`.
+* ``view``: A :symbol:`bson_vector_float32_const_view_t` pointing to validated ``float32`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into elements of a plain BSON Array, written to ``builder``.
+Every element will be converted from ``float`` to ``double`` precision.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_append_array_from_vector`
+  | :symbol:`bson_array_builder_append_vector_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_int8_elements.rst 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_int8_elements.rst
--- 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_int8_elements.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_int8_elements.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,35 @@
+:man_page: bson_array_builder_append_vector_int8_elements
+
+bson_array_builder_append_vector_int8_elements()
+================================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_array_builder_append_vector_int8_elements (bson_array_builder_t *builder,
+                                                  bson_vector_int8_const_view_t view);
+
+Parameters
+----------
+
+* ``builder``: A valid :symbol:`bson_array_builder_t`.
+* ``view``: A :symbol:`bson_vector_int8_const_view_t` pointing to validated ``int8`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into elements of a plain BSON Array, written to ``builder``.
+Every element will be losslessly extended from ``int8_t`` to ``int32_t``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_append_array_from_vector`
+  | :symbol:`bson_array_builder_append_vector_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_packed_bit_elements.rst 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_packed_bit_elements.rst
--- 1.30.4-1/src/libbson/doc/bson_array_builder_append_vector_packed_bit_elements.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_builder_append_vector_packed_bit_elements.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,35 @@
+:man_page: bson_array_builder_append_vector_packed_bit_elements
+
+bson_array_builder_append_vector_packed_bit_elements()
+======================================================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_array_builder_append_vector_packed_bit_elements (bson_array_builder_t *builder,
+                                                        bson_vector_packed_bit_const_view_t view);
+
+Parameters
+----------
+
+* ``builder``: A valid :symbol:`bson_array_builder_t`.
+* ``view``: A :symbol:`bson_vector_packed_bit_const_view_t` pointing to validated ``packed_bit`` :doc:`binary_vector` data.
+
+Description
+-----------
+
+Converts the Vector pointed to by ``view`` into elements of a plain BSON Array, written to ``builder``.
+Every element will be ``0`` or ``1`` written as a ``BSON_TYPE_INT32``.
+
+Returns
+-------
+
+Returns ``true`` if the operation was applied successfully. The function fails if appending the array grows ``bson`` larger than INT32_MAX.
+
+.. seealso::
+
+  | :symbol:`bson_append_array_from_vector`
+  | :symbol:`bson_array_builder_append_vector_elements`
diff -pruN 1.30.4-1/src/libbson/doc/bson_array_builder_t.rst 2.0.2-1/src/libbson/doc/bson_array_builder_t.rst
--- 1.30.4-1/src/libbson/doc/bson_array_builder_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_array_builder_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -83,6 +83,12 @@ Appending values to an array
                                       uint32_t length);
 
     bool
+    bson_array_builder_append_binary_uninit (bson_array_builder_t *bab,
+                                             bson_subtype_t subtype,
+                                             uint8_t **binary,
+                                             uint32_t length);
+
+    bool
     bson_array_builder_append_bool (bson_array_builder_t *bab, bool value);
 
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_as_json.rst 2.0.2-1/src/libbson/doc/bson_as_json.rst
--- 1.30.4-1/src/libbson/doc/bson_as_json.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_as_json.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,47 +0,0 @@
-:man_page: bson_as_json
-
-bson_as_json()
-==============
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-      Use :symbol:`bson_as_canonical_extended_json()` and :symbol:`bson_as_relaxed_extended_json()` instead, which use the same `MongoDB Extended JSON format`_ as all other MongoDB drivers.
-
-      To continue producing Legacy Extended JSON, use :symbol:`bson_as_legacy_extended_json()`.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  char *
-  bson_as_json (const bson_t *bson, size_t *length);
-
-Parameters
-----------
-
-* ``bson``: A :symbol:`bson_t`.
-* ``length``: An optional location for the length of the resulting string.
-
-Description
------------
-
-:symbol:`bson_as_json()` encodes ``bson`` as a UTF-8 string using :doc:`libbson's Legacy Extended JSON <legacy_extended_json>`.
-
-The caller is responsible for freeing the resulting UTF-8 encoded string by calling :symbol:`bson_free()` with the result.
-
-If non-NULL, ``length`` will be set to the length of the result in bytes.
-
-Returns
--------
-
-If successful, a newly allocated UTF-8 encoded string and ``length`` is set.
-
-Upon failure, NULL is returned.
-
-.. only:: html
-
-  .. include:: includes/seealso/bson-as-json.txt
-
-.. _MongoDB Extended JSON format: https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md
diff -pruN 1.30.4-1/src/libbson/doc/bson_copy_to_excluding.rst 2.0.2-1/src/libbson/doc/bson_copy_to_excluding.rst
--- 1.30.4-1/src/libbson/doc/bson_copy_to_excluding.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_copy_to_excluding.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,39 +0,0 @@
-:man_page: bson_copy_to_excluding
-
-bson_copy_to_excluding()
-========================
-
-.. warning::
-   .. deprecated:: 1.1.0
-
-      Use :symbol:`bson_copy_to_excluding_noinit()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_copy_to_excluding (const bson_t *src,
-                          bson_t *dst,
-                          const char *first_exclude,
-                          ...);
-
-Parameters
-----------
-
-* ``src``: A :symbol:`bson_t`.
-* ``dst``: A :symbol:`bson_t`.
-* ``first_exclude``: The first field name to exclude.
-
-Description
------------
-
-The :symbol:`bson_copy_to_excluding()` function shall copy all fields from
-``src`` to ``dst`` except those specified by the variadic, NULL terminated list
-of keys starting from ``first_exclude``.
-
-.. warning::
-
-  :symbol:`bson_init` is called on ``dst``.
-
diff -pruN 1.30.4-1/src/libbson/doc/bson_copy_to_excluding_noinit.rst 2.0.2-1/src/libbson/doc/bson_copy_to_excluding_noinit.rst
--- 1.30.4-1/src/libbson/doc/bson_copy_to_excluding_noinit.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_copy_to_excluding_noinit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -27,9 +27,8 @@ Description
 The :symbol:`bson_copy_to_excluding_noinit()` function shall copy all fields
 from ``src`` to ``dst`` except those specified by the variadic, NULL terminated
 list of keys starting from ``first_exclude``.
-Works the same way as :symbol:`bson_copy_to_excluding`, except does **not** call
-:symbol:`bson_init` on ``dst``.
-This function should be preferred in new code over :symbol:`bson_copy_to_excluding`.
+
+Does **not** call :symbol:`bson_init` on ``dst``.
 
 .. warning::
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_copy_to_excluding_noinit_va.rst 2.0.2-1/src/libbson/doc/bson_copy_to_excluding_noinit_va.rst
--- 1.30.4-1/src/libbson/doc/bson_copy_to_excluding_noinit_va.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_copy_to_excluding_noinit_va.rst	2025-06-19 15:42:22.000000000 +0000
@@ -27,7 +27,7 @@ Description
 
 The :symbol:`bson_copy_to_excluding_noinit_va()` function shall copy all fields from ``src`` to ``dst`` except those specified by ``first_exclude`` and ``args``.
 
-This method works the same way as :symbol:`bson_copy_to_excluding_noinit`, except it takes a va_list. This method does not call :symbol:`bson_init` on ``dst``.
+Does **not** call :symbol:`bson_init` on ``dst``.
 
 .. seealso::
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_iter_binary.rst 2.0.2-1/src/libbson/doc/bson_iter_binary.rst
--- 1.30.4-1/src/libbson/doc/bson_iter_binary.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_iter_binary.rst	2025-06-19 15:42:22.000000000 +0000
@@ -32,3 +32,7 @@ This function shall return the binary da
 
 The buffer that ``binary`` points to is only valid until the iterator's :symbol:`bson_t` is modified or freed.
 
+.. seealso::
+
+  | :symbol:`bson_iter_binary_equal`
+  | :symbol:`bson_iter_binary_subtype`
diff -pruN 1.30.4-1/src/libbson/doc/bson_iter_binary_equal.rst 2.0.2-1/src/libbson/doc/bson_iter_binary_equal.rst
--- 1.30.4-1/src/libbson/doc/bson_iter_binary_equal.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_iter_binary_equal.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,30 @@
+:man_page: bson_iter_binary_equal
+
+bson_iter_binary_equal()
+========================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_iter_binary_equal (const bson_iter_t *iter_a, const bson_iter_t *iter_b);
+
+Parameters
+----------
+
+* ``iter_a``: A :symbol:`bson_iter_t`.
+* ``iter_b``: A :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+Compare two BSON_TYPE_BINARY fields for exact equality.
+
+This is the preferred way to compare :doc:`binary_vector` values for equality.
+
+Returns
+-------
+
+``true`` if both iterators point to BSON_TYPE_BINARY fields with identical subtype and contents. ``false`` if there is any difference in subtype, length, or content, or if the fields are not binary type.
\ No newline at end of file
diff -pruN 1.30.4-1/src/libbson/doc/bson_iter_binary_subtype.rst 2.0.2-1/src/libbson/doc/bson_iter_binary_subtype.rst
--- 1.30.4-1/src/libbson/doc/bson_iter_binary_subtype.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_iter_binary_subtype.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,24 @@
+:man_page: bson_iter_binary_subtype
+
+bson_iter_binary_subtype()
+==========================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bson_subtype_t
+  bson_iter_binary_subtype (const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``iter``: A :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+This function shall return the subtype of a BSON_TYPE_BINARY element. It is a programming error to call this function on a field that is not of type BSON_TYPE_BINARY. You can check this with the BSON_ITER_HOLDS_BINARY() macro or :symbol:`bson_iter_type()`.
+
+Equivalent to the ``subtype`` output parameter of :symbol:`bson_iter_binary`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_iter_overwrite_binary.rst 2.0.2-1/src/libbson/doc/bson_iter_overwrite_binary.rst
--- 1.30.4-1/src/libbson/doc/bson_iter_overwrite_binary.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_iter_overwrite_binary.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,38 @@
+:man_page: bson_iter_overwrite_binary
+
+bson_iter_overwrite_binary()
+============================
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  void
+  bson_iter_overwrite_binary (bson_iter_t *iter,
+                              bson_subtype_t subtype,
+                              uint32_t *binary_len,
+                              uint8_t **binary);
+
+Parameters
+----------
+
+* ``iter``: A :symbol:`bson_iter_t`.
+* ``subtype``: The expected :symbol:`bson_subtype_t`.
+* ``binary_len``: A location for the length of ``binary``.
+* ``binary``: A location for a pointer to the mutable buffer.
+
+Description
+-----------
+
+The ``bson_iter_overwrite_binary()`` function obtains mutable access to a BSON_TYPE_BINARY element in place.
+
+This may only be done when the underlying bson document allows mutation.
+
+It is a programming error to call this function when ``iter`` is not observing an element of type BSON_TYPE_BINARY and the provided ``subtype``.
+
+The buffer that ``binary`` points to is only valid until the iterator's :symbol:`bson_t` is otherwise modified or freed.
+
+.. seealso::
+
+  | :symbol:`bson_iter_binary`
diff -pruN 1.30.4-1/src/libbson/doc/bson_iter_t.rst 2.0.2-1/src/libbson/doc/bson_iter_t.rst
--- 1.30.4-1/src/libbson/doc/bson_iter_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_iter_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -22,6 +22,11 @@ Synopsis
 
   #define BSON_ITER_HOLDS_BINARY(iter) /* ... */
 
+  #define BSON_ITER_HOLDS_VECTOR(iter) /* ... */
+  #define BSON_ITER_HOLDS_VECTOR_INT8(iter) /* ... */
+  #define BSON_ITER_HOLDS_VECTOR_FLOAT32(iter) /* ... */
+  #define BSON_ITER_HOLDS_VECTOR_PACKED_BIT(iter) /* ... */
+
   #define BSON_ITER_HOLDS_UNDEFINED(iter) /* ... */
 
   #define BSON_ITER_HOLDS_OID(iter) /* ... */
@@ -88,6 +93,8 @@ The :symbol:`bson_t` *MUST* be valid for
     bson_iter_as_double
     bson_iter_as_int64
     bson_iter_binary
+    bson_iter_binary_subtype
+    bson_iter_binary_equal
     bson_iter_bool
     bson_iter_code
     bson_iter_codewscope
@@ -115,6 +122,7 @@ The :symbol:`bson_t` *MUST* be valid for
     bson_iter_offset
     bson_iter_oid
     bson_iter_overwrite_bool
+    bson_iter_overwrite_binary
     bson_iter_overwrite_date_time
     bson_iter_overwrite_decimal128
     bson_iter_overwrite_double
diff -pruN 1.30.4-1/src/libbson/doc/bson_oid_init_sequence.rst 2.0.2-1/src/libbson/doc/bson_oid_init_sequence.rst
--- 1.30.4-1/src/libbson/doc/bson_oid_init_sequence.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_oid_init_sequence.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,30 +0,0 @@
-:man_page: bson_oid_init_sequence
-
-bson_oid_init_sequence()
-========================
-
-.. warning::
-   .. deprecated:: 1.14.0
-
-      Use :symbol:`bson_oid_init()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_oid_init_sequence (bson_oid_t *oid, bson_context_t *context);
-
-Parameters
-----------
-
-* ``oid``: A :symbol:`bson_oid_t`.
-* ``context``: An optional :symbol:`bson_context_t`.
-
-Description
------------
-
-Generates a new ObjectID with the next 64-bit sequence number in ``context``. The first 4 bytes contain the current time and the following 8 contain the sequence number in big-endian format.
-
-The :symbol:`bson_oid_t` generated by this function is not guaranteed to be globally unique. Only unique within this context. It is however, guaranteed to be sequential.
diff -pruN 1.30.4-1/src/libbson/doc/bson_oid_t.rst 2.0.2-1/src/libbson/doc/bson_oid_t.rst
--- 1.30.4-1/src/libbson/doc/bson_oid_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_oid_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -70,7 +70,6 @@ You can validate that a string containin
     bson_oid_init_from_data
     bson_oid_init_from_string
     bson_oid_init_from_string_unsafe
-    bson_oid_init_sequence
     bson_oid_is_valid
     bson_oid_to_string
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_append.rst 2.0.2-1/src/libbson/doc/bson_string_append.rst
--- 1.30.4-1/src/libbson/doc/bson_string_append.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_append.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,28 +0,0 @@
-:man_page: bson_string_append
-
-bson_string_append()
-====================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_string_append (bson_string_t *string, const char *str);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``str``: A string.
-
-Description
------------
-
-Appends the ASCII or UTF-8 encoded string ``str`` to ``string``. This is not suitable for embedding NULLs in strings.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_append_c.rst 2.0.2-1/src/libbson/doc/bson_string_append_c.rst
--- 1.30.4-1/src/libbson/doc/bson_string_append_c.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_append_c.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,28 +0,0 @@
-:man_page: bson_string_append_c
-
-bson_string_append_c()
-======================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_string_append_c (bson_string_t *string, char str);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``str``: An ASCII char.
-
-Description
------------
-
-Appends ``c`` to the string builder ``string``.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_append_printf.rst 2.0.2-1/src/libbson/doc/bson_string_append_printf.rst
--- 1.30.4-1/src/libbson/doc/bson_string_append_printf.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_append_printf.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,28 +0,0 @@
-:man_page: bson_string_append_printf
-
-bson_string_append_printf()
-===========================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_string_append_printf (bson_string_t *string, const char *format, ...);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``format``: A printf style format string.
-
-Description
------------
-
-Like bson_string_append() but formats a printf style string and then appends that to ``string``.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_append_unichar.rst 2.0.2-1/src/libbson/doc/bson_string_append_unichar.rst
--- 1.30.4-1/src/libbson/doc/bson_string_append_unichar.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_append_unichar.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,28 +0,0 @@
-:man_page: bson_string_append_unichar
-
-bson_string_append_unichar()
-============================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_string_append_unichar (bson_string_t *string, bson_unichar_t unichar);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``unichar``: A :symbol:`bson_unichar_t`.
-
-Description
------------
-
-Appends a unicode character to string. The character will be encoded into its multi-byte UTF-8 representation.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_free.rst 2.0.2-1/src/libbson/doc/bson_string_free.rst
--- 1.30.4-1/src/libbson/doc/bson_string_free.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_free.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,32 +0,0 @@
-:man_page: bson_string_free
-
-bson_string_free()
-==================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  char *
-  bson_string_free (bson_string_t *string, bool free_segment);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``free_segment``: A bool indicating whether ``string->str`` should be freed.
-
-Description
------------
-
-Frees the ``bson_string_t`` structure and optionally ``string->str``.
-
-Returns
--------
-
-``string->str`` if ``free_segment`` is false, otherwise ``NULL``.
-
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_new.rst 2.0.2-1/src/libbson/doc/bson_string_new.rst
--- 1.30.4-1/src/libbson/doc/bson_string_new.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_new.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,33 +0,0 @@
-:man_page: bson_string_new
-
-bson_string_new()
-=================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bson_string_t *
-  bson_string_new (const char *str);
-
-Parameters
-----------
-
-* ``str``: A string to be copied or NULL.
-
-Description
------------
-
-Creates a new string builder, which uses power-of-two growth of buffers. Use the various bson_string_append*() functions to append to the string.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
-
-Returns
--------
-
-A newly allocated bson_string_t that should be freed with bson_string_free() when no longer in use.
-
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_t.rst 2.0.2-1/src/libbson/doc/bson_string_t.rst
--- 1.30.4-1/src/libbson/doc/bson_string_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,65 +0,0 @@
-:man_page: bson_string_t
-
-bson_string_t
-=============
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-
-String Building Abstraction
-
-Synopsis
---------
-
-.. code-block:: c
-
-  #include <bson/bson.h>
-
-  typedef struct {
-     char *str;
-     uint32_t len;
-     uint32_t alloc;
-  } bson_string_t;
-
-Description
------------
-
-:symbol:`bson_string_t` is an abstraction for building strings. As chunks are added to the string, allocations are performed in powers of two.
-
-This API is useful if you need to build UTF-8 encoded strings.
-
-.. only:: html
-
-  Functions
-  ---------
-
-  .. toctree::
-    :titlesonly:
-    :maxdepth: 1
-
-    bson_string_append
-    bson_string_append_c
-    bson_string_append_printf
-    bson_string_append_unichar
-    bson_string_free
-    bson_string_new
-    bson_string_truncate
-
-Example
--------
-
-.. code-block:: c
-
-  bson_string_t *str;
-
-  str = bson_string_new (NULL);
-  bson_string_append_printf (str, "%d %s %f\n", 0, "some string", 0.123);
-  printf ("%s\n", str->str);
-
-  bson_string_free (str, true);
-
-.. tip::
-
-  You can call :symbol:`bson_string_free()` with ``false`` if you would like to take ownership of ``str->str``. Some APIs that do this might call ``return bson_string_free (str, false);`` after building the string.
-
diff -pruN 1.30.4-1/src/libbson/doc/bson_string_truncate.rst 2.0.2-1/src/libbson/doc/bson_string_truncate.rst
--- 1.30.4-1/src/libbson/doc/bson_string_truncate.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_string_truncate.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,33 +0,0 @@
-:man_page: bson_string_truncate
-
-bson_string_truncate()
-======================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  bson_string_truncate (bson_string_t *string, uint32_t len);
-
-Parameters
-----------
-
-* ``string``: A :symbol:`bson_string_t`.
-* ``len``: The new length of the string, excluding the trailing ``\0``.
-
-Description
------------
-
-Truncates the string so that it is ``len`` bytes in length. This must be smaller or equal to the current length of the string.
-
-A ``\0`` byte will be placed where the end of the string occurs.
-
-.. warning:: This function is oblivious to UTF-8 structure. If truncation occurs in the middle of a UTF-8 byte sequence, the resulting :symbol:`bson_string_t` will contain invalid UTF-8.
-
-.. warning:: The length of the resulting string (including the ``NULL`` terminator) MUST NOT exceed ``UINT32_MAX``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_subtype_t.rst 2.0.2-1/src/libbson/doc/bson_subtype_t.rst
--- 1.30.4-1/src/libbson/doc/bson_subtype_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_subtype_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -22,6 +22,7 @@ Synopsis
      BSON_SUBTYPE_MD5 = 0x05,
      BSON_SUBTYPE_COLUMN = 0x07,
      BSON_SUBTYPE_SENSITIVE = 0x08,
+     BSON_SUBTYPE_VECTOR = 0x09,
      BSON_SUBTYPE_USER = 0x80,
   } bson_subtype_t;
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_t.rst 2.0.2-1/src/libbson/doc/bson_t.rst
--- 1.30.4-1/src/libbson/doc/bson_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -56,6 +56,9 @@ Synopsis
   #define BSON_APPEND_BINARY(b, key, subtype, val, len) \
      bson_append_binary (b, key, (int) strlen (key), subtype, val, len)
 
+  #define BSON_APPEND_BINARY_UNINIT(b, key, subtype, val, len) \
+     bson_append_binary_uninit (b, key, (int) strlen (key), subtype, val, len)
+
   #define BSON_APPEND_BOOL(b, key, val) \
      bson_append_bool (b, key, (int) strlen (key), val)
 
@@ -124,12 +127,11 @@ Synopsis
   #define BSON_APPEND_VALUE(b, key, val) \
      bson_append_value (b, key, (int) strlen (key), (val))
 
-  BSON_ALIGNED_BEGIN (128)
   typedef struct {
      uint32_t flags;       /* Internal flags for the bson_t. */
      uint32_t len;         /* Length of BSON data. */
      uint8_t padding[120]; /* Padding for stack allocation. */
-  } bson_t BSON_ALIGNED_END (128);
+  } bson_t;
 
 Description
 -----------
@@ -163,6 +165,7 @@ BSON document contains duplicate keys.
     bson_append_array_begin
     bson_append_array_end
     bson_append_binary
+    bson_append_binary_uninit
     bson_append_bool
     bson_append_code
     bson_append_code_with_scope
@@ -191,11 +194,9 @@ BSON document contains duplicate keys.
     bson_append_utf8
     bson_append_value
     bson_array_as_canonical_extended_json
-    bson_array_as_json
     bson_array_as_legacy_extended_json
     bson_array_as_relaxed_extended_json
     bson_as_canonical_extended_json
-    bson_as_json
     bson_as_json_with_opts
     bson_as_legacy_extended_json
     bson_as_relaxed_extended_json
@@ -203,7 +204,6 @@ BSON document contains duplicate keys.
     bson_concat
     bson_copy
     bson_copy_to
-    bson_copy_to_excluding
     bson_copy_to_excluding_noinit
     bson_copy_to_excluding_noinit_va
     bson_count_keys
diff -pruN 1.30.4-1/src/libbson/doc/bson_validate_flags_t.rst 2.0.2-1/src/libbson/doc/bson_validate_flags_t.rst
--- 1.30.4-1/src/libbson/doc/bson_validate_flags_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_validate_flags_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -19,6 +19,7 @@ Synopsis
     BSON_VALIDATE_DOT_KEYS = (1 << 2),
     BSON_VALIDATE_UTF8_ALLOW_NULL = (1 << 3),
     BSON_VALIDATE_EMPTY_KEYS = (1 << 4),
+    BSON_VALIDATE_CORRUPT = (1 << 5),
   } bson_validate_flags_t;
 
 Description
@@ -40,6 +41,8 @@ Each defined flag aside from ``BSON_VALI
 * ``BSON_VALIDATE_DOLLAR_KEYS`` Prohibit keys that start with ``$`` outside of a "DBRef" subdocument.
 * ``BSON_VALIDATE_DOT_KEYS`` Prohibit keys that contain ``.`` anywhere in the string.
 * ``BSON_VALIDATE_EMPTY_KEYS`` Prohibit zero-length keys.
+* ``BSON_VALIDATE_CORRUPT`` is not a control flag, but is used as an error code
+  when a validation routine encounters corrupt BSON data.
 
 .. seealso::
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_value_copy.rst 2.0.2-1/src/libbson/doc/bson_value_copy.rst
--- 1.30.4-1/src/libbson/doc/bson_value_copy.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_value_copy.rst	2025-06-19 15:42:22.000000000 +0000
@@ -21,6 +21,7 @@ Description
 -----------
 
 This function will copy the boxed content in ``src`` into ``dst``. ``dst`` must be freed with :symbol:`bson_value_destroy()` when no longer in use.
+``dst`` *MUST* be an uninitialized :symbol:`bson_value_t` to avoid leaking memory.
 
 .. note::
 
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_error_code_t.rst 2.0.2-1/src/libbson/doc/bson_vector_error_code_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_error_code_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_error_code_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,30 @@
+:man_page: bson_vector_error_code_t
+
+bson_vector_error_code_t
+========================
+
+BSON Error codes for :doc:`binary_vector` operations that could fail in multiple ways.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #define BSON_ERROR_VECTOR 4
+
+  typedef enum {
+    BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE = 1,
+    BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE = 2,
+    BSON_VECTOR_ERROR_ARRAY_KEY = 3,
+    BSON_VECTOR_ERROR_MAX_SIZE = 4,
+  } bson_vector_error_code_t;
+
+Description
+-----------
+
+The error ``code`` values in ``bson_vector_error_code_t`` apply to :symbol:`bson_error_t` values with a ``category`` of ``BSON_ERROR_CATEGORY`` and a ``domain`` of ``BSON_ERROR_VECTOR``.
+
+* ``BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE``: An element was encountered with incorrect type. Location and type details in ``message``.
+* ``BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE``: An element was encountered with out-of-range value. Location and value details in ``message``.
+* ``BSON_VECTOR_ERROR_ARRAY_KEY``: An input BSON Array did not contain the expected numeric key value. Expected and actual keys in ``message``.
+* ``BSON_VECTOR_ERROR_MAX_SIZE``: The BSON maximum document size would be exceeded. Equivalent to a failure from ``bson_append_*`` functions that do not return an ``error``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_binary_data_length.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_binary_data_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_binary_data_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_binary_data_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,31 @@
+:man_page: bson_vector_float32_binary_data_length
+
+bson_vector_float32_binary_data_length()
+========================================
+
+Calculate the size of a BSON Binary field that would be needed to store a Vector with the indicated number of ``float32`` elements.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  uint32_t
+  bson_vector_float32_binary_data_length (size_t element_count);
+
+Parameters
+----------
+
+* ``element_count``: Number of elements, as a ``size_t``.
+
+Description
+-----------
+
+Checks ``element_count`` against the maximum representable size, and calculates the required Binary size.
+
+Returns
+-------
+
+On success, returns the required Binary size as a ``uint32_t`` greater than or equal to ``BSON_VECTOR_HEADER_LEN``.
+This length includes the 2-byte Vector header, but not the Binary subtype header or any other BSON headers.
+If the ``element_count`` is too large to represent, returns 0.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_float32_const_view_from_iter
+
+bson_vector_float32_const_view_from_iter()
+==========================================
+
+Initialize a :symbol:`bson_vector_float32_const_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``float32`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_const_view_from_iter (bson_vector_float32_const_view_t *view_out,
+                                            const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_float32_const_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``float32`` element type.
+On success, a :symbol:`bson_vector_float32_const_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_view_from_iter`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,39 @@
+:man_page: bson_vector_float32_const_view_init
+
+bson_vector_float32_const_view_init()
+=====================================
+
+Initialize a :symbol:`bson_vector_float32_const_view_t` from a const ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_const_view_init (bson_vector_float32_const_view_t *view_out,
+                                       const uint8_t *binary_data,
+                                       uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_float32_const_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length and header of the provided binary data block will be checked for a valid Vector of ``float32`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_float32_const_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_view_init`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_float32_const_view_length
+
+bson_vector_float32_const_view_length()
+=======================================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_float32_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_float32_const_view_length (bson_vector_float32_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_const_view_t`.
+
+Description
+-----------
+
+An element count is calculated from the view's stored binary block length.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_view_length`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_read.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_read.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_read.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_read.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_float32_const_view_read
+
+bson_vector_float32_const_view_read()
+=====================================
+
+Copy a contiguous block of elements from a :symbol:`bson_vector_float32_const_view_t` into a C array of ``float``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_const_view_read (bson_vector_float32_const_view_t view,
+                                       float *values_out,
+                                       size_t element_count,
+                                       size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_const_view_t`.
+* ``values_out``: Location where the ``float`` elements will be read to.
+* ``element_count``: Number of elements to read.
+* ``vector_offset_elements``: The vector index of the first element to read.
+
+Description
+-----------
+
+Elements are copied in bulk from the view to the provided output pointer.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``element_count`` elements into ``*values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_view_read`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_const_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_const_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,62 @@
+:man_page: bson_vector_float32_const_view_t
+
+bson_vector_float32_const_view_t
+================================
+
+A reference to non-owned const BSON Binary data holding a valid Vector of ``float32`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_float32_const_view_t {
+     /*< private >*/
+  } bson_vector_float32_const_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_float32_const_view_t` is a structure that acts as an opaque const reference to a block of memory that has been validated as a ``float32`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_float32_const_view_init
+    bson_vector_float32_const_view_from_iter
+    bson_vector_float32_const_view_length
+    bson_vector_float32_const_view_read
+
+Example
+-------
+
+.. code-block:: c
+
+  bson_iter_t iter;
+  bson_vector_float32_const_view_t view;
+
+  if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_float32_const_view_from_iter (&view, &iter)) {
+    size_t length = bson_vector_float32_const_view_length (view);
+    printf ("Elements in 'vector':\n");
+    for (size_t i = 0; i < length; i++) {
+      float element;
+      BSON_ASSERT (bson_vector_float32_const_view_read (view, &element, 1, i));
+      printf (" [%d] = %f\n", (int) i, element);
+    }
+  }
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_as_const.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_as_const.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_as_const.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_as_const.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,29 @@
+:man_page: bson_vector_float32_view_as_const
+
+bson_vector_float32_view_as_const()
+===================================
+
+Convert a :symbol:`bson_vector_float32_view_t` into a :symbol:`bson_vector_float32_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bson_vector_float32_const_view_t
+  bson_vector_float32_view_as_const (bson_vector_float32_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_view_t`.
+
+Description
+-----------
+
+This adds a ``const`` qualifier to the view without re-validating the underlying data.
+
+Returns
+-------
+
+Always returns a :symbol:`bson_vector_float32_const_view_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_float32_view_from_iter
+
+bson_vector_float32_view_from_iter()
+====================================
+
+Initialize a :symbol:`bson_vector_float32_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``float32`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_view_from_iter (bson_vector_float32_view_t *view_out,
+                                      bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_float32_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``float32`` element type.
+On success, a :symbol:`bson_vector_float32_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or otherwise modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_const_view_from_iter`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,39 @@
+:man_page: bson_vector_float32_view_init
+
+bson_vector_float32_view_init()
+===============================
+
+Initialize a :symbol:`bson_vector_float32_view_t` from a mutable ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_view_init (bson_vector_float32_view_t *view_out,
+                                 uint8_t *binary_data,
+                                 uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_float32_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length and header of the provided binary data block will be checked for a valid Vector of ``float32`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_float32_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_const_view_init`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_float32_view_length
+
+bson_vector_float32_view_length()
+=================================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_float32_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_float32_view_length (bson_vector_float32_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_view_t`.
+
+Description
+-----------
+
+An element count is calculated from the view's stored binary block length.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_const_view_length`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_read.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_read.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_read.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_read.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_float32_view_read
+
+bson_vector_float32_view_read()
+===============================
+
+Copy a contiguous block of elements from a :symbol:`bson_vector_float32_view_t` into a C array of ``float``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_view_read (bson_vector_float32_view_t view,
+                                 float *values_out,
+                                 size_t element_count,
+                                 size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_view_t`.
+* ``values_out``: Location where the ``float`` elements will be read to.
+* ``element_count``: Number of elements to read.
+* ``vector_offset_elements``: The vector index of the first element to read.
+
+Description
+-----------
+
+Elements are copied in bulk from the view to the provided output pointer.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``element_count`` elements into ``*values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_float32_const_view_read`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,59 @@
+:man_page: bson_vector_float32_view_t
+
+bson_vector_float32_view_t
+==========================
+
+A reference to mutable non-owned BSON Binary data holding a valid Vector of ``float32`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_float32_view_t {
+     /*< private >*/
+  } bson_vector_float32_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_float32_view_t` is a structure that acts as an opaque reference to a block of memory that has been validated as a ``float32`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_float32_view_init
+    bson_vector_float32_view_from_iter
+    bson_vector_float32_view_as_const
+    bson_vector_float32_view_length
+    bson_vector_float32_view_read
+    bson_vector_float32_view_write
+
+Example
+-------
+
+.. code-block:: c
+
+  static const float values[] = {1.0f, 2.0f, 3.0f};
+  const size_t values_count = sizeof values / sizeof values[0];
+
+  bson_vector_float32_view_t view;
+  BSON_ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "vector", values_count, &view));
+  BSON_ASSERT (bson_vector_float32_view_write (view, values, values_count, 0));
+
+.. seealso::
+
+  | :symbol:`bson_append_vector_float32_uninit`
+  | :symbol:`bson_vector_float32_const_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_float32_view_write.rst 2.0.2-1/src/libbson/doc/bson_vector_float32_view_write.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_float32_view_write.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_float32_view_write.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_float32_view_write
+
+bson_vector_float32_view_write()
+================================
+
+Copy a contiguous block of elements from a C ``float`` array into a :symbol:`bson_vector_float32_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_float32_view_write (bson_vector_float32_view_t view,
+                                  const float *values,
+                                  size_t element_count,
+                                  size_t vector_offset_elements)
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_float32_view_t`.
+* ``values``: Location where the ``float`` elements will be copied from.
+* ``element_count``: Number of elements to write.
+* ``vector_offset_elements``: The vector index of the first element to write.
+
+Description
+-----------
+
+Elements are copied in bulk from the provided pointer into the view.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and writes to ``element_count`` elements in the Vector starting at ``vector_offset_elements``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_binary_data_length.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_binary_data_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_binary_data_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_binary_data_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,31 @@
+:man_page: bson_vector_int8_binary_data_length
+
+bson_vector_int8_binary_data_length()
+=====================================
+
+Calculate the size of a BSON Binary field that would be needed to store a Vector with the indicated number of ``int8`` elements.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  uint32_t
+  bson_vector_int8_binary_data_length (size_t element_count);
+
+Parameters
+----------
+
+* ``element_count``: Number of elements, as a ``size_t``.
+
+Description
+-----------
+
+Checks ``element_count`` against the maximum representable size, and calculates the required Binary size.
+
+Returns
+-------
+
+On success, returns the required Binary size as a ``uint32_t`` greater than or equal to ``BSON_VECTOR_HEADER_LEN``.
+This length includes the 2-byte Vector header, but not the Binary subtype header or any other BSON headers.
+If the ``element_count`` is too large to represent, returns 0.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_int8_const_view_from_iter
+
+bson_vector_int8_const_view_from_iter()
+=======================================
+
+Initialize a :symbol:`bson_vector_int8_const_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``int8`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_const_view_from_iter (bson_vector_int8_const_view_t *view_out,
+                                         const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_int8_const_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``int8`` element type.
+On success, a :symbol:`bson_vector_int8_const_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_from_iter`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,39 @@
+:man_page: bson_vector_int8_const_view_init
+
+bson_vector_int8_const_view_init()
+==================================
+
+Initialize a :symbol:`bson_vector_int8_const_view_t` from a const ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_const_view_init (bson_vector_int8_const_view_t *view_out,
+                                    const uint8_t *binary_data,
+                                    uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_int8_const_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length and header of the provided binary data block will be checked for a valid Vector of ``int8`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_int8_const_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_init`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_int8_const_view_length
+
+bson_vector_int8_const_view_length()
+====================================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_int8_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_int8_const_view_length (bson_vector_int8_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_const_view_t`.
+
+Description
+-----------
+
+An element count is calculated from the view's stored binary block length.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_length`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_pointer.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_pointer.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_pointer.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_pointer.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,36 @@
+:man_page: bson_vector_int8_const_view_pointer
+
+bson_vector_int8_const_view_pointer()
+=====================================
+
+Obtain a direct ``int8_t`` pointer to the Vector elements referenced by a :symbol:`bson_vector_int8_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  const int8_t *
+  bson_vector_int8_const_view_pointer (bson_vector_int8_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_const_view_t`.
+
+Description
+-----------
+
+Unwraps a vector view into a bare pointer.
+The ``int8`` Vector elements use a serialized format that's fully compatible with a C ``int8_t``.
+
+Returns
+-------
+
+A pointer derived from the pointer this View was created from.
+Its lifetime matches that of the original pointer.
+If the view was created from a :symbol:`bson_iter_t`, it will be valid until the underlying :symbol:`bson_t` is otherwise modified or destroyed.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_pointer`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_read.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_read.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_read.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_read.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_int8_const_view_read
+
+bson_vector_int8_const_view_read()
+==================================
+
+Copy a contiguous block of elements from a :symbol:`bson_vector_int8_const_view_t` into a C array of ``int8_t``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_const_view_read (bson_vector_int8_const_view_t view,
+                                    int8_t *values_out,
+                                    size_t element_count,
+                                    size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_const_view_t`.
+* ``values_out``: Location where the ``int8_t`` elements will be read to.
+* ``element_count``: Number of elements to read.
+* ``vector_offset_elements``: The vector index of the first element to read.
+
+Description
+-----------
+
+Elements are copied in bulk from the view to the provided output pointer.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``element_count`` elements into ``*values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_read`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_const_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_const_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,63 @@
+:man_page: bson_vector_int8_const_view_t
+
+bson_vector_int8_const_view_t
+=============================
+
+A reference to non-owned const BSON Binary data holding a valid Vector of ``int8`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_int8_const_view_t {
+     /*< private >*/
+  } bson_vector_int8_const_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_int8_const_view_t` is a structure that acts as an opaque const reference to a block of memory that has been validated as an ``int8`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_int8_const_view_init
+    bson_vector_int8_const_view_from_iter
+    bson_vector_int8_const_view_length
+    bson_vector_int8_const_view_read
+    bson_vector_int8_const_view_pointer
+
+Example
+-------
+
+.. code-block:: c
+
+  bson_iter_t iter;
+  bson_vector_int8_const_view_t view;
+
+  if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_int8_const_view_from_iter (&view, &iter)) {
+    size_t length = bson_vector_int8_const_view_length (view);
+    printf ("Elements in 'vector':\n");
+    for (size_t i = 0; i < length; i++) {
+      int8_t element;
+      BSON_ASSERT (bson_vector_int8_const_view_read (view, &element, 1, i));
+      printf (" [%d] = %d\n", (int) i, (int) element);
+    }
+  }
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_as_const.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_as_const.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_as_const.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_as_const.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,29 @@
+:man_page: bson_vector_int8_view_as_const
+
+bson_vector_int8_view_as_const()
+================================
+
+Convert a :symbol:`bson_vector_int8_view_t` into a :symbol:`bson_vector_int8_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bson_vector_int8_const_view_t
+  bson_vector_int8_view_as_const (bson_vector_int8_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_view_t`.
+
+Description
+-----------
+
+This adds a ``const`` qualifier to the view without re-validating the underlying data.
+
+Returns
+-------
+
+Always returns a :symbol:`bson_vector_int8_const_view_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_int8_view_from_iter
+
+bson_vector_int8_view_from_iter()
+=================================
+
+Initialize a :symbol:`bson_vector_int8_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``int8`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_view_from_iter (bson_vector_int8_view_t *view_out,
+                                   bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_int8_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``int8`` element type.
+On success, a :symbol:`bson_vector_int8_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or otherwise modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_const_view_from_iter`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,39 @@
+:man_page: bson_vector_int8_view_init
+
+bson_vector_int8_view_init()
+============================
+
+Initialize a :symbol:`bson_vector_int8_view_t` from a mutable ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_view_init (bson_vector_int8_view_t *view_out,
+                              uint8_t *binary_data,
+                              uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_int8_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length and header of the provided binary data block will be checked for a valid Vector of ``int8`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_int8_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_const_view_init`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_int8_view_length
+
+bson_vector_int8_view_length()
+==============================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_int8_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_int8_view_length (bson_vector_int8_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_view_t`.
+
+Description
+-----------
+
+An element count is calculated from the view's stored binary block length.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_const_view_length`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_pointer.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_pointer.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_pointer.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_pointer.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,36 @@
+:man_page: bson_vector_int8_view_pointer
+
+bson_vector_int8_view_pointer()
+===============================
+
+Obtain a direct ``int8_t`` pointer to the Vector elements referenced by a :symbol:`bson_vector_int8_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  int8_t *
+  bson_vector_int8_view_pointer (bson_vector_int8_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_view_t`.
+
+Description
+-----------
+
+Unwraps a vector view into a bare pointer.
+The ``int8`` Vector elements use a serialized format that's fully compatible with a C ``int8_t``.
+
+Returns
+-------
+
+A pointer derived from the pointer this View was created from.
+Its lifetime matches that of the original pointer.
+If the view was created from a :symbol:`bson_iter_t`, it will be valid until the underlying :symbol:`bson_t` is otherwise modified or destroyed.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_const_view_pointer`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_read.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_read.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_read.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_read.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_int8_view_read
+
+bson_vector_int8_view_read()
+============================
+
+Copy a contiguous block of elements from a :symbol:`bson_vector_int8_view_t` into a C array of ``int8_t``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_view_read (bson_vector_int8_view_t view,
+                              int8_t *values_out,
+                              size_t element_count,
+                              size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_view_t`.
+* ``values_out``: Location where the ``int8_t`` elements will be read to.
+* ``element_count``: Number of elements to read.
+* ``vector_offset_elements``: The vector index of the first element to read.
+
+Description
+-----------
+
+Elements are copied in bulk from the view to the provided output pointer.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``element_count`` elements into ``*values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_int8_const_view_read`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,60 @@
+:man_page: bson_vector_int8_view_t
+
+bson_vector_int8_view_t
+=======================
+
+A reference to mutable non-owned BSON Binary data holding a valid Vector of ``int8`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_int8_view_t {
+     /*< private >*/
+  } bson_vector_int8_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_int8_view_t` is a structure that acts as an opaque reference to a block of memory that has been validated as an ``int8`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_int8_view_init
+    bson_vector_int8_view_from_iter
+    bson_vector_int8_view_as_const
+    bson_vector_int8_view_length
+    bson_vector_int8_view_read
+    bson_vector_int8_view_write
+    bson_vector_int8_view_pointer
+
+Example
+-------
+
+.. code-block:: c
+
+  static const int8_t values[] = {1, 2, 3};
+  const size_t values_count = sizeof values / sizeof values[0];
+
+  bson_vector_int8_view_t view;
+  BSON_ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "vector", values_count, &view));
+  BSON_ASSERT (bson_vector_int8_view_write (view, values, values_count, 0));
+
+.. seealso::
+
+  | :symbol:`bson_append_vector_int8_uninit`
+  | :symbol:`bson_vector_int8_const_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_int8_view_write.rst 2.0.2-1/src/libbson/doc/bson_vector_int8_view_write.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_int8_view_write.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_int8_view_write.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_int8_view_write
+
+bson_vector_int8_view_write()
+=============================
+
+Copy a contiguous block of elements from a C ``int8_t`` array into a :symbol:`bson_vector_int8_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_int8_view_write (bson_vector_int8_view_t view,
+                               const int8_t *values,
+                               size_t element_count,
+                               size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_int8_view_t`.
+* ``values``: Location where the ``int8_t`` elements will be copied from.
+* ``element_count``: Number of elements to write.
+* ``vector_offset_elements``: The vector index of the first element to write.
+
+Description
+-----------
+
+Elements are copied in bulk from the provided pointer into the view.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and writes to ``element_count`` elements in the Vector starting at ``vector_offset_elements``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_binary_data_length.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_binary_data_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_binary_data_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_binary_data_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,31 @@
+:man_page: bson_vector_packed_bit_binary_data_length
+
+bson_vector_packed_bit_binary_data_length()
+===========================================
+
+Calculate the size of a BSON Binary field that would be needed to store a Vector with the indicated number of ``packed_bit`` elements.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  uint32_t
+  bson_vector_packed_bit_binary_data_length (size_t element_count);
+
+Parameters
+----------
+
+* ``element_count``: Number of single-bit elements, as a ``size_t``.
+
+Description
+-----------
+
+Checks ``element_count`` against the maximum representable size, and calculates the required Binary size.
+
+Returns
+-------
+
+On success, returns the required Binary size as a ``uint32_t`` greater than or equal to ``BSON_VECTOR_HEADER_LEN``.
+This length includes the 2-byte Vector header, but not the Binary subtype header or any other BSON headers.
+If the ``element_count`` is too large to represent, returns 0.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_packed_bit_const_view_from_iter
+
+bson_vector_packed_bit_const_view_from_iter()
+=============================================
+
+Initialize a :symbol:`bson_vector_packed_bit_const_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``packed_bit`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_const_view_from_iter (bson_vector_packed_bit_const_view_t *view_out,
+                                               const bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_packed_bit_const_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``packed_bit`` element type.
+On success, a :symbol:`bson_vector_packed_bit_const_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_from_iter`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,39 @@
+:man_page: bson_vector_packed_bit_const_view_init
+
+bson_vector_packed_bit_const_view_init()
+========================================
+
+Initialize a :symbol:`bson_vector_packed_bit_const_view_t` from a const ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_const_view_init (bson_vector_packed_bit_const_view_t *view_out,
+                                          const uint8_t *binary_data,
+                                          uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_packed_bit_const_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length, header, and trailing padding of the provided binary data block will be checked for a valid Vector of ``packed_bit`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_packed_bit_const_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_init`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_packed_bit_const_view_length
+
+bson_vector_packed_bit_const_view_length()
+==========================================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_const_view_length (bson_vector_packed_bit_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Description
+-----------
+
+An element count is calculated from information stored inside the `bson_vector_packed_bit_const_view_t` value.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_length`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_length_bytes.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_length_bytes.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_length_bytes.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_length_bytes.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,34 @@
+:man_page: bson_vector_packed_bit_const_view_length_bytes
+
+bson_vector_packed_bit_const_view_length_bytes()
+================================================
+
+Return the number of packed bytes in a Vector referenced by a :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_const_view_length_bytes (bson_vector_packed_bit_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Description
+-----------
+
+A byte count is calculated from the view's stored binary block length.
+If the element count isn't a multiple of 8, the final byte will include bits that do not belong to any element.
+
+Returns
+-------
+
+The number of bytes, as a ``size_t``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_length_bytes`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_padding.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_padding.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_padding.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_padding.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,34 @@
+:man_page: bson_vector_packed_bit_const_view_padding
+
+bson_vector_packed_bit_const_view_padding()
+===========================================
+
+Returns the number of unused bits in a Vector referenced by a :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_const_view_padding (bson_vector_packed_bit_const_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Description
+-----------
+
+The 3-bit ``padding`` field is extracted from a copy of the Vector header inside ``view``.
+
+Returns
+-------
+
+The number of unused bits in the final packed byte. Guaranteed to be between 0 and 7 inclusive.
+Vector validation guarantees that empty Vectors have a ``padding`` of 0.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_padding`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_read_packed.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_read_packed.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_read_packed.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_read_packed.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,45 @@
+:man_page: bson_vector_packed_bit_const_view_read_packed
+
+bson_vector_packed_bit_const_view_read_packed()
+===============================================
+
+Copy a contiguous block of packed bytes out of a :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_const_view_read_packed (bson_vector_packed_bit_const_view_t view,
+                                                 uint8_t *packed_values_out,
+                                                 size_t byte_count,
+                                                 size_t vector_offset_bytes);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_const_view_t`.
+* ``packed_values_out``: Location where the packed bytes will be read to.
+* ``byte_count``: Number of bytes to read.
+* ``vector_offset_bytes``: The byte index of the first packed byte to read.
+
+Description
+-----------
+
+Packed bytes are copied in bulk from the view to the provided output pointer.
+
+If the Vector's element count isn't a multiple of 8, its final byte will include bits that do not belong to any element.
+Vector validation checks that these bits are zero.
+
+Returns
+-------
+
+If the ``byte_count`` and ``vector_offset_bytes`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``byte_count`` bytes into ``*packed_values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_read_packed`
+  | :symbol:`bson_vector_packed_bit_view_write_packed`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,75 @@
+:man_page: bson_vector_packed_bit_const_view_t
+
+bson_vector_packed_bit_const_view_t
+===================================
+
+A reference to non-owned const BSON Binary data holding a valid Vector of ``packed_bit`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_packed_bit_const_view_t {
+     /*< private >*/
+  } bson_vector_packed_bit_const_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_packed_bit_const_view_t` is a structure that acts as an opaque const reference to a block of memory that has been validated as a ``packed_bit`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_packed_bit_const_view_init
+    bson_vector_packed_bit_const_view_from_iter
+    bson_vector_packed_bit_const_view_length
+    bson_vector_packed_bit_const_view_length_bytes
+    bson_vector_packed_bit_const_view_padding
+    bson_vector_packed_bit_const_view_read_packed
+    bson_vector_packed_bit_const_view_unpack_bool
+
+Example
+-------
+
+.. code-block:: c
+
+  bson_iter_t iter;
+  bson_vector_packed_bit_const_view_t view;
+
+  if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_packed_bit_const_view_from_iter (&view, &iter)) {
+    size_t length = bson_vector_packed_bit_const_view_length (view);
+    size_t length_bytes = bson_vector_packed_bit_const_view_length_bytes (view);
+    size_t padding = bson_vector_packed_bit_const_view_padding (view);
+
+    printf ("Elements in 'vector':\n");
+    for (size_t i = 0; i < length; i++) {
+      bool element;
+      BSON_ASSERT (bson_vector_packed_bit_const_view_unpack_bool (view, &element, 1, i));
+      printf (" elements[%d] = %d\n", (int) i, (int) element);
+    }
+
+    printf ("Bytes in 'vector': (%d bits unused)\n", (int) padding);
+    for (size_t i = 0; i < length_bytes; i++) {
+      uint8_t packed_byte;
+      BSON_ASSERT (bson_vector_packed_bit_const_view_read_packed (view, &packed_byte, 1, i));
+      printf (" bytes[%d] = 0x%02x\n", (int) i, (unsigned) packed_byte);
+    }
+  }
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_unpack_bool.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_unpack_bool.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_const_view_unpack_bool.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_const_view_unpack_bool.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_packed_bit_const_view_unpack_bool
+
+bson_vector_packed_bit_const_view_unpack_bool()
+===============================================
+
+Unpack a contiguous block of elements from a :symbol:`bson_vector_packed_bit_const_view_t` into a C array of ``bool``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_const_view_unpack_bool (bson_vector_packed_bit_const_view_t view,
+                                                 bool *unpacked_values_out,
+                                                 size_t element_count,
+                                                 size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_const_view_t`.
+* ``unpacked_values_out``: Location where the ``bool`` elements will be unpacked to.
+* ``element_count``: Number of elements to unpack.
+* ``vector_offset_elements``: The vector index of the first element to unpack.
+
+Description
+-----------
+
+Elements are unpacked from individual bits into a C array of ``bool``.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and unpacks ``element_count`` elements into ``*unpacked_values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_unpack_bool`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_as_const.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_as_const.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_as_const.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_as_const.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,29 @@
+:man_page: bson_vector_packed_bit_view_as_const
+
+bson_vector_packed_bit_view_as_const()
+======================================
+
+Convert a :symbol:`bson_vector_packed_bit_view_t` into a :symbol:`bson_vector_packed_bit_const_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bson_vector_packed_bit_const_view_t
+  bson_vector_packed_bit_view_as_const (bson_vector_packed_bit_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+
+Description
+-----------
+
+This adds a ``const`` qualifier to the view without re-validating the underlying data.
+
+Returns
+-------
+
+Always returns a :symbol:`bson_vector_packed_bit_const_view_t`.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_from_iter.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_from_iter.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_from_iter.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_from_iter.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,33 @@
+:man_page: bson_vector_packed_bit_view_from_iter
+
+bson_vector_packed_bit_view_from_iter()
+=======================================
+
+Initialize a :symbol:`bson_vector_packed_bit_view_t` from a :symbol:`bson_iter_t` pointing to a valid Vector of ``packed_bit`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_from_iter (bson_vector_packed_bit_view_t *view_out,
+                                         bson_iter_t *iter);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_packed_bit_view_t` is written here on success.
+* ``iter``: A valid :symbol:`bson_iter_t`.
+
+Description
+-----------
+
+The provided iterator, which must point to some kind of BSON item, will be checked for a valid Vector of ``packed_bit`` element type.
+On success, a :symbol:`bson_vector_packed_bit_view_t` is set to point to the same underlying :symbol:`bson_t` buffer as the provided :symbol:`bson_iter_t`.
+The view will only be valid until the containing document is destroyed or otherwise modified.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_init.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_init.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_init.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_init.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,35 @@
+:man_page: bson_vector_packed_bit_view_init
+
+bson_vector_packed_bit_view_init()
+==================================
+
+Initialize a :symbol:`bson_vector_packed_bit_view_t` from a mutable ``uint8_t`` buffer.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_init (bson_vector_packed_bit_view_t *view_out,
+                                    uint8_t *binary_data,
+                                    uint32_t binary_data_len);
+
+Parameters
+----------
+
+* ``view_out``: A :symbol:`bson_vector_packed_bit_view_t` is written here on success.
+* ``binary_data``: A pointer to the BSON Binary data block to be validated.
+* ``binary_data_len``: Length of the binary data block, in bytes.
+
+Description
+-----------
+
+The length, header, and trailing padding of the provided binary data block will be checked for a valid Vector of ``packed_bit`` element type.
+On success, the pointer and length are packaged as a :symbol:`bson_vector_packed_bit_view_t` written to ``*view_out``.
+The view will only be valid as long as ``binary_data`` is valid.
+
+Returns
+-------
+
+Returns true if the view was successfully initialized.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_length.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_length.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_length.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_length.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,29 @@
+:man_page: bson_vector_packed_bit_view_length
+
+bson_vector_packed_bit_view_length()
+====================================
+
+Return the number of elements in a Vector referenced by a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_view_length (bson_vector_packed_bit_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+
+Description
+-----------
+
+An element count is calculated from information stored inside the `bson_vector_packed_bit_view_t` value.
+
+Returns
+-------
+
+The number of elements, as a ``size_t``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_length_bytes.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_length_bytes.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_length_bytes.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_length_bytes.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,30 @@
+:man_page: bson_vector_packed_bit_view_length_bytes
+
+bson_vector_packed_bit_view_length_bytes()
+==========================================
+
+Return the number of packed bytes in a Vector referenced by a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_view_length_bytes (bson_vector_packed_bit_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+
+Description
+-----------
+
+A byte count is calculated from the view's stored binary block length.
+If the element count isn't a multiple of 8, the final byte will include bits that do not belong to any element.
+
+Returns
+-------
+
+The number of bytes, as a ``size_t``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_pack_bool.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_pack_bool.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_pack_bool.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_pack_bool.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+:man_page: bson_vector_packed_bit_view_pack_bool
+
+bson_vector_packed_bit_view_pack_bool()
+=======================================
+
+Pack a contiguous block of elements from a C ``bool`` array into a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_pack_bool (bson_vector_packed_bit_view_t view,
+                                         const bool *unpacked_values,
+                                         size_t element_count,
+                                         size_t vector_offset_elements)
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+* ``unpacked_values``: Location where the ``bool`` elements will be packed from.
+* ``element_count``: Number of elements to pack.
+* ``vector_offset_elements``: The vector index of the first element to pack.
+
+Description
+-----------
+
+Elements are packed into individual Vector bits from a C ``bool`` array.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and writes to ``element_count`` elements in the Vector starting at ``vector_offset_elements``.
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_padding.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_padding.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_padding.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_padding.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,34 @@
+:man_page: bson_vector_packed_bit_view_padding
+
+bson_vector_packed_bit_view_padding()
+=====================================
+
+Returns the number of unused bits in a Vector referenced by a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  size_t
+  bson_vector_packed_bit_view_padding (bson_vector_packed_bit_view_t view);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+
+Description
+-----------
+
+The 3-bit ``padding`` field is extracted from a copy of the Vector header inside ``view``.
+
+Returns
+-------
+
+The number of unused bits in the final packed byte. Guaranteed to be between 0 and 7 inclusive.
+Vector validation guarantees that empty Vectors have a ``padding`` of 0.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_const_view_padding`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_read_packed.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_read_packed.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_read_packed.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_read_packed.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,45 @@
+:man_page: bson_vector_packed_bit_view_read_packed
+
+bson_vector_packed_bit_view_read_packed()
+=========================================
+
+Copy a contiguous block of packed bytes out of a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_read_packed (bson_vector_packed_bit_view_t view,
+                                           uint8_t *packed_values_out,
+                                           size_t byte_count,
+                                           size_t vector_offset_bytes);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+* ``packed_values_out``: Location where the packed bytes will be read to.
+* ``byte_count``: Number of bytes to read.
+* ``vector_offset_bytes``: The byte index of the first packed byte to read.
+
+Description
+-----------
+
+Packed bytes are copied in bulk from the view to the provided output pointer.
+
+If the Vector's element count isn't a multiple of 8, its final byte will include bits that do not belong to any element.
+Vector validation checks that these bits are zero.
+
+Returns
+-------
+
+If the ``byte_count`` and ``vector_offset_bytes`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and reads ``byte_count`` bytes into ``*packed_values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_const_view_read_packed`
+  | :symbol:`bson_vector_packed_bit_view_write_packed`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_t.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_t.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_t.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,85 @@
+:man_page: bson_vector_packed_bit_view_t
+
+bson_vector_packed_bit_view_t
+=============================
+
+A reference to mutable non-owned BSON Binary data holding a valid Vector of ``packed_bit`` element type.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  #include <bson/bson.h>
+
+  typedef struct bson_vector_packed_bit_view_t {
+     /*< private >*/
+  } bson_vector_packed_bit_view_t;
+
+Description
+-----------
+
+:symbol:`bson_vector_packed_bit_view_t` is a structure that acts as an opaque reference to a block of memory that has been validated as a ``packed_bit`` vector.
+
+It is meant to be passed by value and can be discarded at any time. The contents of the structure should be considered private.
+
+The :symbol:`bson_t` *MUST* be valid for the lifetime of the view and it is an error to modify the :symbol:`bson_t` while using the view.
+
+.. only:: html
+
+  Functions
+  ---------
+
+  .. toctree::
+    :titlesonly:
+    :maxdepth: 1
+
+    bson_vector_packed_bit_view_init
+    bson_vector_packed_bit_view_from_iter
+    bson_vector_packed_bit_view_as_const
+    bson_vector_packed_bit_view_length
+    bson_vector_packed_bit_view_length_bytes
+    bson_vector_packed_bit_view_padding
+    bson_vector_packed_bit_view_read_packed
+    bson_vector_packed_bit_view_write_packed
+    bson_vector_packed_bit_view_unpack_bool
+    bson_vector_packed_bit_view_pack_bool
+
+Example
+-------
+
+.. code-block:: c
+
+  // Fill a new vector with individual boolean elements
+  {
+      static const bool bool_values[] = {true, false, true, true, false};
+      const size_t bool_values_count = sizeof bool_values / sizeof bool_values[0];
+
+      bson_vector_packed_bit_view_t view;
+      BSON_ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "from_bool", bool_values_count, &view));
+      BSON_ASSERT (bson_vector_packed_bit_view_pack_bool (view, bool_values, bool_values_count, 0));
+  }
+
+  // Fill another new vector with packed bytes
+  {
+      static const uint8_t packed_bytes[] = {0xb0};
+      const size_t unused_bits_count = 3;
+      const size_t packed_values_count = sizeof packed_bytes * 8 - unused_bits_count;
+
+      bson_vector_packed_bit_view_t view;
+      BSON_ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "from_packed", packed_values_count, &view));
+      BSON_ASSERT (bson_vector_packed_bit_view_write_packed (view, packed_bytes, sizeof packed_bytes, 0));
+  }
+
+  // Compare both vectors. They match exactly.
+  {
+      bson_iter_t from_bool_iter, from_packed_iter;
+      BSON_ASSERT (bson_iter_init_find (&from_bool_iter, &doc, "from_bool"));
+      BSON_ASSERT (bson_iter_init_find (&from_packed_iter, &doc, "from_packed"));
+      BSON_ASSERT (bson_iter_binary_equal (&from_bool_iter, &from_packed_iter));
+  }
+
+.. seealso::
+
+  | :symbol:`bson_append_vector_packed_bit_uninit`
+  | :symbol:`bson_vector_packed_bit_const_view_t`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_unpack_bool.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_unpack_bool.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_unpack_bool.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_unpack_bool.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,41 @@
+:man_page: bson_vector_packed_bit_view_unpack_bool
+
+bson_vector_packed_bit_view_unpack_bool()
+=========================================
+
+Unpack a contiguous block of elements from a :symbol:`bson_vector_packed_bit_view_t` into a C array of ``bool``.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_unpack_bool (bson_vector_packed_bit_view_t view,
+                                           bool *unpacked_values_out,
+                                           size_t element_count,
+                                           size_t vector_offset_elements);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+* ``unpacked_values_out``: Location where the ``bool`` elements will be unpacked to.
+* ``element_count``: Number of elements to unpack.
+* ``vector_offset_elements``: The vector index of the first element to unpack.
+
+Description
+-----------
+
+Elements are unpacked from individual bits into a C array of ``bool``.
+
+Returns
+-------
+
+If the ``element_count`` and ``vector_offset_elements`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and unpacks ``element_count`` elements into ``*unpacked_values_out``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_const_view_unpack_bool`
diff -pruN 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_write_packed.rst 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_write_packed.rst
--- 1.30.4-1/src/libbson/doc/bson_vector_packed_bit_view_write_packed.rst	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_vector_packed_bit_view_write_packed.rst	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,45 @@
+:man_page: bson_vector_packed_bit_view_write_packed
+
+bson_vector_packed_bit_view_write_packed()
+==========================================
+
+Copy a contiguous block of packed bytes into a :symbol:`bson_vector_packed_bit_view_t`.
+
+Synopsis
+--------
+
+.. code-block:: c
+
+  bool
+  bson_vector_packed_bit_view_write_packed (bson_vector_packed_bit_view_t view,
+                                            const uint8_t *packed_values,
+                                            size_t byte_count,
+                                            size_t vector_offset_bytes);
+
+Parameters
+----------
+
+* ``view``: A valid :symbol:`bson_vector_packed_bit_view_t`.
+* ``packed_values``: Location where the packed bytes will be copied from.
+* ``byte_count``: Number of bytes to write.
+* ``vector_offset_bytes``: The byte index of the first packed byte to write.
+
+Description
+-----------
+
+Packed bytes are copied in bulk from the input pointer to the provided view.
+
+If the Vector's element count isn't a multiple of 8, its final byte will include bits that do not belong to any element.
+This function cannot be used to modify the unused bits, they will be explicitly zeroed if set.
+
+Returns
+-------
+
+If the ``byte_count`` and ``vector_offset_bytes`` parameters overflow the bounds of the Vector, returns false without taking any other action.
+If the parameters are in range, this is guaranteed to succeed.
+On success, returns true and writes ``byte_count`` bytes from ``*packed_values`` into the Vector starting at byte index ``vector_offset_bytes``.
+
+.. seealso::
+
+  | :symbol:`bson_vector_packed_bit_view_read_packed`
+  | :symbol:`bson_vector_packed_bit_const_view_read_packed`
diff -pruN 1.30.4-1/src/libbson/doc/bson_writer_t.rst 2.0.2-1/src/libbson/doc/bson_writer_t.rst
--- 1.30.4-1/src/libbson/doc/bson_writer_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/bson_writer_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -61,9 +61,9 @@ Example
 
      writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
 
-     for (i = 0; i < 1000; i++) {
+     for (int i = 0; i < 1000; i++) {
         bson_writer_begin (writer, &doc);
-        BSON_APPEND_INT32 (&doc, "i", i);
+        BSON_APPEND_INT32 (doc, "i", i);
         bson_writer_end (writer);
      }
 
diff -pruN 1.30.4-1/src/libbson/doc/includes/seealso/bson-as-json.txt 2.0.2-1/src/libbson/doc/includes/seealso/bson-as-json.txt
--- 1.30.4-1/src/libbson/doc/includes/seealso/bson-as-json.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/doc/includes/seealso/bson-as-json.txt	2025-06-19 15:42:22.000000000 +0000
@@ -5,8 +5,6 @@
 
   | :symbol:`bson_as_legacy_extended_json()`
 
-  | :symbol:`bson_as_json()` (Deprecated)
-
   | :symbol:`bson_as_json_with_opts()`
 
   | :symbol:`bson_array_as_canonical_extended_json()`
@@ -15,5 +13,3 @@
 
   | :symbol:`bson_array_as_legacy_extended_json()`
 
-  | :symbol:`bson_array_as_json()` (Deprecated)
-
diff -pruN 1.30.4-1/src/libbson/etc/bsonConfig.cmake 2.0.2-1/src/libbson/etc/bsonConfig.cmake
--- 1.30.4-1/src/libbson/etc/bsonConfig.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/etc/bsonConfig.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -1,16 +1,15 @@
 #[[
-    This is a transitional CMake package config file to allow compatibility
-    between libbson 1.x and libbson 2.x CMake packages.
+    CMake package file for the BSON library.
 
-    When distributed with libbson 1.x, this file is mostly just a shim for
-    the `bson-1.0` CMake packages.
+    This file globs and includes all "*-targets.cmake" files in the containing
+    directory, and intends that those files define the actual libbson targets.
 
-    This file imports "bson-1.0" and generates alias targets for it:
+    This file also defines a `bson::bson` target, which redirects to either
+    `bson::static` or `bson::shared` depending on what type of library is
+    available and can be controlled with an import-time CMake setting.
 
-    • `bson::shared` → `mongo::bson_shared`
-    • `bson::static` → `mongo::bson_static`
-    • `bson::bson` → Points to either `bson::shared` or `bson::static`,
-        controlled by `BSON_DEFAULT_IMPORTED_LIBRARY_TYPE`
+    If the installation has a static library, it is named `bson::static`. If
+    the installation has a shared (dynamic) library, it is named `bson::shared`.
 ]]
 
 # Check for missing components before proceeding. We don't provide any, so we
@@ -31,35 +30,29 @@ if(missing_required_components)
 endif()
 
 include(CMakeFindDependencyMacro)
+find_dependency(Threads)  # Required for Threads::Threads
 
-# We are installed alongside the `bson-1.0` packages. Forcibly prevent find_package
-# from considering any other `bson-1.0` package that might live elsewhere on the system
-# by setting HINTS and NO_DEFAULT_PATH
-get_filename_component(parent_dir "${CMAKE_CURRENT_LIST_DIR}" DIRECTORY)
-find_dependency(bson-1.0 HINTS ${parent_dir} NO_DEFAULT_PATH)
+# Import the target files that will be installed alongside this file. Only the
+# targets of libraries that were actually installed alongside this file will be imported
+file(GLOB __targets_files "${CMAKE_CURRENT_LIST_DIR}/*-targets.cmake")
+foreach(__file IN LISTS __targets_files)
+    include("${__file}")
+endforeach()
 
 # The library type that is linked with `bson::bson`
-set(_default_lib_type)
-# Add compat targets for the bson-1.0 package targets
-if(TARGET mongo::bson_shared AND NOT TARGET bson::shared)
-    add_library(bson::shared IMPORTED INTERFACE)
-    set_property(TARGET bson::shared APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongo::bson_shared)
-    set(_default_lib_type SHARED)
-endif()
-if(TARGET mongo::bson_static AND NOT TARGET bson::static)
-    add_library(bson::static IMPORTED INTERFACE)
-    set_property(TARGET bson::static APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongo::bson_static)
+set(__default_lib_type SHARED)
+if(TARGET bson::static)
     # If static is available, set it as the default library type
-    set(_default_lib_type STATIC)
+    set(__default_lib_type STATIC)
 endif()
 
 # Allow the user to tweak what library type is linked for `bson::bson`
-set(BSON_DEFAULT_IMPORTED_LIBRARY_TYPE "${_default_lib_type}"
+set(BSON_DEFAULT_IMPORTED_LIBRARY_TYPE "${__default_lib_type}"
     CACHE STRING "The default library type that is used when linking against 'bson::bson' (either SHARED or STATIC, requires that the package was built with the appropriate library type)")
 set_property(CACHE BSON_DEFAULT_IMPORTED_LIBRARY_TYPE PROPERTY STRINGS SHARED STATIC)
 
 if(NOT TARGET bson::bson)  # Don't redefine the target if we were already included
-    string(TOLOWER "${BSON_DEFAULT_IMPORTED_LIBRARY_TYPE}" _type)
+    string(TOLOWER "${BSON_DEFAULT_IMPORTED_LIBRARY_TYPE}" __type)
     add_library(bson::bson IMPORTED INTERFACE)
-    set_property(TARGET bson::bson APPEND PROPERTY INTERFACE_LINK_LIBRARIES bson::${_type})
+    set_property(TARGET bson::bson APPEND PROPERTY INTERFACE_LINK_LIBRARIES bson::${__type})
 endif()
diff -pruN 1.30.4-1/src/libbson/examples/bson-metrics.c 2.0.2-1/src/libbson/examples/bson-metrics.c
--- 1.30.4-1/src/libbson/examples/bson-metrics.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/bson-metrics.c	2025-06-19 15:42:22.000000000 +0000
@@ -252,7 +252,7 @@ main (int argc, char *argv[])
       mark = 0;
       while ((b = bson_reader_read (reader, NULL))) {
          off_t pos = bson_reader_tell (reader);
-         state.doc_size_max = BSON_MAX (pos - mark, state.doc_size_max);
+         state.doc_size_max = BSON_MAX (pos - mark, (off_t) state.doc_size_max);
          mark = pos;
          bson_metrics (b, NULL, &state);
       }
diff -pruN 1.30.4-1/src/libbson/examples/cmake/find_package/CMakeLists.txt 2.0.2-1/src/libbson/examples/cmake/find_package/CMakeLists.txt
--- 1.30.4-1/src/libbson/examples/cmake/find_package/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/cmake/find_package/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@ project (hello_bson LANGUAGES C)
 # building libbson.
 # -- sphinx-include-start --
 # Specify the minimum version you require.
-find_package (bson 1.7 REQUIRED)
+find_package (bson 2.0 REQUIRED)
 
 # The "hello_bson.c" sample program is shared among four tests.
 add_executable (hello_bson ../../hello_bson.c)
diff -pruN 1.30.4-1/src/libbson/examples/cmake/find_package_static/CMakeLists.txt 2.0.2-1/src/libbson/examples/cmake/find_package_static/CMakeLists.txt
--- 1.30.4-1/src/libbson/examples/cmake/find_package_static/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/cmake/find_package_static/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@ project (hello_bson LANGUAGES C)
 # building libbson.
 # -- sphinx-include-start --
 # Specify the minimum version you require.
-find_package (bson 1.7 REQUIRED)
+find_package (bson 2.0 REQUIRED)
 
 # The "hello_bson.c" sample program is shared among four tests.
 add_executable (hello_bson ../../hello_bson.c)
diff -pruN 1.30.4-1/src/libbson/examples/cmake-deprecated/.gitignore 2.0.2-1/src/libbson/examples/cmake-deprecated/.gitignore
--- 1.30.4-1/src/libbson/examples/cmake-deprecated/.gitignore	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/cmake-deprecated/.gitignore	1970-01-01 00:00:00.000000000 +0000
@@ -1,6 +0,0 @@
-CMakeCache.txt
-CMakeFiles
-Makefile
-cmake_install.cmake
-hello_bson
-build
diff -pruN 1.30.4-1/src/libbson/examples/cmake-deprecated/find_package/CMakeLists.txt 2.0.2-1/src/libbson/examples/cmake-deprecated/find_package/CMakeLists.txt
--- 1.30.4-1/src/libbson/examples/cmake-deprecated/find_package/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/cmake-deprecated/find_package/CMakeLists.txt	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Demonstrates how to use the CMake 'find_package' mechanism to locate
-# and build against libbson.
-
-cmake_minimum_required (VERSION 2.8)
-
-project (hello_bson LANGUAGES C)
-
-# NOTE: For this to work, the CMAKE_PREFIX_PATH variable must be set to point to
-# the directory that was used as the argument to CMAKE_INSTALL_PREFIX when
-# building libbson.
-# -- sphinx-include-start --
-# Specify the minimum version you require.
-find_package (libbson-1.0 1.7 REQUIRED)
-
-message (STATUS "   libbson found version \"${BSON_VERSION}\"")
-message (STATUS "   libbson include path \"${BSON_INCLUDE_DIRS}\"")
-message (STATUS "   libbson libraries \"${BSON_LIBRARIES}\"")
-
-# The "hello_bson.c" sample program is shared among four tests.
-add_executable (hello_bson ../../hello_bson.c)
-target_include_directories (hello_bson PRIVATE ${BSON_INCLUDE_DIRS})
-target_link_libraries (hello_bson PRIVATE ${BSON_LIBRARIES})
-target_compile_definitions (hello_bson PRIVATE ${BSON_DEFINITIONS})
diff -pruN 1.30.4-1/src/libbson/examples/cmake-deprecated/find_package_static/CMakeLists.txt 2.0.2-1/src/libbson/examples/cmake-deprecated/find_package_static/CMakeLists.txt
--- 1.30.4-1/src/libbson/examples/cmake-deprecated/find_package_static/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/cmake-deprecated/find_package_static/CMakeLists.txt	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Demonstrates how to use the CMake 'find_package' mechanism to locate
-# and build against libbson.
-
-cmake_minimum_required (VERSION 2.8)
-
-project (hello_bson LANGUAGES C)
-
-# NOTE: For this to work, the CMAKE_PREFIX_PATH variable must be set to point to
-# the directory that was used as the argument to CMAKE_INSTALL_PREFIX when
-# building libbson.
-# -- sphinx-include-start --
-# Specify the minimum version you require.
-find_package (libbson-static-1.0 1.7 REQUIRED)
-
-message (STATUS "   libbson-static found version \"${BSON_STATIC_VERSION}\"")
-message (STATUS "   libbson-static include path \"${BSON_STATIC_INCLUDE_DIRS}\"")
-message (STATUS "   libbson-static libraries \"${BSON_STATIC_LIBRARIES}\"")
-
-# The "hello_bson.c" sample program is shared among four tests.
-add_executable (hello_bson ../../hello_bson.c)
-target_include_directories (hello_bson PRIVATE ${BSON_STATIC_INCLUDE_DIRS})
-target_link_libraries (hello_bson PRIVATE ${BSON_STATIC_LIBRARIES})
-target_compile_definitions (hello_bson PRIVATE ${BSON_STATIC_DEFINITIONS})
diff -pruN 1.30.4-1/src/libbson/examples/compile-with-pkg-config-static.sh 2.0.2-1/src/libbson/examples/compile-with-pkg-config-static.sh
--- 1.30.4-1/src/libbson/examples/compile-with-pkg-config-static.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/compile-with-pkg-config-static.sh	2025-06-19 15:42:22.000000000 +0000
@@ -3,4 +3,4 @@
 set -o errexit  # Exit the script with error if any of the commands fail
 
 # -- sphinx-include-start --
-gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-static-1.0)
+gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags bson$major-static)
diff -pruN 1.30.4-1/src/libbson/examples/compile-with-pkg-config.sh 2.0.2-1/src/libbson/examples/compile-with-pkg-config.sh
--- 1.30.4-1/src/libbson/examples/compile-with-pkg-config.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/compile-with-pkg-config.sh	2025-06-19 15:42:22.000000000 +0000
@@ -3,4 +3,4 @@
 set -o errexit  # Exit the script with error if any of the commands fail
 
 # -- sphinx-include-start --
-gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-1.0)
+gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags bson$major)
diff -pruN 1.30.4-1/src/libbson/examples/extended-json.c 2.0.2-1/src/libbson/examples/extended-json.c
--- 1.30.4-1/src/libbson/examples/extended-json.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/examples/extended-json.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,7 @@
 #include <stdio.h>
 
 int
-main (int argc, char *argv[])
+main (void)
 {
    {
       // bson_as_canonical_extended_json ... begin
diff -pruN 1.30.4-1/src/libbson/libbson.rc.in 2.0.2-1/src/libbson/libbson.rc.in
--- 1.30.4-1/src/libbson/libbson.rc.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/libbson.rc.in	2025-06-19 15:42:22.000000000 +0000
@@ -5,7 +5,6 @@
 #include <bson/bson-version.h> // Defines BSON_MAJOR_VERSION and other version macros.
 
 #define BSON_OUTPUT_BASENAME "@BSON_OUTPUT_BASENAME@"
-#define BSON_API_VERSION "@BSON_API_VERSION@"
 
 VS_VERSION_INFO VERSIONINFO
  FILEVERSION BSON_MAJOR_VERSION,BSON_MINOR_VERSION,BSON_MICRO_VERSION,0
@@ -30,8 +29,8 @@ BEGIN
             VALUE "CompanyName", "MongoDB, Inc"
             VALUE "FileDescription", "A BSON Library for C"
             VALUE "FileVersion", BSON_VERSION_S
-            VALUE "InternalName", BSON_OUTPUT_BASENAME "-" BSON_API_VERSION
-            VALUE "OriginalFilename", BSON_OUTPUT_BASENAME "-" BSON_API_VERSION ".dll"
+            VALUE "InternalName", BSON_OUTPUT_BASENAME "@PROJECT_VERSION_MAJOR@"
+            VALUE "OriginalFilename", BSON_OUTPUT_BASENAME "@PROJECT_VERSION_MAJOR@.dll"
             VALUE "ProductName", "MongoDB C Driver"
             VALUE "ProductVersion", BSON_VERSION_S
             VALUE "LegalCopyright", "Copyright 2009-present MongoDB, Inc."
diff -pruN 1.30.4-1/src/libbson/src/bson/bcon.c 2.0.2-1/src/libbson/src/bson/bcon.c
--- 1.30.4-1/src/libbson/src/bson/bcon.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bcon.c	2025-06-19 15:42:22.000000000 +0000
@@ -38,7 +38,6 @@
 #define STACK_BSON_PARENT STACK_BSON (-1)
 #define STACK_BSON_CHILD STACK_BSON (0)
 
-#define STACK_ITER_PARENT STACK_ITER (-1)
 #define STACK_ITER_CHILD STACK_ITER (0)
 
 #define STACK_I STACK_ELE (0, i)
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-atomic.c 2.0.2-1/src/libbson/src/bson/bson-atomic.c
--- 1.30.4-1/src/libbson/src/bson/bson-atomic.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-atomic.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,274 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <bson/bson-atomic.h>
-#include <common-macros-private.h>
-
-BEGIN_IGNORE_DEPRECATIONS
-
-#ifdef BSON_OS_UNIX
-/* For sched_yield() */
-#include <sched.h>
-#endif
-
-int32_t
-bson_atomic_int_add (volatile int32_t *p, int32_t n)
-{
-   return n + bson_atomic_int32_fetch_add ((DECL_ATOMIC_INTEGRAL_INT32 *) p, n, bson_memory_order_seq_cst);
-}
-
-int64_t
-bson_atomic_int64_add (volatile int64_t *p, int64_t n)
-{
-   return n + bson_atomic_int64_fetch_add (p, n, bson_memory_order_seq_cst);
-}
-
-void
-bson_thrd_yield (void)
-{
-   BSON_IF_WINDOWS (SwitchToThread ();)
-   BSON_IF_POSIX (sched_yield ();)
-}
-
-void
-bson_memory_barrier (void)
-{
-   bson_atomic_thread_fence ();
-}
-
-/**
- * Some platforms do not support compiler intrinsics for atomic operations.
- * We emulate that here using a spin lock and regular arithmetic operations
- */
-static int8_t gEmulAtomicLock = 0;
-
-static void
-_lock_emul_atomic (void)
-{
-   int i;
-   if (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) {
-      /* Successfully took the spinlock */
-      return;
-   }
-   /* Failed. Try taking ten more times, then begin sleeping. */
-   for (i = 0; i < 10; ++i) {
-      if (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) {
-         /* Succeeded in taking the lock */
-         return;
-      }
-   }
-   /* Still don't have the lock. Spin and yield */
-   while (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) != 0) {
-      bson_thrd_yield ();
-   }
-}
-
-static void
-_unlock_emul_atomic (void)
-{
-   int64_t rv = bson_atomic_int8_exchange (&gEmulAtomicLock, 0, bson_memory_order_release);
-   BSON_ASSERT (rv == 1 && "Released atomic lock while not holding it");
-}
-
-int64_t
-_bson_emul_atomic_int64_fetch_add (volatile int64_t *p, int64_t n, enum bson_memory_order _unused)
-{
-   int64_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p += n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int64_t
-_bson_emul_atomic_int64_exchange (volatile int64_t *p, int64_t n, enum bson_memory_order _unused)
-{
-   int64_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p = n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int64_t
-_bson_emul_atomic_int64_compare_exchange_strong (volatile int64_t *p,
-                                                 int64_t expect_value,
-                                                 int64_t new_value,
-                                                 enum bson_memory_order _unused)
-{
-   int64_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   if (ret == expect_value) {
-      *p = new_value;
-   }
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int64_t
-_bson_emul_atomic_int64_compare_exchange_weak (volatile int64_t *p,
-                                               int64_t expect_value,
-                                               int64_t new_value,
-                                               enum bson_memory_order order)
-{
-   /* We're emulating. We can't do a weak version. */
-   return _bson_emul_atomic_int64_compare_exchange_strong (p, expect_value, new_value, order);
-}
-
-
-int32_t
-_bson_emul_atomic_int32_fetch_add (volatile int32_t *p, int32_t n, enum bson_memory_order _unused)
-{
-   int32_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p += n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int32_t
-_bson_emul_atomic_int32_exchange (volatile int32_t *p, int32_t n, enum bson_memory_order _unused)
-{
-   int32_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p = n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int32_t
-_bson_emul_atomic_int32_compare_exchange_strong (volatile int32_t *p,
-                                                 int32_t expect_value,
-                                                 int32_t new_value,
-                                                 enum bson_memory_order _unused)
-{
-   int32_t ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   if (ret == expect_value) {
-      *p = new_value;
-   }
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int32_t
-_bson_emul_atomic_int32_compare_exchange_weak (volatile int32_t *p,
-                                               int32_t expect_value,
-                                               int32_t new_value,
-                                               enum bson_memory_order order)
-{
-   /* We're emulating. We can't do a weak version. */
-   return _bson_emul_atomic_int32_compare_exchange_strong (p, expect_value, new_value, order);
-}
-
-
-int
-_bson_emul_atomic_int_fetch_add (volatile int *p, int n, enum bson_memory_order _unused)
-{
-   int ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p += n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int
-_bson_emul_atomic_int_exchange (volatile int *p, int n, enum bson_memory_order _unused)
-{
-   int ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p = n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int
-_bson_emul_atomic_int_compare_exchange_strong (volatile int *p,
-                                               int expect_value,
-                                               int new_value,
-                                               enum bson_memory_order _unused)
-{
-   int ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   if (ret == expect_value) {
-      *p = new_value;
-   }
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-int
-_bson_emul_atomic_int_compare_exchange_weak (volatile int *p,
-                                             int expect_value,
-                                             int new_value,
-                                             enum bson_memory_order order)
-{
-   /* We're emulating. We can't do a weak version. */
-   return _bson_emul_atomic_int_compare_exchange_strong (p, expect_value, new_value, order);
-}
-
-void *
-_bson_emul_atomic_ptr_exchange (void *volatile *p, void *n, enum bson_memory_order _unused)
-{
-   void *ret;
-
-   BSON_UNUSED (_unused);
-
-   _lock_emul_atomic ();
-   ret = *p;
-   *p = n;
-   _unlock_emul_atomic ();
-   return ret;
-}
-
-END_IGNORE_DEPRECATIONS
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-atomic.h 2.0.2-1/src/libbson/src/bson/bson-atomic.h
--- 1.30.4-1/src/libbson/src/bson/bson-atomic.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-atomic.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,683 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <bson/bson-prelude.h>
-
-
-#ifndef BSON_ATOMIC_H
-#define BSON_ATOMIC_H
-
-
-#include <bson/bson-config.h>
-#include <bson/bson-compat.h>
-#include <bson/bson-macros.h>
-
-#ifdef _MSC_VER
-#include <intrin.h>
-#endif
-
-// bson-atomic.h is deprecated.
-// Ignore deprecation warnings for function calls within this file.
-
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
-#define BSON_BEGIN_IGNORE_DEPRECATIONS \
-   _Pragma ("GCC diagnostic push") _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
-#define BSON_END_IGNORE_DEPRECATIONS _Pragma ("GCC diagnostic pop")
-#elif defined(__clang__)
-#define BSON_BEGIN_IGNORE_DEPRECATIONS \
-   _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
-#define BSON_END_IGNORE_DEPRECATIONS _Pragma ("clang diagnostic pop")
-#else
-#define BSON_BEGIN_IGNORE_DEPRECATIONS
-#define BSON_END_IGNORE_DEPRECATIONS
-#endif
-
-BSON_BEGIN_IGNORE_DEPRECATIONS
-
-BSON_BEGIN_DECLS
-
-enum BSON_GNUC_DEPRECATED bson_memory_order {
-   bson_memory_order_seq_cst,
-   bson_memory_order_acquire,
-   bson_memory_order_release,
-   bson_memory_order_relaxed,
-   bson_memory_order_acq_rel,
-   bson_memory_order_consume,
-};
-
-#if defined(_M_ARM) /* MSVC memorder atomics are only avail on ARM */
-#define MSVC_MEMORDER_SUFFIX(X) X
-#else
-#define MSVC_MEMORDER_SUFFIX(X)
-#endif
-
-#if defined(USE_LEGACY_GCC_ATOMICS) || (!defined(__clang__) && __GNUC__ == 4) || defined(__xlC__)
-#define BSON_USE_LEGACY_GCC_ATOMICS
-#else
-#undef BSON_USE_LEGACY_GCC_ATOMICS
-#endif
-
-/* Not all GCC-like compilers support the current __atomic built-ins.  Older
- * GCC (pre-5) used different built-ins named with the __sync prefix.  When
- * compiling with such older GCC versions, it is necessary to use the applicable
- * functions, which requires redefining BSON_IF_GNU_LIKE and defining the
- * additional BSON_IF_GNU_LEGACY_ATOMICS macro here. */
-#ifdef BSON_USE_LEGACY_GCC_ATOMICS
-#undef BSON_IF_GNU_LIKE
-#define BSON_IF_GNU_LIKE(...)
-#define BSON_IF_GNU_LEGACY_ATOMICS(...) __VA_ARGS__
-#else
-#define BSON_IF_GNU_LEGACY_ATOMICS(...)
-#endif
-
-/* CDRIVER-4229 zSeries with gcc 4.8.4 produces illegal instructions for int and
- * int32 atomic intrinsics. */
-#if defined(__s390__) || defined(__s390x__) || defined(__zarch__)
-#define BSON_EMULATE_INT32
-#define BSON_EMULATE_INT
-#endif
-
-/* CDRIVER-4264 Contrary to documentation, VS 2013 targeting x86 does not
- * correctly/consistently provide _InterlockedPointerExchange. */
-#if defined(_MSC_VER) && _MSC_VER < 1900 && defined(_M_IX86)
-#define BSON_EMULATE_PTR
-#endif
-
-// Disable the -Wcovered-switch-default warning.
-#define BSON_DISABLE_COVERED_SWITCH_DEFAULT_BEGIN
-#define BSON_DISABLE_COVERED_SWITCH_DEFAULT_END
-#if defined(__clang__)
-#if __has_warning("-Wcovered-switch-default")
-#undef BSON_DISABLE_COVERED_SWITCH_DEFAULT_BEGIN
-#undef BSON_DISABLE_COVERED_SWITCH_DEFAULT_END
-#define BSON_DISABLE_COVERED_SWITCH_DEFAULT_BEGIN \
-   _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Wcovered-switch-default\"")
-#define BSON_DISABLE_COVERED_SWITCH_DEFAULT_END _Pragma ("clang diagnostic pop")
-#endif // __has_warning("-Wcovered-switch-default")
-#endif // defined(__clang__)
-
-// Disable the -Watomic-implicit-seq-cst warning.
-#define BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_BEGIN
-#define BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_END
-#if defined(__clang__)
-#if __has_warning("-Watomic-implicit-seq-cst")
-#undef BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_BEGIN
-#undef BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_END
-#define BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_BEGIN \
-   _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Watomic-implicit-seq-cst\"")
-#define BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_END _Pragma ("clang diagnostic pop")
-#endif // __has_warning("-Watomic-implicit-seq-cst")
-#endif // defined(__clang__)
-
-BSON_DISABLE_COVERED_SWITCH_DEFAULT_BEGIN
-
-#define DEF_ATOMIC_OP(MSVC_Intrinsic, GNU_Intrinsic, GNU_Legacy_Intrinsic, Order, ...)                  \
-   do {                                                                                                 \
-      switch (Order) {                                                                                  \
-      case bson_memory_order_acq_rel:                                                                   \
-         BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);)                                            \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQ_REL);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      case bson_memory_order_seq_cst:                                                                   \
-         BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);)                                            \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_SEQ_CST);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      case bson_memory_order_acquire:                                                                   \
-         BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQUIRE);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      case bson_memory_order_consume:                                                                   \
-         BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_CONSUME);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      case bson_memory_order_release:                                                                   \
-         BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_rel)) (__VA_ARGS__);) \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELEASE);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      case bson_memory_order_relaxed:                                                                   \
-         BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_nf)) (__VA_ARGS__);)  \
-         BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELAXED);)                       \
-         BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);)                        \
-      default:                                                                                          \
-         BSON_UNREACHABLE ("Invalid bson_memory_order value");                                          \
-      }                                                                                                 \
-   } while (0)
-
-
-#define DEF_ATOMIC_CMPEXCH_STRONG(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue)    \
-   do {                                                                                                  \
-      BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \
-                       Ptr, NewValue, ExpectActualVar);)                                                 \
-      BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr,                                         \
-                                                            &ExpectActualVar,                            \
-                                                            NewValue,                                    \
-                                                            false, /* Not weak */                        \
-                                                            GNU_MemOrder,                                \
-                                                            GNU_MemOrder);)                              \
-      BSON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val;                                     \
-                                  _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue);   \
-                                  ExpectActualVar = _val;)                                               \
-   } while (0)
-
-
-#define DEF_ATOMIC_CMPEXCH_WEAK(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue)      \
-   do {                                                                                                  \
-      BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \
-                       Ptr, NewValue, ExpectActualVar);)                                                 \
-      BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr,                                         \
-                                                            &ExpectActualVar,                            \
-                                                            NewValue,                                    \
-                                                            true, /* Yes weak */                         \
-                                                            GNU_MemOrder,                                \
-                                                            GNU_MemOrder);)                              \
-      BSON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val;                                     \
-                                  _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue);   \
-                                  ExpectActualVar = _val;)                                               \
-   } while (0)
-
-
-#define DECL_ATOMIC_INTEGRAL(NamePart, Type, VCIntrinSuffix)                                                           \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_fetch_add (                                   \
-      Type volatile *a, Type addend, enum bson_memory_order ord)                                                       \
-   {                                                                                                                   \
-      DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchangeAdd, VCIntrinSuffix),                                            \
-                     __atomic_fetch_add,                                                                               \
-                     __sync_fetch_and_add,                                                                             \
-                     ord,                                                                                              \
-                     a,                                                                                                \
-                     addend);                                                                                          \
-   }                                                                                                                   \
-                                                                                                                       \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_fetch_sub (                                   \
-      Type volatile *a, Type subtrahend, enum bson_memory_order ord)                                                   \
-   {                                                                                                                   \
-      /* MSVC doesn't have a subtract intrinsic, so just reuse addition    */                                          \
-      BSON_IF_MSVC (return bson_atomic_##NamePart##_fetch_add (a, -subtrahend, ord);)                                  \
-      BSON_IF_GNU_LIKE (DEF_ATOMIC_OP (~, __atomic_fetch_sub, ~, ord, a, subtrahend);)                                 \
-      BSON_IF_GNU_LEGACY_ATOMICS (DEF_ATOMIC_OP (~, ~, __sync_fetch_and_sub, ord, a, subtrahend);)                     \
-   }                                                                                                                   \
-                                                                                                                       \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_fetch (Type volatile const *a,                \
-                                                                                enum bson_memory_order order)          \
-   {                                                                                                                   \
-      /* MSVC doesn't have a load intrinsic, so just add zero */                                                       \
-      BSON_IF_MSVC (return bson_atomic_##NamePart##_fetch_add ((Type volatile *) a, 0, order);)                        \
-      /* GNU doesn't want RELEASE order for the fetch operation, so we can't                                           \
-       * just use DEF_ATOMIC_OP. */                                                                                    \
-      BSON_IF_GNU_LIKE (switch (order) {                                                                               \
-         case bson_memory_order_release: /* Fall back to seqcst */                                                     \
-         case bson_memory_order_acq_rel: /* Fall back to seqcst */                                                     \
-         case bson_memory_order_seq_cst:                                                                               \
-            return __atomic_load_n (a, __ATOMIC_SEQ_CST);                                                              \
-         case bson_memory_order_acquire:                                                                               \
-            return __atomic_load_n (a, __ATOMIC_ACQUIRE);                                                              \
-         case bson_memory_order_consume:                                                                               \
-            return __atomic_load_n (a, __ATOMIC_CONSUME);                                                              \
-         case bson_memory_order_relaxed:                                                                               \
-            return __atomic_load_n (a, __ATOMIC_RELAXED);                                                              \
-         default:                                                                                                      \
-            BSON_UNREACHABLE ("Invalid bson_memory_order value");                                                      \
-      })                                                                                                               \
-      BSON_IF_GNU_LEGACY_ATOMICS ({                                                                                    \
-         BSON_UNUSED (order);                                                                                          \
-         __sync_synchronize ();                                                                                        \
-         return *a;                                                                                                    \
-      })                                                                                                               \
-   }                                                                                                                   \
-                                                                                                                       \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_exchange (                                    \
-      Type volatile *a, Type value, enum bson_memory_order ord)                                                        \
-   {                                                                                                                   \
-      BSON_IF_MSVC (DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchange, VCIntrinSuffix), ~, ~, ord, a, value);)          \
-      /* GNU doesn't want CONSUME order for the exchange operation, so we                                              \
-       * cannot use DEF_ATOMIC_OP. */                                                                                  \
-      BSON_IF_GNU_LIKE (switch (ord) {                                                                                 \
-         case bson_memory_order_acq_rel:                                                                               \
-            return __atomic_exchange_n (a, value, __ATOMIC_ACQ_REL);                                                   \
-         case bson_memory_order_release:                                                                               \
-            return __atomic_exchange_n (a, value, __ATOMIC_RELEASE);                                                   \
-         case bson_memory_order_seq_cst:                                                                               \
-            return __atomic_exchange_n (a, value, __ATOMIC_SEQ_CST);                                                   \
-         case bson_memory_order_consume: /* Fall back to acquire */                                                    \
-         case bson_memory_order_acquire:                                                                               \
-            return __atomic_exchange_n (a, value, __ATOMIC_ACQUIRE);                                                   \
-         case bson_memory_order_relaxed:                                                                               \
-            return __atomic_exchange_n (a, value, __ATOMIC_RELAXED);                                                   \
-         default:                                                                                                      \
-            BSON_UNREACHABLE ("Invalid bson_memory_order value");                                                      \
-      })                                                                                                               \
-      BSON_IF_GNU_LEGACY_ATOMICS (BSON_UNUSED (ord); return __sync_val_compare_and_swap (a, *a, value);)               \
-   }                                                                                                                   \
-                                                                                                                       \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_compare_exchange_strong (                     \
-      Type volatile *a, Type expect, Type new_value, enum bson_memory_order ord)                                       \
-   {                                                                                                                   \
-      Type actual = expect;                                                                                            \
-      switch (ord) {                                                                                                   \
-      case bson_memory_order_release:                                                                                  \
-      case bson_memory_order_acq_rel:                                                                                  \
-      case bson_memory_order_seq_cst:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value);                         \
-         break;                                                                                                        \
-      case bson_memory_order_acquire:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_STRONG (                                                                                   \
-            VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value);                      \
-         break;                                                                                                        \
-      case bson_memory_order_consume:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_STRONG (                                                                                   \
-            VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value);                      \
-         break;                                                                                                        \
-      case bson_memory_order_relaxed:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_STRONG (                                                                                   \
-            VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value);                       \
-         break;                                                                                                        \
-      default:                                                                                                         \
-         BSON_UNREACHABLE ("Invalid bson_memory_order value");                                                         \
-      }                                                                                                                \
-      return actual;                                                                                                   \
-   }                                                                                                                   \
-                                                                                                                       \
-   static BSON_INLINE Type BSON_GNUC_DEPRECATED bson_atomic_##NamePart##_compare_exchange_weak (                       \
-      Type volatile *a, Type expect, Type new_value, enum bson_memory_order ord)                                       \
-   {                                                                                                                   \
-      Type actual = expect;                                                                                            \
-      switch (ord) {                                                                                                   \
-      case bson_memory_order_release:                                                                                  \
-      case bson_memory_order_acq_rel:                                                                                  \
-      case bson_memory_order_seq_cst:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value);                           \
-         break;                                                                                                        \
-      case bson_memory_order_acquire:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_WEAK (                                                                                     \
-            VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value);                      \
-         break;                                                                                                        \
-      case bson_memory_order_consume:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_WEAK (                                                                                     \
-            VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value);                      \
-         break;                                                                                                        \
-      case bson_memory_order_relaxed:                                                                                  \
-         DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value); \
-         break;                                                                                                        \
-      default:                                                                                                         \
-         BSON_UNREACHABLE ("Invalid bson_memory_order value");                                                         \
-      }                                                                                                                \
-      return actual;                                                                                                   \
-   }
-
-#define DECL_ATOMIC_STDINT(Name, VCSuffix) DECL_ATOMIC_INTEGRAL (Name, Name##_t, VCSuffix)
-
-#if defined(_MSC_VER) || defined(BSON_USE_LEGACY_GCC_ATOMICS)
-/* MSVC and GCC require built-in types (not typedefs) for their atomic
- * intrinsics. */
-#if defined(_MSC_VER)
-#define DECL_ATOMIC_INTEGRAL_INT8 char
-#define DECL_ATOMIC_INTEGRAL_INT32 long
-#define DECL_ATOMIC_INTEGRAL_INT long
-#else
-#define DECL_ATOMIC_INTEGRAL_INT8 signed char
-#define DECL_ATOMIC_INTEGRAL_INT32 int
-#define DECL_ATOMIC_INTEGRAL_INT int
-#endif
-DECL_ATOMIC_INTEGRAL (int8, DECL_ATOMIC_INTEGRAL_INT8, 8)
-DECL_ATOMIC_INTEGRAL (int16, short, 16)
-#if !defined(BSON_EMULATE_INT32)
-DECL_ATOMIC_INTEGRAL (int32, DECL_ATOMIC_INTEGRAL_INT32, )
-#endif
-#if !defined(BSON_EMULATE_INT)
-DECL_ATOMIC_INTEGRAL (int, DECL_ATOMIC_INTEGRAL_INT, )
-#endif
-#else
-/* Other compilers that we support provide generic intrinsics */
-DECL_ATOMIC_STDINT (int8, 8)
-DECL_ATOMIC_STDINT (int16, 16)
-#if !defined(BSON_EMULATE_INT32)
-DECL_ATOMIC_STDINT (int32, )
-#endif
-#if !defined(BSON_EMULATE_INT)
-DECL_ATOMIC_INTEGRAL (int, int, )
-#endif
-#endif
-
-#ifndef DECL_ATOMIC_INTEGRAL_INT32
-#define DECL_ATOMIC_INTEGRAL_INT32 int32_t
-#endif
-
-BSON_EXPORT (int64_t)
-_bson_emul_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum bson_memory_order);
-BSON_EXPORT (int64_t)
-_bson_emul_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum bson_memory_order);
-BSON_EXPORT (int64_t)
-_bson_emul_atomic_int64_compare_exchange_strong (int64_t volatile *val,
-                                                 int64_t expect_value,
-                                                 int64_t new_value,
-                                                 enum bson_memory_order);
-
-BSON_EXPORT (int64_t)
-_bson_emul_atomic_int64_compare_exchange_weak (int64_t volatile *val,
-                                               int64_t expect_value,
-                                               int64_t new_value,
-                                               enum bson_memory_order);
-
-BSON_EXPORT (int32_t)
-_bson_emul_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum bson_memory_order);
-BSON_EXPORT (int32_t)
-_bson_emul_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum bson_memory_order);
-BSON_EXPORT (int32_t)
-_bson_emul_atomic_int32_compare_exchange_strong (int32_t volatile *val,
-                                                 int32_t expect_value,
-                                                 int32_t new_value,
-                                                 enum bson_memory_order);
-
-BSON_EXPORT (int32_t)
-_bson_emul_atomic_int32_compare_exchange_weak (int32_t volatile *val,
-                                               int32_t expect_value,
-                                               int32_t new_value,
-                                               enum bson_memory_order);
-
-BSON_EXPORT (int)
-_bson_emul_atomic_int_fetch_add (int volatile *val, int v, enum bson_memory_order);
-BSON_EXPORT (int)
-_bson_emul_atomic_int_exchange (int volatile *val, int v, enum bson_memory_order);
-BSON_EXPORT (int)
-_bson_emul_atomic_int_compare_exchange_strong (int volatile *val,
-                                               int expect_value,
-                                               int new_value,
-                                               enum bson_memory_order);
-
-BSON_EXPORT (int)
-_bson_emul_atomic_int_compare_exchange_weak (int volatile *val,
-                                             int expect_value,
-                                             int new_value,
-                                             enum bson_memory_order);
-
-BSON_EXPORT (void *)
-_bson_emul_atomic_ptr_exchange (void *volatile *val, void *v, enum bson_memory_order);
-
-BSON_EXPORT (void)
-bson_thrd_yield (void);
-
-#if (defined(_MSC_VER) && !defined(_M_IX86)) || (defined(__LP64__) && __LP64__)
-/* (64-bit intrinsics are only available in x64) */
-#ifdef _MSC_VER
-DECL_ATOMIC_INTEGRAL (int64, __int64, 64)
-#else
-DECL_ATOMIC_STDINT (int64, 64)
-#endif
-#else
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_fetch (const int64_t volatile *val, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_fetch_add ((int64_t volatile *) val, 0, order);
-}
-
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_fetch_add (val, v, order);
-}
-
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_fetch_sub (int64_t volatile *val, int64_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_fetch_add (val, -v, order);
-}
-
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_exchange (val, v, order);
-}
-
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_compare_exchange_strong (int64_t volatile *val,
-                                           int64_t expect_value,
-                                           int64_t new_value,
-                                           enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_compare_exchange_strong (val, expect_value, new_value, order);
-}
-
-static BSON_INLINE int64_t BSON_GNUC_DEPRECATED
-bson_atomic_int64_compare_exchange_weak (int64_t volatile *val,
-                                         int64_t expect_value,
-                                         int64_t new_value,
-                                         enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int64_compare_exchange_weak (val, expect_value, new_value, order);
-}
-#endif
-
-#if defined(BSON_EMULATE_INT32)
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_fetch (const int32_t volatile *val, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_fetch_add ((int32_t volatile *) val, 0, order);
-}
-
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_fetch_add (val, v, order);
-}
-
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_fetch_sub (int32_t volatile *val, int32_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_fetch_add (val, -v, order);
-}
-
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_exchange (val, v, order);
-}
-
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_compare_exchange_strong (int32_t volatile *val,
-                                           int32_t expect_value,
-                                           int32_t new_value,
-                                           enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_compare_exchange_strong (val, expect_value, new_value, order);
-}
-
-static BSON_INLINE int32_t BSON_GNUC_DEPRECATED
-bson_atomic_int32_compare_exchange_weak (int32_t volatile *val,
-                                         int32_t expect_value,
-                                         int32_t new_value,
-                                         enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int32_compare_exchange_weak (val, expect_value, new_value, order);
-}
-#endif /* BSON_EMULATE_INT32 */
-
-#if defined(BSON_EMULATE_INT)
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_fetch (const int volatile *val, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_fetch_add ((int volatile *) val, 0, order);
-}
-
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_fetch_add (int volatile *val, int v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_fetch_add (val, v, order);
-}
-
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_fetch_sub (int volatile *val, int v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_fetch_add (val, -v, order);
-}
-
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_exchange (int volatile *val, int v, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_exchange (val, v, order);
-}
-
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_compare_exchange_strong (int volatile *val,
-                                         int expect_value,
-                                         int new_value,
-                                         enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_compare_exchange_strong (val, expect_value, new_value, order);
-}
-
-static BSON_INLINE int BSON_GNUC_DEPRECATED
-bson_atomic_int_compare_exchange_weak (int volatile *val, int expect_value, int new_value, enum bson_memory_order order)
-{
-   return _bson_emul_atomic_int_compare_exchange_weak (val, expect_value, new_value, order);
-}
-#endif /* BSON_EMULATE_INT */
-
-static BSON_INLINE void *BSON_GNUC_DEPRECATED
-bson_atomic_ptr_exchange (void *volatile *ptr, void *new_value, enum bson_memory_order ord)
-{
-#if defined(BSON_EMULATE_PTR)
-   return _bson_emul_atomic_ptr_exchange (ptr, new_value, ord);
-#elif defined(BSON_USE_LEGACY_GCC_ATOMICS)
-   /* The older __sync_val_compare_and_swap also takes oldval */
-   DEF_ATOMIC_OP (_InterlockedExchangePointer, , __sync_val_compare_and_swap, ord, ptr, *ptr, new_value);
-#else
-   DEF_ATOMIC_OP (_InterlockedExchangePointer, __atomic_exchange_n, , ord, ptr, new_value);
-#endif
-}
-
-static BSON_INLINE void *BSON_GNUC_DEPRECATED
-bson_atomic_ptr_compare_exchange_strong (void *volatile *ptr, void *expect, void *new_value, enum bson_memory_order ord)
-{
-   switch (ord) {
-   case bson_memory_order_release:
-   case bson_memory_order_acq_rel:
-   case bson_memory_order_seq_cst:
-      DEF_ATOMIC_CMPEXCH_STRONG (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_relaxed:
-      DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_consume:
-      DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_acquire:
-      DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value);
-      return expect;
-   default:
-      BSON_UNREACHABLE ("Invalid bson_memory_order value");
-   }
-}
-
-
-static BSON_INLINE void *BSON_GNUC_DEPRECATED
-bson_atomic_ptr_compare_exchange_weak (void *volatile *ptr, void *expect, void *new_value, enum bson_memory_order ord)
-{
-   switch (ord) {
-   case bson_memory_order_release:
-   case bson_memory_order_acq_rel:
-   case bson_memory_order_seq_cst:
-      DEF_ATOMIC_CMPEXCH_WEAK (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_relaxed:
-      DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_consume:
-      DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value);
-      return expect;
-   case bson_memory_order_acquire:
-      DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value);
-      return expect;
-   default:
-      BSON_UNREACHABLE ("Invalid bson_memory_order value");
-   }
-}
-
-
-static BSON_INLINE void *BSON_GNUC_DEPRECATED
-bson_atomic_ptr_fetch (void *volatile const *ptr, enum bson_memory_order ord)
-{
-   // Use a union to address cast-qual compilation warning
-   union {
-      void *volatile const *const_ptr;
-      void *volatile *non_const_ptr;
-   } u;
-   u.const_ptr = ptr;
-   return bson_atomic_ptr_compare_exchange_strong (u.non_const_ptr, NULL, NULL, ord);
-}
-
-#undef DECL_ATOMIC_STDINT
-#undef DECL_ATOMIC_INTEGRAL
-#undef DEF_ATOMIC_OP
-#undef DEF_ATOMIC_CMPEXCH_STRONG
-#undef DEF_ATOMIC_CMPEXCH_WEAK
-#undef MSVC_MEMORDER_SUFFIX
-
-/**
- * @brief Generate a full-fence memory barrier at the call site.
- */
-static BSON_INLINE void BSON_GNUC_DEPRECATED
-bson_atomic_thread_fence (void)
-{
-   BSON_IF_MSVC (MemoryBarrier ();)
-
-   BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_BEGIN
-   BSON_IF_GNU_LIKE (__sync_synchronize ();)
-   BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_END
-
-   BSON_IF_GNU_LEGACY_ATOMICS (__sync_synchronize ();)
-}
-
-static BSON_INLINE void BSON_GNUC_DEPRECATED
-bson_sync_synchronize (void)
-{
-   bson_atomic_thread_fence ();
-}
-
-#ifdef BSON_USE_LEGACY_GCC_ATOMICS
-#undef BSON_IF_GNU_LIKE
-#define BSON_IF_GNU_LIKE(...) __VA_ARGS__
-#endif
-#undef BSON_IF_GNU_LEGACY_ATOMICS
-#undef BSON_USE_LEGACY_GCC_ATOMICS
-
-BSON_GNUC_DEPRECATED
-BSON_EXPORT (void) bson_memory_barrier (void);
-
-BSON_GNUC_DEPRECATED
-BSON_EXPORT (int32_t) bson_atomic_int_add (volatile int32_t *p, int32_t n);
-
-BSON_GNUC_DEPRECATED
-BSON_EXPORT (int64_t) bson_atomic_int64_add (volatile int64_t *p, int64_t n);
-
-BSON_DISABLE_COVERED_SWITCH_DEFAULT_END
-
-#undef BSON_EMULATE_PTR
-#undef BSON_EMULATE_INT32
-#undef BSON_EMULATE_INT
-#undef BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_BEGIN
-#undef BSON_DISABLE_ATOMIC_IMPLICIT_SEQ_CST_END
-#undef BSON_DISABLE_COVERED_SWITCH_DEFAULT_BEGIN
-#undef BSON_DISABLE_COVERED_SWITCH_DEFAULT_END
-
-
-BSON_END_DECLS
-
-BSON_END_IGNORE_DEPRECATIONS
-
-#undef BSON_BEGIN_IGNORE_DEPRECATIONS
-#undef BSON_END_IGNORE_DEPRECATIONS
-
-#endif /* BSON_ATOMIC_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-cmp.h 2.0.2-1/src/libbson/src/bson/bson-cmp.h
--- 1.30.4-1/src/libbson/src/bson/bson-cmp.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-cmp.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,193 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <bson/bson-prelude.h>
-
-
-#ifndef BSON_CMP_H
-#define BSON_CMP_H
-
-
-#include <bson/bson-compat.h> /* ssize_t */
-#include <bson/bson-macros.h> /* BSON_CONCAT */
-
-#include <limits.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-// bson-cmp.h is deprecated.
-// Ignore deprecation warnings for function calls within this file.
-
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
-#define BSON_BEGIN_IGNORE_DEPRECATIONS \
-   _Pragma ("GCC diagnostic push") _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
-#define BSON_END_IGNORE_DEPRECATIONS _Pragma ("GCC diagnostic pop")
-#elif defined(__clang__)
-#define BSON_BEGIN_IGNORE_DEPRECATIONS \
-   _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
-#define BSON_END_IGNORE_DEPRECATIONS _Pragma ("clang diagnostic pop")
-#else
-#define BSON_BEGIN_IGNORE_DEPRECATIONS
-#define BSON_END_IGNORE_DEPRECATIONS
-#endif
-
-BSON_BEGIN_IGNORE_DEPRECATIONS
-
-BSON_BEGIN_DECLS
-
-
-/* Based on the "Safe Integral Comparisons" proposal merged in C++20:
- * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0586r2.html
- *
- * Due to lack of type deduction in C, relational comparison functions (e.g.
- * `cmp_less`) are defined in sets of four "functions" according to the
- * signedness of each value argument, e.g.:
- *  - bson_cmp_less_ss (signed-value, signed-value)
- *  - bson_cmp_less_uu (unsigned-value, unsigned-value)
- *  - bson_cmp_less_su (signed-value, unsigned-value)
- *  - bson_cmp_less_us (unsigned-value, signed-value)
- *
- * Similarly, the `in_range` function is defined as a set of two "functions"
- * according to the signedness of the value argument:
- *  - bson_in_range_signed (Type, signed-value)
- *  - bson_in_range_unsigned (Type, unsigned-value)
- *
- * The user must take care to use the correct signedness for the provided
- * argument(s). Enabling compiler warnings for implicit sign conversions is
- * recommended.
- */
-
-#define BSON_CMP_SET(op, ss, uu, su, us)                                                                   \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_cmp_, op, _ss) (int64_t t, int64_t u)   \
-   {                                                                                                       \
-      return (ss);                                                                                         \
-   }                                                                                                       \
-                                                                                                           \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_cmp_, op, _uu) (uint64_t t, uint64_t u) \
-   {                                                                                                       \
-      return (uu);                                                                                         \
-   }                                                                                                       \
-                                                                                                           \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_cmp_, op, _su) (int64_t t, uint64_t u)  \
-   {                                                                                                       \
-      return (su);                                                                                         \
-   }                                                                                                       \
-                                                                                                           \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_cmp_, op, _us) (uint64_t t, int64_t u)  \
-   {                                                                                                       \
-      return (us);                                                                                         \
-   }
-
-BSON_CMP_SET (equal, t == u, t == u, t < 0 ? false : (uint64_t) (t) == u, u < 0 ? false : t == (uint64_t) (u))
-
-BSON_CMP_SET (not_equal,
-              !bson_cmp_equal_ss (t, u),
-              !bson_cmp_equal_uu (t, u),
-              !bson_cmp_equal_su (t, u),
-              !bson_cmp_equal_us (t, u))
-
-BSON_CMP_SET (less, t < u, t < u, t < 0 ? true : (uint64_t) (t) < u, u < 0 ? false : t < (uint64_t) (u))
-
-BSON_CMP_SET (
-   greater, bson_cmp_less_ss (u, t), bson_cmp_less_uu (u, t), bson_cmp_less_us (u, t), bson_cmp_less_su (u, t))
-
-BSON_CMP_SET (less_equal,
-              !bson_cmp_greater_ss (t, u),
-              !bson_cmp_greater_uu (t, u),
-              !bson_cmp_greater_su (t, u),
-              !bson_cmp_greater_us (t, u))
-
-BSON_CMP_SET (greater_equal,
-              !bson_cmp_less_ss (t, u),
-              !bson_cmp_less_uu (t, u),
-              !bson_cmp_less_su (t, u),
-              !bson_cmp_less_us (t, u))
-
-#undef BSON_CMP_SET
-
-
-/* Return true if the given value is within the range of the corresponding
- * signed type. The suffix must match the signedness of the given value. */
-#define BSON_IN_RANGE_SET_SIGNED(Type, min, max)                                                                  \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_in_range, _##Type, _signed) (int64_t value)    \
-   {                                                                                                              \
-      return bson_cmp_greater_equal_ss (value, min) && bson_cmp_less_equal_ss (value, max);                       \
-   }                                                                                                              \
-                                                                                                                  \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (uint64_t value) \
-   {                                                                                                              \
-      return bson_cmp_greater_equal_us (value, min) && bson_cmp_less_equal_us (value, max);                       \
-   }
-
-/* Return true if the given value is within the range of the corresponding
- * unsigned type. The suffix must match the signedness of the given value. */
-#define BSON_IN_RANGE_SET_UNSIGNED(Type, max)                                                                     \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_in_range, _##Type, _signed) (int64_t value)    \
-   {                                                                                                              \
-      return bson_cmp_greater_equal_su (value, 0u) && bson_cmp_less_equal_su (value, max);                        \
-   }                                                                                                              \
-                                                                                                                  \
-   static BSON_INLINE bool BSON_GNUC_DEPRECATED BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (uint64_t value) \
-   {                                                                                                              \
-      return bson_cmp_less_equal_uu (value, max);                                                                 \
-   }
-
-BSON_IN_RANGE_SET_SIGNED (signed_char, SCHAR_MIN, SCHAR_MAX)
-BSON_IN_RANGE_SET_SIGNED (short, SHRT_MIN, SHRT_MAX)
-BSON_IN_RANGE_SET_SIGNED (int, INT_MIN, INT_MAX)
-BSON_IN_RANGE_SET_SIGNED (long, LONG_MIN, LONG_MAX)
-BSON_IN_RANGE_SET_SIGNED (long_long, LLONG_MIN, LLONG_MAX)
-
-BSON_IN_RANGE_SET_UNSIGNED (unsigned_char, UCHAR_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (unsigned_short, USHRT_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (unsigned_int, UINT_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (unsigned_long, ULONG_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (unsigned_long_long, ULLONG_MAX)
-
-BSON_IN_RANGE_SET_SIGNED (int8_t, INT8_MIN, INT8_MAX)
-BSON_IN_RANGE_SET_SIGNED (int16_t, INT16_MIN, INT16_MAX)
-BSON_IN_RANGE_SET_SIGNED (int32_t, INT32_MIN, INT32_MAX)
-BSON_IN_RANGE_SET_SIGNED (int64_t, INT64_MIN, INT64_MAX)
-
-BSON_IN_RANGE_SET_UNSIGNED (uint8_t, UINT8_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (uint16_t, UINT16_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (uint32_t, UINT32_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (uint64_t, UINT64_MAX)
-
-BSON_IN_RANGE_SET_SIGNED (ssize_t, SSIZE_MIN, SSIZE_MAX)
-BSON_IN_RANGE_SET_UNSIGNED (size_t, SIZE_MAX)
-
-#undef BSON_IN_RANGE_SET_SIGNED
-#undef BSON_IN_RANGE_SET_UNSIGNED
-
-
-/* Return true if the value with *signed* type is in the representable range of
- * Type and false otherwise. */
-#define bson_in_range_signed(Type, value) BSON_CONCAT3 (bson_in_range, _##Type, _signed) (value)
-
-/* Return true if the value with *unsigned* type is in the representable range
- * of Type and false otherwise. */
-#define bson_in_range_unsigned(Type, value) BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (value)
-
-
-BSON_END_DECLS
-
-BSON_END_IGNORE_DEPRECATIONS
-
-#undef BSON_BEGIN_IGNORE_DEPRECATIONS
-#undef BSON_END_IGNORE_DEPRECATIONS
-
-#endif /* BSON_CMP_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-config.h.in 2.0.2-1/src/libbson/src/bson/bson-config.h.in
--- 1.30.4-1/src/libbson/src/bson/bson-config.h.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-config.h.in	2025-06-19 15:42:22.000000000 +0000
@@ -96,14 +96,6 @@
 #endif
 
 
-/*
- * Define to 1 if you want extra aligned types in libbson
- */
-#define BSON_EXTRA_ALIGN @BSON_EXTRA_ALIGN@
-#if BSON_EXTRA_ALIGN != 1
-# undef BSON_EXTRA_ALIGN
-#endif
-
 
 /*
  * Define to 1 if you have rand_r available on your platform.
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-context-private.h 2.0.2-1/src/libbson/src/bson/bson-context-private.h
--- 1.30.4-1/src/libbson/src/bson/bson-context-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-context-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -65,19 +65,6 @@ _bson_context_set_oid_rand (bson_context
 void
 _bson_context_set_oid_seq32 (bson_context_t *context, bson_oid_t *oid);
 
-/**
- * @brief Write a 64-bit counter from the given context into the OID. Increments
- * the context's sequence counter.
- *
- * @param context The context with the counter to get+update
- * @param oid The OID to modify
- *
- * @note Only used by the deprecated @ref bson_oid_init_sequence
- */
-void
-_bson_context_set_oid_seq64 (bson_context_t *context, bson_oid_t *oid);
-
-
 BSON_END_DECLS
 
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-context.c 2.0.2-1/src/libbson/src/bson/bson-context.c
--- 1.30.4-1/src/libbson/src/bson/bson-context.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-context.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <mlib/intencode.h>
 #include <bson/bson-compat.h>
 
 #include <limits.h>
@@ -67,18 +68,6 @@ _bson_context_set_oid_seq32 (bson_contex
    memcpy (&oid->bytes[BSON_OID_SEQ32_OFFSET], ((uint8_t *) &seq) + 1, BSON_OID_SEQ32_SIZE);
 }
 
-
-void
-_bson_context_set_oid_seq64 (bson_context_t *context, /* IN */
-                             bson_oid_t *oid)         /* OUT */
-{
-   uint64_t seq =
-      (uint64_t) mcommon_atomic_int64_fetch_add ((int64_t *) &context->seq64, 1, mcommon_memory_order_seq_cst);
-
-   seq = BSON_UINT64_TO_BE (seq);
-   memcpy (&oid->bytes[BSON_OID_SEQ64_OFFSET], &seq, BSON_OID_SEQ64_SIZE);
-}
-
 /*
  * --------------------------------------------------------------------------
  *
@@ -116,23 +105,6 @@ _bson_rotl_u64 (uint64_t *p, int nbits)
    *p = (*p << nbits) | (*p >> (64 - nbits));
 }
 
-/* Write the little-endian representation of 'val' into 'out' */
-void
-_u64_into_u8x8_le (uint8_t out[8], uint64_t val)
-{
-   val = BSON_UINT64_TO_LE (val);
-   memcpy (out, &val, sizeof val);
-}
-
-/* Read a little-endian representation of a 64bit number from 'in' */
-uint64_t
-_u8x8_le_to_u64 (const uint8_t in[8])
-{
-   uint64_t r;
-   memcpy (&r, in, sizeof r);
-   return BSON_UINT64_FROM_LE (r);
-}
-
 /* Perform one SipHash round */
 void
 _sip_round (uint64_t *v0, uint64_t *v1, uint64_t *v2, uint64_t *v3)
@@ -167,8 +139,8 @@ _siphash (const void *in, const size_t i
    uint64_t v1 = UINT64_C (0x646f72616e646f6d);
    uint64_t v2 = UINT64_C (0x6c7967656e657261);
    uint64_t v3 = UINT64_C (0x7465646279746573);
-   uint64_t k0 = _u8x8_le_to_u64 (kk);
-   uint64_t k1 = _u8x8_le_to_u64 (kk + 8);
+   uint64_t k0 = mlib_read_u64le (kk);
+   uint64_t k1 = mlib_read_u64le (kk + 8);
    uint64_t m;
    int i;
    const unsigned char *end = ni + inlen - (inlen % sizeof (uint64_t));
@@ -182,7 +154,7 @@ _siphash (const void *in, const size_t i
    v1 ^= 0xee;
 
    for (; ni != end; ni += 8) {
-      m = _u8x8_le_to_u64 (ni);
+      m = mlib_read_u64le (ni);
       v3 ^= m;
 
       for (i = 0; i < C_ROUNDS; ++i)
@@ -232,7 +204,7 @@ _siphash (const void *in, const size_t i
       _sip_round (&v0, &v1, &v2, &v3);
 
    b = v0 ^ v1 ^ v2 ^ v3;
-   _u64_into_u8x8_le (digest_buf, b);
+   mlib_write_u64le (digest_buf, b);
 
    v1 ^= 0xdd;
 
@@ -240,7 +212,7 @@ _siphash (const void *in, const size_t i
       _sip_round (&v0, &v1, &v2, &v3);
 
    b = v0 ^ v1 ^ v2 ^ v3;
-   _u64_into_u8x8_le (digest_buf + 8, b);
+   mlib_write_u64le (digest_buf + 8, b);
 
    memcpy (digest, digest_buf, sizeof digest_buf);
 }
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-decimal128.c 2.0.2-1/src/libbson/src/bson/bson-decimal128.c
--- 1.30.4-1/src/libbson/src/bson/bson-decimal128.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-decimal128.c	2025-06-19 15:42:22.000000000 +0000
@@ -23,7 +23,8 @@
 #include <bson/bson-types.h>
 #include <bson/bson-macros.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/loop.h>
 
 
 #define BSON_DECIMAL128_EXPONENT_MAX 6111
@@ -128,16 +129,15 @@ void
 bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN  */
                            char *str)                    /* OUT */
 {
-   uint32_t COMBINATION_MASK = 0x1f;   /* Extract least significant 5 bits */
-   uint32_t EXPONENT_MASK = 0x3fff;    /* Extract least significant 14 bits */
-   uint32_t COMBINATION_INFINITY = 30; /* Value of combination field for Inf */
-   uint32_t COMBINATION_NAN = 31;      /* Value of combination field for NaN */
-   uint32_t EXPONENT_BIAS = 6176;      /* decimal128 exponent bias */
+   const int COMBINATION_MASK = 0x1f;   /* Extract least significant 5 bits */
+   const int EXPONENT_MASK = 0x3fff;    /* Extract least significant 14 bits */
+   const int COMBINATION_INFINITY = 30; /* Value of combination field for Inf */
+   const int COMBINATION_NAN = 31;      /* Value of combination field for NaN */
+   const int EXPONENT_BIAS = 6176;      /* decimal128 exponent bias */
 
    char *str_out = str;      /* output pointer in string */
    char significand_str[35]; /* decoded significand digits */
 
-
    /* Note: bits in this routine are referred to starting at 0, */
    /* from the sign bit, towards the coefficient. */
    uint32_t high;                            /* bits 0 - 31 */
@@ -145,13 +145,8 @@ bson_decimal128_to_string (const bson_de
    uint32_t midl;                            /* bits 64 - 95 */
    uint32_t low;                             /* bits 96 - 127 */
    uint32_t combination;                     /* bits 1 - 5 */
-   uint32_t biased_exponent;                 /* decoded biased exponent (14 bits) */
-   uint32_t significand_digits = 0;          /* the number of significand digits */
    uint32_t significand[36] = {0};           /* the base-10 digits in the significand */
    uint32_t *significand_read = significand; /* read pointer into significand */
-   int32_t exponent;                         /* unbiased exponent */
-   int32_t scientific_exponent;              /* the exponent if scientific notation is
-                                              * used */
    bool is_zero = false;                     /* true if the number is zero */
 
    uint8_t significand_msb;        /* the most signifcant significand bits (50-46) */
@@ -171,12 +166,13 @@ bson_decimal128_to_string (const bson_de
    /* Decode combination field and exponent */
    combination = (high >> 26) & COMBINATION_MASK;
 
+   int biased_exponent;
    if (BSON_UNLIKELY ((combination >> 3) == 3)) {
       /* Check for 'special' values */
-      if (combination == COMBINATION_INFINITY) { /* Infinity */
+      if (mlib_cmp (combination, ==, COMBINATION_INFINITY)) { /* Infinity */
          strcpy (str_out, BSON_DECIMAL128_INF);
          return;
-      } else if (combination == COMBINATION_NAN) { /* NaN */
+      } else if (mlib_cmp (combination, ==, COMBINATION_NAN)) { /* NaN */
          /* str, not str_out, to erase the sign */
          strcpy (str, BSON_DECIMAL128_NAN);
          /* we don't care about the NaN payload. */
@@ -190,13 +186,15 @@ bson_decimal128_to_string (const bson_de
       biased_exponent = (high >> 17) & EXPONENT_MASK;
    }
 
-   exponent = biased_exponent - EXPONENT_BIAS;
+   /* unbiased exponent */
+   const int32_t exponent = biased_exponent - EXPONENT_BIAS;
+
    /* Create string of significand digits */
 
    /* Convert the 114-bit binary number represented by */
    /* (high, midh, midl, low) to at most 34 decimal */
    /* digits through modulo and division. */
-   significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+   significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xfu) << 14);
    significand128.parts[1] = midh;
    significand128.parts[2] = midl;
    significand128.parts[3] = low;
@@ -234,18 +232,20 @@ bson_decimal128_to_string (const bson_de
    /* Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd */
    /* Regular    - ddd.ddd */
 
+   int32_t num_significant_digits;
    if (is_zero) {
-      significand_digits = 1;
+      num_significant_digits = 1;
       *significand_read = 0;
    } else {
-      significand_digits = 36;
+      num_significant_digits = 36;
       while (!(*significand_read)) {
-         significand_digits--;
+         num_significant_digits--;
          significand_read++;
       }
    }
 
-   scientific_exponent = significand_digits - 1 + exponent;
+   /* the exponent if scientific notation is used */
+   const int32_t scientific_exponent = num_significant_digits - 1 + exponent;
 
    /* The scientific exponent checks are dictated by the string conversion
     * specification and are somewhat arbitrary cutoffs.
@@ -258,13 +258,13 @@ bson_decimal128_to_string (const bson_de
    if (scientific_exponent < -6 || exponent > 0) {
       /* Scientific format */
       *(str_out++) = *(significand_read++) + '0';
-      significand_digits--;
+      num_significant_digits--;
 
-      if (significand_digits) {
+      if (num_significant_digits) {
          *(str_out++) = '.';
       }
 
-      for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; i++) {
+      for (int32_t i = 0; i < num_significant_digits && (str_out - str) < 36; i++) {
          *(str_out++) = *(significand_read++) + '0';
       }
       /* Exponent */
@@ -275,18 +275,19 @@ bson_decimal128_to_string (const bson_de
    } else {
       /* Regular format with no decimal place */
       if (exponent >= 0) {
-         for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; i++) {
+         for (int32_t i = 0; i < num_significant_digits && (str_out - str) < 36; i++) {
             *(str_out++) = *(significand_read++) + '0';
          }
          *str_out = '\0';
       } else {
-         int32_t radix_position = significand_digits + exponent;
+         int32_t radix_position = num_significant_digits + exponent;
 
          // Reserve space for null terminator.
          const int available_bytes = BSON_DECIMAL128_STRING - 1;
+         const char *const str_end = str + available_bytes;
 
          if (radix_position > 0) { /* non-zero digits before radix */
-            for (int32_t i = 0; i < radix_position && (str_out - str) < available_bytes; i++) {
+            for (int32_t i = 0; i < radix_position && str_out != str_end; i++) {
                *(str_out++) = *(significand_read++) + '0';
             }
          } else { /* leading zero before radix point */
@@ -294,14 +295,16 @@ bson_decimal128_to_string (const bson_de
          }
 
          *(str_out++) = '.';
-         while (radix_position++ < 0) { /* add leading zeros after radix */
+         while (radix_position++ < 0 && str_out != str_end) { /* add leading zeros after radix */
             *(str_out++) = '0';
          }
 
-         for (uint32_t i = 0; mcommon_cmp_greater_us (significand_digits - i, BSON_MAX (radix_position - 1, 0)) &&
-                              (str_out - str) < available_bytes;
-              i++) {
-            *(str_out++) = *(significand_read++) + '0';
+         const unsigned dot_pos = (unsigned) BSON_MAX (radix_position - 1, 0);
+         const unsigned n_trailing_digits = num_significant_digits - dot_pos;
+         const unsigned n_to_write = BSON_MIN (n_trailing_digits, (unsigned) (str_end - str_out));
+         mlib_foreach_urange (i, n_to_write) {
+            (void) i;
+            *str_out++ = *significand_read++ + '0';
          }
          *str_out = '\0';
       }
@@ -548,7 +551,7 @@ bson_decimal128_from_string_w_len (const
             }
 
             found_nonzero = true;
-            *(digits_insert++) = *(str_read) - '0'; /* Only store 34 digits */
+            *(digits_insert++) = (uint16_t) (*(str_read) - '0'); /* Only store 34 digits */
             ndigits_stored++;
          }
       }
@@ -582,7 +585,7 @@ bson_decimal128_from_string_w_len (const
       int read_exponent = SSCANF (++str_read, "%" SCNd64 "%n", &temp_exponent, &nread);
       str_read += nread;
 
-      if (!read_exponent || nread == 0 || !mcommon_in_range_int32_t_signed (temp_exponent)) {
+      if (!read_exponent || nread == 0 || !mlib_in_range (int32_t, temp_exponent)) {
          BSON_DECIMAL128_SET_NAN (*dec);
          return false;
       }
@@ -601,7 +604,6 @@ bson_decimal128_from_string_w_len (const
    first_digit = 0;
 
    if (!ndigits_stored) { /* value is zero */
-      first_digit = 0;
       last_digit = 0;
       digits[0] = 0;
       ndigits = 1;
@@ -623,11 +625,10 @@ bson_decimal128_from_string_w_len (const
    /* to represent user input */
 
    /* Overflow prevention */
-   if (mcommon_cmp_less_equal_su (exponent, radix_position) &&
-       mcommon_cmp_greater_us (radix_position, exponent + (1 << 14))) {
+   if (mlib_cmp (exponent, <=, radix_position) && mlib_cmp (radix_position, >, exponent + (1 << 14))) {
       exponent = BSON_DECIMAL128_EXPONENT_MIN;
    } else {
-      BSON_ASSERT (mcommon_in_range_unsigned (int32_t, radix_position));
+      BSON_ASSERT (mlib_in_range (int32_t, radix_position));
       exponent -= (int32_t) radix_position;
    }
 
@@ -694,11 +695,9 @@ bson_decimal128_from_string_w_len (const
    /* Round */
    /* We've normalized the exponent, but might still need to round. */
    if (last_digit - first_digit + 1 < significant_digits) {
-      uint8_t round_digit;
-
       /* There are non-zero digits after last_digit that need rounding. */
       /* We round to nearest, ties to even */
-      round_digit = string[first_nonzero + last_digit + includes_sign + saw_radix + 1] - '0';
+      const char round_digit = string[first_nonzero + last_digit + includes_sign + saw_radix + 1] - '0';
 
       if (round_digit != 0) {
          /* Inexact (non-zero) rounding is not allowed */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-endian.h 2.0.2-1/src/libbson/src/bson/bson-endian.h
--- 1.30.4-1/src/libbson/src/bson/bson-endian.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-endian.h	2025-06-19 15:42:22.000000000 +0000
@@ -83,6 +83,8 @@ BSON_BEGIN_DECLS
 #define BSON_UINT64_TO_BE(v) BSON_UINT64_SWAP_LE_BE (v)
 #define BSON_DOUBLE_FROM_LE(v) ((double) v)
 #define BSON_DOUBLE_TO_LE(v) ((double) v)
+#define BSON_FLOAT_FROM_LE(v) ((float) v)
+#define BSON_FLOAT_TO_LE(v) ((float) v)
 #elif BSON_BYTE_ORDER == BSON_BIG_ENDIAN
 #define BSON_UINT16_FROM_LE(v) BSON_UINT16_SWAP_LE_BE (v)
 #define BSON_UINT16_TO_LE(v) BSON_UINT16_SWAP_LE_BE (v)
@@ -98,6 +100,8 @@ BSON_BEGIN_DECLS
 #define BSON_UINT64_TO_BE(v) ((uint64_t) v)
 #define BSON_DOUBLE_FROM_LE(v) (__bson_double_swap_slow (v))
 #define BSON_DOUBLE_TO_LE(v) (__bson_double_swap_slow (v))
+#define BSON_FLOAT_FROM_LE(v) (__bson_float_swap_slow (v))
+#define BSON_FLOAT_TO_LE(v) (__bson_float_swap_slow (v))
 #else
 #error "The endianness of target architecture is unknown."
 #endif
@@ -203,6 +207,37 @@ __bson_double_swap_slow (double v) /* IN
    memcpy (&v, &uv, sizeof (v));
 
    return v;
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
+ * __bson_float_swap_slow --
+ *
+ *       Fallback endianness conversion for single floating point.
+ *
+ * Returns:
+ *       The endian swapped version.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+BSON_STATIC_ASSERT2 (sizeof_uint32_t, sizeof (float) == sizeof (uint32_t));
+
+static BSON_INLINE float
+__bson_float_swap_slow (float v) /* IN */
+{
+   uint32_t uv;
+
+   memcpy (&uv, &v, sizeof (v));
+   uv = BSON_UINT32_SWAP_LE_BE (uv);
+   memcpy (&v, &uv, sizeof (v));
+
+   return v;
 }
 
 BSON_END_DECLS
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-error-private.h 2.0.2-1/src/libbson/src/bson/bson-error-private.h
--- 1.30.4-1/src/libbson/src/bson/bson-error-private.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-error-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bson/bson-prelude.h>
+
+#ifndef BSON_ERROR_PRIVATE_H
+#define BSON_ERROR_PRIVATE_H
+
+#include <bson/bson-error.h>
+#include <bson/bson-macros.h>
+
+
+#define BSON_ERROR_CATEGORY 1
+
+
+static BSON_INLINE void
+bson_set_error_category (bson_error_t *error, uint8_t category)
+{
+   BSON_ASSERT_PARAM (error);
+   error->reserved = category;
+}
+
+#endif /* BSON_ERROR_PRIVATE_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-error.c 2.0.2-1/src/libbson/src/bson/bson-error.c
--- 1.30.4-1/src/libbson/src/bson/bson-error.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-error.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,7 @@
 
 #include <bson/bson-compat.h>
 #include <bson/bson-config.h>
-#include <bson/bson-error.h>
+#include <bson/bson-error-private.h>
 #include <bson/bson-memory.h>
 #include <common-string-private.h>
 #include <bson/bson-types.h>
@@ -74,12 +74,11 @@ bson_set_error (bson_error_t *error, /*
    if (error) {
       error->domain = domain;
       error->code = code;
+      bson_set_error_category (error, BSON_ERROR_CATEGORY);
 
       va_start (args, format);
       bson_vsnprintf (error->message, sizeof error->message, format, args);
       va_end (args);
-
-      error->message[sizeof error->message - 1] = '\0';
    }
 }
 
@@ -113,7 +112,7 @@ bson_strerror_r (int err_code,
 #if defined(_WIN32)
    // Windows does not provide `strerror_l` or `strerror_r`, but it does
    // unconditionally provide `strerror_s`.
-   if (strerror_s (buf, buflen, err_code) != 0) {
+   if (strerror_s (buf, buflen, err_code) == 0) {
       ret = buf;
    }
 #elif defined(_AIX)
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-error.h 2.0.2-1/src/libbson/src/bson/bson-error.h
--- 1.30.4-1/src/libbson/src/bson/bson-error.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-error.h	2025-06-19 15:42:22.000000000 +0000
@@ -32,6 +32,7 @@ BSON_BEGIN_DECLS
 #define BSON_ERROR_JSON 1
 #define BSON_ERROR_READER 2
 #define BSON_ERROR_INVALID 3
+#define BSON_ERROR_VECTOR 4
 
 
 BSON_EXPORT (void)
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-iter.c 2.0.2-1/src/libbson/src/bson/bson-iter.c
--- 1.30.4-1/src/libbson/src/bson/bson-iter.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-iter.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,11 +15,12 @@
  */
 
 
+#include <mlib/intencode.h>
+#include <mlib/cmp.h>
 #include <bson/bson-iter.h>
 #include <bson/bson-config.h>
 #include <bson/bson-decimal128.h>
 #include <bson/bson-types.h>
-#include <common-cmp-private.h>
 
 #define ITER_TYPE(i) ((bson_type_t) * ((i)->raw + (i)->type))
 
@@ -90,8 +91,6 @@ bson_iter_init_from_data (bson_iter_t *i
                           const uint8_t *data, /* IN */
                           size_t length)       /* IN */
 {
-   uint32_t len_le;
-
    BSON_ASSERT (iter);
    BSON_ASSERT (data);
 
@@ -100,9 +99,9 @@ bson_iter_init_from_data (bson_iter_t *i
       return false;
    }
 
-   memcpy (&len_le, data, sizeof (len_le));
-
-   if (BSON_UNLIKELY ((size_t) BSON_UINT32_FROM_LE (len_le) != length)) {
+   // Check that the object header matches the length of the given buffer
+   const uint32_t hdr_len = mlib_read_u32le (data);
+   if (BSON_UNLIKELY (hdr_len != length)) {
       memset (iter, 0, sizeof *iter);
       return false;
    }
@@ -112,7 +111,7 @@ bson_iter_init_from_data (bson_iter_t *i
       return false;
    }
 
-   if (BSON_UNLIKELY (!mcommon_in_range_unsigned (uint32_t, length))) {
+   if (BSON_UNLIKELY (!mlib_in_range (uint32_t, length))) {
       memset (iter, 0, sizeof *iter);
       return false;
    }
@@ -575,16 +574,13 @@ fill_data_fields:
    case BSON_TYPE_CODE:
    case BSON_TYPE_SYMBOL:
    case BSON_TYPE_UTF8: {
-      uint32_t l;
-
       if ((o + 4) >= len) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
       iter->d2 = o + 4;
-      memcpy (&l, iter->raw + iter->d1, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
+      const uint32_t l = mlib_read_u32le (iter->raw + iter->d1);
 
       if (l > (len - (o + 4))) {
          iter->err_off = o;
@@ -611,7 +607,6 @@ fill_data_fields:
    } break;
    case BSON_TYPE_BINARY: {
       bson_subtype_t subtype;
-      uint32_t l;
 
       if (o >= (len - 4)) {
          iter->err_off = o;
@@ -621,8 +616,7 @@ fill_data_fields:
       iter->d2 = o + 4;
       iter->d3 = o + 5;
 
-      memcpy (&l, iter->raw + iter->d1, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
+      const uint32_t l = mlib_read_u32le (iter->raw + iter->d1);
 
       if (l >= (len - o - 4)) {
          iter->err_off = o;
@@ -632,17 +626,14 @@ fill_data_fields:
       subtype = *(iter->raw + iter->d2);
 
       if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
-         int32_t binary_len;
-
          if (l < 4) {
             iter->err_off = o;
             goto mark_invalid;
          }
 
          /* subtype 2 has a redundant length header in the data */
-         memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len));
-         binary_len = BSON_UINT32_FROM_LE (binary_len);
-         if (binary_len != l - 4) {
+         const int32_t bin_len = mlib_read_i32le (iter->raw + iter->d3);
+         if (mlib_cmp (bin_len, !=, l - 4)) {
             iter->err_off = iter->d3;
             goto mark_invalid;
          }
@@ -652,16 +643,12 @@ fill_data_fields:
    } break;
    case BSON_TYPE_ARRAY:
    case BSON_TYPE_DOCUMENT: {
-      uint32_t l;
-
       if (o >= (len - 4)) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
-      memcpy (&l, iter->raw + iter->d1, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
-
+      const uint32_t l = mlib_read_u32le (iter->raw + iter->d1);
       if ((l > len) || (l > (len - o))) {
          iter->err_off = o;
          goto mark_invalid;
@@ -720,16 +707,13 @@ fill_data_fields:
       iter->next_off = o + 1;
    } break;
    case BSON_TYPE_DBPOINTER: {
-      uint32_t l;
-
       if (o >= (len - 4)) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
       iter->d2 = o + 4;
-      memcpy (&l, iter->raw + iter->d1, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
+      const uint32_t l = mlib_read_u32le (iter->raw + iter->d1);
 
       /* Check valid string length. l counts '\0' but not 4 bytes for itself. */
       if (l == 0 || l > (len - o - 4)) {
@@ -747,9 +731,6 @@ fill_data_fields:
       iter->next_off = o + 4 + l + 12;
    } break;
    case BSON_TYPE_CODEWSCOPE: {
-      uint32_t l;
-      uint32_t doclen;
-
       if ((len < 19) || (o >= (len - 14))) {
          iter->err_off = o;
          goto mark_invalid;
@@ -758,40 +739,37 @@ fill_data_fields:
       iter->d2 = o + 4;
       iter->d3 = o + 8;
 
-      memcpy (&l, iter->raw + iter->d1, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
+      const uint32_t l1 = mlib_read_u32le (iter->raw + iter->d1);
 
-      if ((l < 14) || (l >= (len - o))) {
+      if ((l1 < 14) || (l1 >= (len - o))) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
-      iter->next_off = o + l;
+      iter->next_off = o + l1;
 
       if (iter->next_off >= len) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
-      memcpy (&l, iter->raw + iter->d2, sizeof (l));
-      l = BSON_UINT32_FROM_LE (l);
+      const uint32_t l2 = mlib_read_u32le (iter->raw + iter->d2);
 
-      if (l == 0 || l >= (len - o - 4 - 4)) {
+      if (l2 == 0 || l2 >= (len - o - 4 - 4)) {
          iter->err_off = o;
          goto mark_invalid;
       }
 
-      if ((o + 4 + 4 + l + 4) >= iter->next_off) {
+      if ((o + 4 + 4 + l2 + 4) >= iter->next_off) {
          iter->err_off = o + 4;
          goto mark_invalid;
       }
 
-      iter->d4 = o + 4 + 4 + l;
-      memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen));
-      doclen = BSON_UINT32_FROM_LE (doclen);
+      iter->d4 = o + 4 + 4 + l2;
+      const uint32_t doclen = mlib_read_u32le (iter->raw + iter->d4);
 
-      if ((o + 4 + 4 + l + doclen) != iter->next_off) {
-         iter->err_off = o + 4 + 4 + l;
+      if ((o + 4 + 4 + l2 + doclen) != iter->next_off) {
+         iter->err_off = o + 4 + 4 + l2;
          goto mark_invalid;
       }
    } break;
@@ -881,6 +859,12 @@ bson_iter_next (bson_iter_t *iter) /* IN
  *       @binary should not be modified or freed and is only valid while
  *       @iter's bson_t is valid and unmodified.
  *
+ *       Note: Public constraints are tighter than private ones.
+ *       API documentation says it's "a programming error to call this function
+ *       when ``iter`` is not observing an element of type BSON_TYPE_BINARY.".
+ *       Privately only, we do check the iterator type and we output NULL and
+ *       BSON_SUBTYPE_BINARY when the type is incorrect.
+ *
  * Parameters:
  *       @iter: A bson_iter_t
  *       @subtype: A location for the binary subtype.
@@ -915,8 +899,7 @@ bson_iter_binary (const bson_iter_t *ite
       *subtype = (bson_subtype_t) * (iter->raw + iter->d2);
 
       if (binary) {
-         memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len));
-         *binary_len = BSON_UINT32_FROM_LE (*binary_len);
+         *binary_len = mlib_read_u32le (iter->raw + iter->d1);
          *binary = iter->raw + iter->d3;
 
          if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
@@ -945,6 +928,149 @@ bson_iter_binary (const bson_iter_t *ite
 /*
  *--------------------------------------------------------------------------
  *
+ * bson_iter_overwrite_binary --
+ *
+ *       Obtain temporary mutable access to the contents of a BSON_TYPE_BINARY
+ *       field. It may be modified in content only, without changing length
+ *       or subtype, through a temporary pointer that's only valid until the
+ *       underlying bson_t is modified or deleted.
+ *
+ *       Note: Public constraints are tighter than private ones.
+ *       API documentation says it's "a programming error to call this function
+ *       when ``iter`` is not observing an element of type BSON_TYPE_BINARY.".
+ *       Privately only, we do check the iterator type and we return NULL when
+ *       the type is incorrect.
+ *
+ * Parameters:
+ *       @iter: A bson_iter_t
+ *       @binary_len: A location for the length of @binary.
+ *       @binary: A location for a pointer to the binary data.
+ *
+ * Returns:
+ *       On success, returns a pointer in *binary and a length in *binary_len.
+ *       The pointer is invalidated when the underlying bson_t is destroyed or modified.
+ *       If the iter does not point to a binary item of the indicated subtype,
+ *       returns NULL in *binary and 0 *binary_len.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+BSON_EXPORT (void)
+bson_iter_overwrite_binary (bson_iter_t *iter,      /* IN */
+                            bson_subtype_t subtype, /* IN */
+                            uint32_t *binary_len,   /* OUT */
+                            uint8_t **binary)       /* OUT */
+{
+   BSON_ASSERT_PARAM (iter);
+   BSON_OPTIONAL_PARAM (binary_len);
+   BSON_OPTIONAL_PARAM (binary);
+
+   bson_subtype_t iter_subtype;
+   uint32_t iter_binary_len;
+   const uint8_t *iter_binary;
+   bson_iter_binary (iter, &iter_subtype, &iter_binary_len, &iter_binary);
+
+   if (iter_binary && iter_subtype == subtype) {
+      // All of bson_iter_overwrite_* work by casting away const from iter->raw.
+      if (binary) {
+         *binary = (void *) iter_binary;
+      }
+      if (binary_len) {
+         *binary_len = iter_binary_len;
+      }
+      return;
+   }
+   if (binary) {
+      *binary = NULL;
+   }
+   if (binary_len) {
+      *binary_len = 0;
+   }
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
+ * bson_iter_binary_subtype --
+ *
+ *       Retrieves the subtype of a BSON_TYPE_BINARY field.
+ *
+ *       Note: Public constraints are tighter than private ones.
+ *       API documentation says it's "a programming error to call this function
+ *       when ``iter`` is not observing an element of type BSON_TYPE_BINARY.".
+ *       Privately only, we do check the iterator type and return
+ *       BSON_SUBTYPE_BINARY when the type is incorrect.
+ *
+ * Parameters:
+ *       @iter: A bson_iter_t
+ *
+ * Returns:
+ *       Same as the @subtype OUT parameter from bson_iter_binary().
+ *       If the iterator is valid, returns the referenced subtype. Otherwise,
+ *       returns BSON_SUBTYPE_BINARY as a fallback.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+BSON_EXPORT (bson_subtype_t)
+bson_iter_binary_subtype (const bson_iter_t *iter)
+{
+   bson_subtype_t result;
+   bson_iter_binary (iter, &result, NULL, NULL);
+   return result;
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
+ * bson_iter_binary_equal --
+ *
+ *       Compare two BSON_TYPE_BINARY fields for equality.
+ *
+ * Parameters:
+ *       @iter_a: First bson_iter_t to compare
+ *       @iter_b: Second bson_iter_t to compare
+ *
+ * Returns:
+ *       true if both iterators point to BSON_TYPE_BINARY fields with
+ *       identical subtype and contents. false if there is any difference.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+BSON_EXPORT (bool)
+bson_iter_binary_equal (const bson_iter_t *iter_a, const bson_iter_t *iter_b)
+{
+   BSON_ASSERT_PARAM (iter_a);
+   BSON_ASSERT_PARAM (iter_b);
+
+   if (BSON_ITER_HOLDS_BINARY (iter_a) && BSON_ITER_HOLDS_BINARY (iter_b)) {
+      bson_subtype_t subtypes[2];
+      uint32_t lengths[2];
+      const uint8_t *data[2];
+      bson_iter_binary (iter_a, &subtypes[0], &lengths[0], &data[0]);
+      bson_iter_binary (iter_b, &subtypes[1], &lengths[1], &data[1]);
+      return subtypes[0] == subtypes[1] && lengths[0] == lengths[1] && 0 == memcmp (data[0], data[1], lengths[0]);
+   } else {
+      return false;
+   }
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
  * bson_iter_bool --
  *
  *       Retrieves the current field of type BSON_TYPE_BOOL.
@@ -1448,21 +1574,17 @@ bson_iter_codewscope (const bson_iter_t
                       uint32_t *scope_len,     /* OUT */
                       const uint8_t **scope)   /* OUT */
 {
-   uint32_t len;
-
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) {
       if (length) {
-         memcpy (&len, iter->raw + iter->d2, sizeof (len));
+         const uint32_t len = mlib_read_u32le (iter->raw + iter->d2);
          /* The string length was checked > 0 in _bson_iter_next_internal. */
-         len = BSON_UINT32_FROM_LE (len);
          BSON_ASSERT (len > 0);
          *length = len - 1;
       }
 
-      memcpy (&len, iter->raw + iter->d4, sizeof (len));
-      *scope_len = BSON_UINT32_FROM_LE (len);
+      *scope_len = mlib_read_u32le (iter->raw + iter->d4);
       *scope = iter->raw + iter->d4;
       return (const char *) (iter->raw + iter->d3);
    }
@@ -1531,8 +1653,7 @@ bson_iter_dbpointer (const bson_iter_t *
 
    if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) {
       if (collection_len) {
-         memcpy (collection_len, (iter->raw + iter->d1), sizeof (*collection_len));
-         *collection_len = BSON_UINT32_FROM_LE (*collection_len);
+         *collection_len = mlib_read_u32le (iter->raw + iter->d1);
 
          if ((*collection_len) > 0) {
             (*collection_len)--;
@@ -1681,17 +1802,14 @@ bson_iter_timestamp (const bson_iter_t *
                      uint32_t *timestamp,     /* OUT */
                      uint32_t *increment)     /* OUT */
 {
-   uint64_t encoded;
    uint32_t ret_timestamp = 0;
    uint32_t ret_increment = 0;
 
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) {
-      memcpy (&encoded, iter->raw + iter->d1, sizeof (encoded));
-      encoded = BSON_UINT64_FROM_LE (encoded);
-      ret_timestamp = (encoded >> 32) & 0xFFFFFFFF;
-      ret_increment = encoded & 0xFFFFFFFF;
+      ret_increment = mlib_read_u32le (iter->raw + iter->d1);
+      ret_timestamp = mlib_read_u32le (iter->raw + iter->d1 + sizeof (uint32_t));
    }
 
    if (timestamp) {
@@ -1796,8 +1914,7 @@ bson_iter_document (const bson_iter_t *i
    *document_len = 0;
 
    if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) {
-      memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len));
-      *document_len = BSON_UINT32_FROM_LE (*document_len);
+      *document_len = mlib_read_u32le (iter->raw + iter->d1);
       *document = (iter->raw + iter->d1);
    }
 }
@@ -1858,8 +1975,7 @@ bson_iter_array (const bson_iter_t *iter
    *array_len = 0;
 
    if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) {
-      memcpy (array_len, (iter->raw + iter->d1), sizeof (*array_len));
-      *array_len = BSON_UINT32_FROM_LE (*array_len);
+      *array_len = mlib_read_u32le (iter->raw + iter->d1);
       *array = (iter->raw + iter->d1);
    }
 }
@@ -2210,13 +2326,11 @@ bson_iter_overwrite_oid (bson_iter_t *it
 void
 bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment)
 {
-   uint64_t value;
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) {
-      value = ((((uint64_t) timestamp) << 32U) | ((uint64_t) increment));
-      value = BSON_UINT64_TO_LE (value);
-      memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value));
+      void *out = mlib_write_u32le ((char *) iter->raw + iter->d1, increment);
+      mlib_write_u32le (out, timestamp);
    }
 }
 
@@ -2227,8 +2341,7 @@ bson_iter_overwrite_date_time (bson_iter
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) {
-      value = BSON_UINT64_TO_LE (value);
-      memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value));
+      mlib_write_i64le ((char *) iter->raw + iter->d1, value);
    }
 }
 
@@ -2257,10 +2370,7 @@ bson_iter_overwrite_int32 (bson_iter_t *
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_INT32) {
-#if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN
-      value = BSON_UINT32_TO_LE (value);
-#endif
-      memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value));
+      mlib_write_i32le ((char *) iter->raw + iter->d1, value);
    }
 }
 
@@ -2289,10 +2399,7 @@ bson_iter_overwrite_int64 (bson_iter_t *
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_INT64) {
-#if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN
-      value = BSON_UINT64_TO_LE (value);
-#endif
-      memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value));
+      mlib_write_i64le ((char *) iter->raw + iter->d1, value);
    }
 }
 
@@ -2321,8 +2428,7 @@ bson_iter_overwrite_double (bson_iter_t
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) {
-      value = BSON_DOUBLE_TO_LE (value);
-      memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value));
+      mlib_write_f64le ((char *) iter->raw + iter->d1, value);
    }
 }
 
@@ -2350,14 +2456,10 @@ bson_iter_overwrite_decimal128 (bson_ite
    BSON_ASSERT (iter);
 
    if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) {
-#if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN
-      uint64_t data[2];
-      data[0] = BSON_UINT64_TO_LE (value->low);
-      data[1] = BSON_UINT64_TO_LE (value->high);
-      memcpy ((void *) (iter->raw + iter->d1), data, sizeof (data));
-#else
-      memcpy ((void *) (iter->raw + iter->d1), value, sizeof (*value));
-#endif
+      // low bits
+      void *out = mlib_write_u64le ((char *) iter->raw + iter->d1, value->low);
+      // Followed by high bits
+      mlib_write_u64le (out, value->high);
    }
 }
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-iter.h 2.0.2-1/src/libbson/src/bson/bson-iter.h
--- 1.30.4-1/src/libbson/src/bson/bson-iter.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-iter.h	2025-06-19 15:42:22.000000000 +0000
@@ -40,6 +40,15 @@ BSON_BEGIN_DECLS
 
 #define BSON_ITER_HOLDS_BINARY(iter) (bson_iter_type ((iter)) == BSON_TYPE_BINARY)
 
+#define BSON_ITER_HOLDS_VECTOR(iter) \
+   (BSON_ITER_HOLDS_BINARY (iter) && bson_iter_binary_subtype (iter) == BSON_SUBTYPE_VECTOR)
+
+#define BSON_ITER_HOLDS_VECTOR_INT8(iter) (bson_vector_int8_const_view_from_iter (NULL, iter))
+
+#define BSON_ITER_HOLDS_VECTOR_FLOAT32(iter) (bson_vector_float32_const_view_from_iter (NULL, iter))
+
+#define BSON_ITER_HOLDS_VECTOR_PACKED_BIT(iter) (bson_vector_packed_bit_const_view_from_iter (NULL, iter))
+
 #define BSON_ITER_HOLDS_UNDEFINED(iter) (bson_iter_type ((iter)) == BSON_TYPE_UNDEFINED)
 
 #define BSON_ITER_HOLDS_OID(iter) (bson_iter_type ((iter)) == BSON_TYPE_OID)
@@ -115,6 +124,15 @@ bson_iter_array (const bson_iter_t *iter
 BSON_EXPORT (void)
 bson_iter_binary (const bson_iter_t *iter, bson_subtype_t *subtype, uint32_t *binary_len, const uint8_t **binary);
 
+BSON_EXPORT (void)
+bson_iter_overwrite_binary (bson_iter_t *iter, bson_subtype_t subtype, uint32_t *binary_len, uint8_t **binary);
+
+BSON_EXPORT (bson_subtype_t)
+bson_iter_binary_subtype (const bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_iter_binary_equal (const bson_iter_t *iter_a, const bson_iter_t *iter_b);
+
 
 BSON_EXPORT (const char *)
 bson_iter_code (const bson_iter_t *iter, uint32_t *length);
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-json.c 2.0.2-1/src/libbson/src/bson/bson-json.c
--- 1.30.4-1/src/libbson/src/bson/bson-json.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-json.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,13 +22,14 @@
 
 #include <bson/bson.h>
 #include <bson/bson-config.h>
+#include <bson/bson-error-private.h>
 #include <bson/bson-json.h>
 #include <bson/bson-json-private.h>
 #include <bson/bson-iso8601-private.h>
 
+#include <mlib/cmp.h>
 #include <common-b64-private.h>
 #include <jsonsl/jsonsl.h>
-#include <common-cmp-private.h>
 
 #ifdef _WIN32
 #include <io.h>
@@ -264,9 +265,7 @@ _noop (void)
 #define STACK_BSON_CHILD STACK_BSON (0)
 #define STACK_I STACK_ELE (0, i)
 #define STACK_FRAME_TYPE STACK_ELE (0, type)
-#define STACK_IS_INITIAL (STACK_FRAME_TYPE == BSON_JSON_FRAME_INITIAL)
 #define STACK_IS_ARRAY (STACK_FRAME_TYPE == BSON_JSON_FRAME_ARRAY)
-#define STACK_IS_DOC (STACK_FRAME_TYPE == BSON_JSON_FRAME_DOC)
 #define STACK_IS_SCOPE (STACK_FRAME_TYPE == BSON_JSON_FRAME_SCOPE)
 #define STACK_IS_DBPOINTER (STACK_FRAME_TYPE == BSON_JSON_FRAME_DBPOINTER)
 #define FRAME_TYPE_HAS_BSON(_type) ((_type) == BSON_JSON_FRAME_SCOPE || (_type) == BSON_JSON_FRAME_DBPOINTER)
@@ -422,10 +421,11 @@ _bson_json_read_set_error (bson_json_rea
    if (reader->error) {
       reader->error->domain = BSON_ERROR_JSON;
       reader->error->code = BSON_JSON_ERROR_READ_INVALID_PARAM;
+      bson_set_error_category (reader->error, BSON_ERROR_CATEGORY);
+
       va_start (ap, fmt);
       bson_vsnprintf (reader->error->message, sizeof reader->error->message, fmt, ap);
       va_end (ap);
-      reader->error->message[sizeof reader->error->message - 1] = '\0';
    }
 
    reader->bson.read_state = BSON_JSON_ERROR;
@@ -447,10 +447,11 @@ _bson_json_read_corrupt (bson_json_reade
    if (reader->error) {
       reader->error->domain = BSON_ERROR_JSON;
       reader->error->code = BSON_JSON_ERROR_READ_CORRUPT_JS;
+      bson_set_error_category (reader->error, BSON_ERROR_CATEGORY);
+
       va_start (ap, fmt);
       bson_vsnprintf (reader->error->message, sizeof reader->error->message, fmt, ap);
       va_end (ap);
-      reader->error->message[sizeof reader->error->message - 1] = '\0';
    }
 
    reader->bson.read_state = BSON_JSON_ERROR;
@@ -1110,7 +1111,7 @@ _bson_json_read_start_map (bson_json_rea
           * expected a legacy Binary format. now we see the second "{", so
           * backtrack and parse $type query operator. */
          bson->read_state = BSON_JSON_IN_START_MAP;
-         BSON_ASSERT (mcommon_in_range_unsigned (int, len));
+         BSON_ASSERT (mlib_in_range (int, len));
          STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD));
          _bson_json_save_map_key (bson, (const uint8_t *) "$type", 5);
          break;
@@ -2071,8 +2072,8 @@ bson_json_reader_read (bson_json_reader_
 
          /* accumulate a key or string value */
          if (reader->json_text_pos != -1) {
-            if (mcommon_cmp_less_su (reader->json_text_pos, reader->json->pos)) {
-               BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, reader->json->pos));
+            if (mlib_cmp (reader->json_text_pos, <, reader->json->pos)) {
+               BSON_ASSERT (mlib_in_range (ssize_t, reader->json->pos));
                accum = BSON_MIN ((ssize_t) reader->json->pos - reader->json_text_pos, r);
                /* if this chunk stopped mid-token, buf_offset is how far into
                 * our current chunk the token begins. */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-json.h 2.0.2-1/src/libbson/src/bson/bson-json.h
--- 1.30.4-1/src/libbson/src/bson/bson-json.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-json.h	2025-06-19 15:42:22.000000000 +0000
@@ -64,8 +64,8 @@ bson_json_opts_destroy (bson_json_opts_t
 BSON_EXPORT (void)
 bson_json_opts_set_outermost_array (bson_json_opts_t *opts, bool is_outermost_array);
 
-typedef ssize_t (*bson_json_reader_cb) (void *handle, uint8_t *buf, size_t count);
-typedef void (*bson_json_destroy_cb) (void *handle);
+typedef ssize_t (BSON_CALL *bson_json_reader_cb) (void *handle, uint8_t *buf, size_t count);
+typedef void (BSON_CALL *bson_json_destroy_cb) (void *handle);
 
 
 BSON_EXPORT (bson_json_reader_t *)
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-keys.c 2.0.2-1/src/libbson/src/bson/bson-keys.c
--- 1.30.4-1/src/libbson/src/bson/bson-keys.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-keys.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,7 @@
 
 #include <bson/bson-keys.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 static const char *gUint32Strs[] = {
@@ -145,6 +145,6 @@ bson_uint32_to_string (uint32_t value,
    int ret = bson_snprintf (str, size, "%u", value);
    // Truncation is OK.
    BSON_ASSERT (ret > 0);
-   BSON_ASSERT (mcommon_in_range_size_t_signed (ret));
+   BSON_ASSERT (mlib_in_range (size_t, ret));
    return (size_t) ret;
 }
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-macros.h 2.0.2-1/src/libbson/src/bson/bson-macros.h
--- 1.30.4-1/src/libbson/src/bson/bson-macros.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-macros.h	2025-06-19 15:42:22.000000000 +0000
@@ -162,15 +162,6 @@
 #define BSON_ALIGN_OF_PTR (BSON_ALIGNOF (void *))
 #endif
 
-#ifdef BSON_EXTRA_ALIGN
-#if defined(_MSC_VER)
-#define BSON_ALIGNED_BEGIN(_N) __declspec (align (_N))
-#define BSON_ALIGNED_END(_N)
-#else
-#define BSON_ALIGNED_BEGIN(_N)
-#define BSON_ALIGNED_END(_N) __attribute__ ((aligned (_N)))
-#endif
-#else
 #if defined(_MSC_VER)
 #define BSON_ALIGNED_BEGIN(_N) __declspec (align (BSON_ALIGN_OF_PTR))
 #define BSON_ALIGNED_END(_N)
@@ -178,7 +169,6 @@
 #define BSON_ALIGNED_BEGIN(_N)
 #define BSON_ALIGNED_END(_N) __attribute__ ((aligned ((_N) > BSON_ALIGN_OF_PTR ? BSON_ALIGN_OF_PTR : (_N))))
 #endif
-#endif
 
 
 #define bson_str_empty(s) (!s[0])
@@ -210,6 +200,18 @@
 #endif
 
 
+#if defined(__GNUC__)
+#define BSON_RESTRICT __restrict__
+#elif defined(_MSC_VER)
+#define BSON_RESTRICT __restrict
+#elif !defined(__cplusplus)
+// C99 (not C++)
+#define BSON_RESTRICT restrict
+#else
+#define BSON_RESTRICT
+#endif
+
+
 BSON_NORETURN static BSON_INLINE void
 _bson_assert_failed_on_line (const char *file, int line, const char *func, const char *test)
 {
@@ -329,23 +331,39 @@ _bson_assert_failed_on_param (const char
 #define BSON_TYPEOF typeof
 #endif
 
+/**
+ * @brief Statically annotate an entity as deprecated, including the given deprecation message
+ *
+ * @param Message The message to be included in a deprecation warning. This
+ * should be a string literal.
+ */
+#define BSON_DEPRECATED(Message) _bsonDeprecatedImpl (Message)
 
-#if BSON_GNUC_CHECK_VERSION(3, 1)
-#define BSON_GNUC_DEPRECATED __attribute__ ((__deprecated__))
+// Pick the appropriate implementation of a deprecation attribute
+#if defined(_MSC_VER)
+// For MSVC, emit __declspec(deprecated(Msg))
+#define _bsonDeprecatedImpl(Msg) __declspec (deprecated (Msg))
+#elif defined(__GNUC__) && (defined(__clang__) || BSON_GNUC_CHECK_VERSION(4, 5))
+// For new enough Clang and GCC, emit __attribute__((__deprecated__(Msg)))
+#define _bsonDeprecatedImpl(Msg) __attribute__ ((__deprecated__ (Msg)))
+#elif defined(__GNUC__)
+// For older GCC, emit deprecation attribute without the message
+#define _bsonDeprecatedImpl(Msg) __attribute__ ((__deprecated__))
 #else
-#define BSON_GNUC_DEPRECATED
+// For other compilers, emit nothing
+#define _bsonDeprecatedImpl(Msg)
 #endif
 
+#define BSON_DEPRECATED_FOR(F) BSON_DEPRECATED ("This API is deprecated. Use " #F " instead.")
+
+#define BSON_GNUC_DEPRECATED BSON_DEPRECATED ("This API is deprecated")
+#define BSON_GNUC_DEPRECATED_FOR(F) BSON_DEPRECATED_FOR (F)
+
 #define BSON_CONCAT_IMPL(a, ...) a##__VA_ARGS__
 #define BSON_CONCAT(a, ...) BSON_CONCAT_IMPL (a, __VA_ARGS__)
 #define BSON_CONCAT3(a, b, c) BSON_CONCAT (a, BSON_CONCAT (b, c))
 #define BSON_CONCAT4(a, b, c, d) BSON_CONCAT (BSON_CONCAT (a, b), BSON_CONCAT (c, d))
 
-#if BSON_GNUC_CHECK_VERSION(4, 5)
-#define BSON_GNUC_DEPRECATED_FOR(f) __attribute__ ((deprecated ("Use " #f " instead")))
-#else
-#define BSON_GNUC_DEPRECATED_FOR(f) BSON_GNUC_DEPRECATED
-#endif
 
 /**
  * @brief String-ify the given argument
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-md5.c 2.0.2-1/src/libbson/src/bson/bson-md5.c
--- 1.30.4-1/src/libbson/src/bson/bson-md5.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-md5.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,24 +0,0 @@
-#include <bson/bson-compat.h>
-
-#include <bson/bson-md5.h>
-#include <common-md5-private.h>
-
-
-void
-bson_md5_init (bson_md5_t *pms)
-{
-   mcommon_md5_init (pms);
-}
-
-
-void
-bson_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes)
-{
-   mcommon_md5_append (pms, data, nbytes);
-}
-
-void
-bson_md5_finish (bson_md5_t *pms, uint8_t digest[16])
-{
-   mcommon_md5_finish (pms, digest);
-}
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-md5.h 2.0.2-1/src/libbson/src/bson/bson-md5.h
--- 1.30.4-1/src/libbson/src/bson/bson-md5.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-md5.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,87 +0,0 @@
-/*
-  Copyright (C) 1999, 2002 Aladdin Enterprises.  All rights reserved.
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgement in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-
-  L. Peter Deutsch
-  ghost@aladdin.com
-
- */
-/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */
-/*
-  Independent implementation of MD5 (RFC 1321).
-
-  This code implements the MD5 Algorithm defined in RFC 1321, whose
-  text is available at
-    http://www.ietf.org/rfc/rfc1321.txt
-  The code is derived from the text of the RFC, including the test suite
-  (section A.5) but excluding the rest of Appendix A.  It does not include
-  any code or documentation that is identified in the RFC as being
-  copyrighted.
-
-  The original and principal author of md5.h is L. Peter Deutsch
-  <ghost@aladdin.com>.  Other authors are noted in the change history
-  that follows (in reverse chronological order):
-
-  2002-04-13 lpd Removed support for non-ANSI compilers; removed
-    references to Ghostscript; clarified derivation from RFC 1321;
-    now handles byte order either statically or dynamically.
-  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
-  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
-    added conditionalization for C++ compilation from Martin
-    Purschke <purschke@bnl.gov>.
-  1999-05-03 lpd Original version.
- */
-
-
-/*
- * The following MD5 implementation has been modified to use types as
- * specified in libbson.
- */
-
-#include <bson/bson-prelude.h>
-
-
-#ifndef BSON_MD5_H
-#define BSON_MD5_H
-
-
-#include <bson/bson-endian.h>
-
-
-BSON_BEGIN_DECLS
-
-
-typedef struct {
-   uint32_t count[2]; /* message length in bits, lsw first */
-   uint32_t abcd[4];  /* digest buffer */
-   uint8_t buf[64];   /* accumulate block */
-} bson_md5_t;
-
-
-BSON_EXPORT (void)
-bson_md5_init (bson_md5_t *pms) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_md5_finish (bson_md5_t *pms, uint8_t digest[16]) BSON_GNUC_DEPRECATED;
-
-
-BSON_END_DECLS
-
-
-#endif /* BSON_MD5_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-memory.h 2.0.2-1/src/libbson/src/bson/bson-memory.h
--- 1.30.4-1/src/libbson/src/bson/bson-memory.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-memory.h	2025-06-19 15:42:22.000000000 +0000
@@ -28,15 +28,15 @@
 BSON_BEGIN_DECLS
 
 
-typedef void *(*bson_realloc_func) (void *mem, size_t num_bytes, void *ctx);
+typedef void *(BSON_CALL *bson_realloc_func) (void *mem, size_t num_bytes, void *ctx);
 
 
 typedef struct _bson_mem_vtable_t {
-   void *(*malloc) (size_t num_bytes);
-   void *(*calloc) (size_t n_members, size_t num_bytes);
-   void *(*realloc) (void *mem, size_t num_bytes);
-   void (*free) (void *mem);
-   void *(*aligned_alloc) (size_t alignment, size_t num_bytes);
+   void *(BSON_CALL *malloc) (size_t num_bytes);
+   void *(BSON_CALL *calloc) (size_t n_members, size_t num_bytes);
+   void *(BSON_CALL *realloc) (void *mem, size_t num_bytes);
+   void (BSON_CALL *free) (void *mem);
+   void *(BSON_CALL *aligned_alloc) (size_t alignment, size_t num_bytes);
    void *padding[3];
 } bson_mem_vtable_t;
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-oid.c 2.0.2-1/src/libbson/src/bson/bson-oid.c
--- 1.30.4-1/src/libbson/src/bson/bson-oid.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-oid.c	2025-06-19 15:42:22.000000000 +0000
@@ -76,8 +76,9 @@ BSON_MAYBE_UNUSED static const uint16_t
 #endif
 };
 
-static BSON_INLINE void
-_oid_init (bson_oid_t *oid, bson_context_t *context, bool add_random)
+void
+bson_oid_init (bson_oid_t *oid,         /* OUT */
+               bson_context_t *context) /* IN */
 {
    BSON_ASSERT (oid);
    if (!context) {
@@ -90,27 +91,9 @@ _oid_init (bson_oid_t *oid, bson_context
    oid->bytes[1] = (uint8_t) (now >> 16);
    oid->bytes[2] = (uint8_t) (now >> 8);
    oid->bytes[3] = (uint8_t) (now >> 0);
-   // Maybe add randomness if the caller wants it
-   if (add_random) {
-      _bson_context_set_oid_rand (context, oid);
-      _bson_context_set_oid_seq32 (context, oid);
-   } else {
-      _bson_context_set_oid_seq64 (context, oid);
-   }
-}
-
-void
-bson_oid_init_sequence (bson_oid_t *oid,         /* OUT */
-                        bson_context_t *context) /* IN */
-{
-   _oid_init (oid, context, false /* no randomness */);
-}
-
-void
-bson_oid_init (bson_oid_t *oid,         /* OUT */
-               bson_context_t *context) /* IN */
-{
-   _oid_init (oid, context, true /* add randomness */);
+   // Add randomness
+   _bson_context_set_oid_rand (context, oid);
+   _bson_context_set_oid_seq32 (context, oid);
 }
 
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-oid.h 2.0.2-1/src/libbson/src/bson/bson-oid.h
--- 1.30.4-1/src/libbson/src/bson/bson-oid.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-oid.h	2025-06-19 15:42:22.000000000 +0000
@@ -51,8 +51,6 @@ bson_oid_init_from_data (bson_oid_t *oid
 BSON_EXPORT (void)
 bson_oid_init_from_string (bson_oid_t *oid, const char *str);
 BSON_EXPORT (void)
-bson_oid_init_sequence (bson_oid_t *oid, bson_context_t *context) BSON_GNUC_DEPRECATED_FOR (bson_oid_init);
-BSON_EXPORT (void)
 bson_oid_to_string (const bson_oid_t *oid, char str[25]);
 
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-private.h 2.0.2-1/src/libbson/src/bson/bson-private.h
--- 1.30.4-1/src/libbson/src/bson/bson-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -40,28 +40,19 @@ typedef enum {
 } bson_flags_t;
 
 
-#ifdef BSON_MEMCHECK
-#define BSON_INLINE_DATA_SIZE (120 - sizeof (char *))
-#else
 #define BSON_INLINE_DATA_SIZE 120
-#endif
 
 
-BSON_ALIGNED_BEGIN (128)
+BSON_ALIGNED_BEGIN (BSON_ALIGN_OF_PTR)
 typedef struct {
    bson_flags_t flags;
    uint32_t len;
-#ifdef BSON_MEMCHECK
-   char *canary;
-#endif
    uint8_t data[BSON_INLINE_DATA_SIZE];
-} bson_impl_inline_t BSON_ALIGNED_END (128);
+} bson_impl_inline_t BSON_ALIGNED_END (BSON_ALIGN_OF_PTR);
 
 
 BSON_STATIC_ASSERT2 (impl_inline_t, sizeof (bson_impl_inline_t) == 128);
 
-
-BSON_ALIGNED_BEGIN (128)
 typedef struct {
    bson_flags_t flags; /* flags describing the bson_t */
    /* len is part of the public bson_t declaration. It is not
@@ -78,11 +69,16 @@ typedef struct {
    size_t alloclen;           /* length of buffer that we own. */
    bson_realloc_func realloc; /* our realloc implementation */
    void *realloc_func_ctx;    /* context for our realloc func */
-} bson_impl_alloc_t BSON_ALIGNED_END (128);
+} bson_impl_alloc_t;
 
 
 BSON_STATIC_ASSERT2 (impl_alloc_t, sizeof (bson_impl_alloc_t) <= 128);
 
+// Ensure both `bson_t` implementations have the same alignment requirement:
+BSON_STATIC_ASSERT2 (impls_match_alignment, BSON_ALIGNOF (bson_impl_inline_t) == BSON_ALIGNOF (bson_impl_alloc_t));
+// Ensure `bson_t` has same alignment requirement as implementations:
+BSON_STATIC_ASSERT2 (impls_match_alignment, BSON_ALIGNOF (bson_t) == BSON_ALIGNOF (bson_impl_alloc_t));
+
 
 BSON_END_DECLS
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-reader.c 2.0.2-1/src/libbson/src/bson/bson-reader.c
--- 1.30.4-1/src/libbson/src/bson/bson-reader.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-reader.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <mlib/intencode.h>
 #include <bson/bson.h>
 
 #include <errno.h>
@@ -450,8 +451,6 @@ static const bson_t *
 _bson_reader_handle_read (bson_reader_handle_t *reader, /* IN */
                           bool *reached_eof)            /* IN */
 {
-   int32_t blen;
-
    if (reached_eof) {
       *reached_eof = false;
    }
@@ -462,9 +461,7 @@ _bson_reader_handle_read (bson_reader_ha
          continue;
       }
 
-      memcpy (&blen, &reader->data[reader->offset], sizeof blen);
-      blen = BSON_UINT32_FROM_LE (blen);
-
+      const int32_t blen = mlib_read_i32le (reader->data + reader->offset);
       if (blen < 5) {
          return NULL;
       }
@@ -556,16 +553,12 @@ static const bson_t *
 _bson_reader_data_read (bson_reader_data_t *reader, /* IN */
                         bool *reached_eof)          /* IN */
 {
-   int32_t blen;
-
    if (reached_eof) {
       *reached_eof = false;
    }
 
    if ((reader->offset + 4) < reader->length) {
-      memcpy (&blen, &reader->data[reader->offset], sizeof blen);
-      blen = BSON_UINT32_FROM_LE (blen);
-
+      const int32_t blen = mlib_read_i32le (reader->data + reader->offset);
       if (blen < 5) {
          return NULL;
       }
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-reader.h 2.0.2-1/src/libbson/src/bson/bson-reader.h
--- 1.30.4-1/src/libbson/src/bson/bson-reader.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-reader.h	2025-06-19 15:42:22.000000000 +0000
@@ -59,9 +59,9 @@ BSON_BEGIN_DECLS
  *--------------------------------------------------------------------------
  */
 
-typedef ssize_t (*bson_reader_read_func_t) (void *handle,  /* IN */
-                                            void *buf,     /* IN */
-                                            size_t count); /* IN */
+typedef ssize_t (BSON_CALL *bson_reader_read_func_t) (void *handle,  /* IN */
+                                                      void *buf,     /* IN */
+                                                      size_t count); /* IN */
 
 
 /*
@@ -84,7 +84,7 @@ typedef ssize_t (*bson_reader_read_func_
  *--------------------------------------------------------------------------
  */
 
-typedef void (*bson_reader_destroy_func_t) (void *handle); /* IN */
+typedef void (BSON_CALL *bson_reader_destroy_func_t) (void *handle); /* IN */
 
 
 BSON_EXPORT (bson_reader_t *)
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-string.c 2.0.2-1/src/libbson/src/bson/bson-string.c
--- 1.30.4-1/src/libbson/src/bson/bson-string.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-string.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,7 @@
 
 #include <bson/bson-compat.h>
 #include <bson/bson-config.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-string-private.h>
 #include <common-bits-private.h>
 #include <bson/bson-memory.h>
@@ -33,116 +33,6 @@
 #endif
 
 
-bson_string_t *
-bson_string_new (const char *str) /* IN */
-{
-   /* Compatibility wrapper; deprecated.
-    * New mcommon_string behavior is to use power of two rounding for resize but not for initial allocation unless
-    * extra capacity is explicitly requested. This emulates the old behavior, padding the allocation of all new strings.
-    */
-   size_t len = str ? strlen (str) : 0;
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, len) && (uint32_t) len < UINT32_MAX);
-   uint32_t alloc = mcommon_next_power_of_two_u32 ((uint32_t) len + 1);
-   return (bson_string_t *) mcommon_string_new_with_capacity (str ? str : "", (uint32_t) len, alloc - 1);
-}
-
-char *
-bson_string_free (bson_string_t *string, /* IN */
-                  bool free_segment)     /* IN */
-{
-   // Compatibility wrapper; deprecated.
-   if (free_segment) {
-      mcommon_string_destroy ((mcommon_string_t *) string);
-      return NULL;
-   } else {
-      return mcommon_string_destroy_with_steal ((mcommon_string_t *) string);
-   }
-}
-
-void
-bson_string_append (bson_string_t *string, /* IN */
-                    const char *str)       /* IN */
-{
-   // Compatibility wrapper; deprecated.
-   BSON_ASSERT_PARAM (string);
-   BSON_ASSERT_PARAM (str);
-
-   mcommon_string_append_t append;
-   mcommon_string_set_append ((mcommon_string_t *) string, &append);
-   (void) mcommon_string_append (&append, str);
-}
-
-void
-bson_string_append_unichar (bson_string_t *string,  /* IN */
-                            bson_unichar_t unichar) /* IN */
-{
-   // Compatibility wrapper; deprecated.
-   BSON_ASSERT_PARAM (string);
-
-   mcommon_string_append_t append;
-   mcommon_string_set_append ((mcommon_string_t *) string, &append);
-   (void) mcommon_string_append_unichar (&append, unichar);
-}
-
-void
-bson_string_append_c (bson_string_t *string, /* IN */
-                      char c)                /* IN */
-{
-   // Compatibility wrapper; deprecated.
-   BSON_ASSERT_PARAM (string);
-
-   mcommon_string_append_t append;
-   mcommon_string_set_append ((mcommon_string_t *) string, &append);
-   (void) mcommon_string_append_bytes (&append, &c, 1);
-}
-
-void
-bson_string_append_printf (bson_string_t *string, const char *format, ...)
-{
-   // Compatibility wrapper; deprecated.
-   BSON_ASSERT_PARAM (string);
-   BSON_ASSERT_PARAM (format);
-
-   va_list args;
-   mcommon_string_append_t append;
-   mcommon_string_set_append ((mcommon_string_t *) string, &append);
-   va_start (args, format);
-   (void) mcommon_string_append_vprintf (&append, format, args);
-   va_end (args);
-}
-
-
-void
-bson_string_truncate (bson_string_t *string, /* IN */
-                      uint32_t len)          /* IN */
-{
-   /* Does not preserve UTF-8 validity; deprecated.
-    * Although the documentation only describes truncation as decreasing the length, we have undocumented requirements:
-    * the string may grow or shrink, and the buffer is expected to be allocated using the same power-of-two scheme as
-    * when growing to append. No effect if 'string' already has the requested length, regardless of the allocation size.
-    * When extending string length, this implementation is guaranteed to fill with NUL bytes. Previous versions left the
-    * new buffer contents undefined.
-    */
-   BSON_ASSERT_PARAM (string);
-   BSON_ASSERT (len < UINT32_MAX);
-
-   uint32_t old_len = string->len;
-   if (len != old_len) {
-      uint32_t alloc = mcommon_next_power_of_two_u32 (len + 1u);
-      char *buffer = bson_realloc (string->str, alloc);
-      string->str = buffer;
-      string->alloc = alloc;
-      string->len = len;
-
-      if (len < old_len) {
-         buffer[len] = '\0';
-      } else {
-         memset (buffer + old_len, 0, len + 1 - old_len);
-      }
-   }
-}
-
-
 /*
  *--------------------------------------------------------------------------
  *
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-string.h 2.0.2-1/src/libbson/src/bson/bson-string.h
--- 1.30.4-1/src/libbson/src/bson/bson-string.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-string.h	2025-06-19 15:42:22.000000000 +0000
@@ -29,50 +29,39 @@
 
 BSON_BEGIN_DECLS
 
-
-typedef struct {
-   char *str;
-   uint32_t len;
-   uint32_t alloc;
-} bson_string_t;
-
-
-BSON_EXPORT (bson_string_t *)
-bson_string_new (const char *str) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (char *)
-bson_string_free (bson_string_t *string, bool free_segment) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_string_append (bson_string_t *string, const char *str) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_string_append_c (bson_string_t *string, char str) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_string_append_unichar (bson_string_t *string, bson_unichar_t unichar) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_string_append_printf (bson_string_t *string, const char *format, ...) BSON_GNUC_PRINTF (2, 3) BSON_GNUC_DEPRECATED;
-BSON_EXPORT (void)
-bson_string_truncate (bson_string_t *string, uint32_t len) BSON_GNUC_DEPRECATED;
 BSON_EXPORT (char *)
 bson_strdup (const char *str);
+
 BSON_EXPORT (char *)
 bson_strdup_printf (const char *format, ...) BSON_GNUC_PRINTF (1, 2);
+
 BSON_EXPORT (char *)
 bson_strdupv_printf (const char *format, va_list args) BSON_GNUC_PRINTF (1, 0);
+
 BSON_EXPORT (char *)
 bson_strndup (const char *str, size_t n_bytes);
+
 BSON_EXPORT (void)
 bson_strncpy (char *dst, const char *src, size_t size);
+
 BSON_EXPORT (int)
 bson_vsnprintf (char *str, size_t size, const char *format, va_list ap) BSON_GNUC_PRINTF (3, 0);
+
 BSON_EXPORT (int)
 bson_snprintf (char *str, size_t size, const char *format, ...) BSON_GNUC_PRINTF (3, 4);
+
 BSON_EXPORT (void)
 bson_strfreev (char **strv);
+
 BSON_EXPORT (size_t)
 bson_strnlen (const char *s, size_t maxlen);
+
 BSON_EXPORT (int64_t)
 bson_ascii_strtoll (const char *str, char **endptr, int base);
+
 BSON_EXPORT (int)
 bson_strcasecmp (const char *s1, const char *s2);
+
 BSON_EXPORT (bool)
 bson_isspace (int c);
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-timegm.c 2.0.2-1/src/libbson/src/bson/bson-timegm.c
--- 1.30.4-1/src/libbson/src/bson/bson-timegm.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-timegm.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,21 +18,10 @@
 #include <string.h>
 #include <stdint.h> /* for INT64_MAX and INT64_MIN */
 
-/* Unlike <ctype.h>'s isdigit, this also works if c < 0 | c > UCHAR_MAX. */
-#define is_digit(c) ((unsigned) (c) - '0' <= 9)
-
 #if 2 < __GNUC__ + (96 <= __GNUC_MINOR__)
-#define ATTRIBUTE_CONST __attribute__ ((const))
 #define ATTRIBUTE_PURE __attribute__ ((__pure__))
-#define ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
 #else
-#define ATTRIBUTE_CONST        /* empty */
-#define ATTRIBUTE_PURE         /* empty */
-#define ATTRIBUTE_FORMAT(spec) /* empty */
-#endif
-
-#if !defined(__STDC_VERSION__) && !defined restrict
-#define restrict /* empty */
+#define ATTRIBUTE_PURE /* empty */
 #endif
 
 #ifdef __clang__
@@ -79,88 +68,13 @@ static int64_t const time_t_max = INT64_
 #define SECSPERDAY ((int_fast32_t) SECSPERHOUR * HOURSPERDAY)
 #define MONSPERYEAR 12
 
-#define TM_SUNDAY 0
-#define TM_MONDAY 1
-#define TM_TUESDAY 2
-#define TM_WEDNESDAY 3
-#define TM_THURSDAY 4
-#define TM_FRIDAY 5
-#define TM_SATURDAY 6
-
-#define TM_JANUARY 0
-#define TM_FEBRUARY 1
-#define TM_MARCH 2
-#define TM_APRIL 3
-#define TM_MAY 4
-#define TM_JUNE 5
-#define TM_JULY 6
-#define TM_AUGUST 7
-#define TM_SEPTEMBER 8
-#define TM_OCTOBER 9
-#define TM_NOVEMBER 10
-#define TM_DECEMBER 11
-
 #define TM_YEAR_BASE 1900
 
 #define EPOCH_YEAR 1970
-#define EPOCH_WDAY TM_THURSDAY
+#define EPOCH_WDAY 4 /* TM_THURSDAY */
 
 #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
 
-/*
-** Since everything in isleap is modulo 400 (or a factor of 400), we know that
-**	isleap(y) == isleap(y % 400)
-** and so
-**	isleap(a + b) == isleap((a + b) % 400)
-** or
-**	isleap(a + b) == isleap(a % 400 + b % 400)
-** This is true even if % means modulo rather than Fortran remainder
-** (which is allowed by C89 but not C99).
-** We use this to avoid addition overflow problems.
-*/
-
-#define isleap_sum(a, b) isleap ((a) % 400 + (b) % 400)
-
-#ifndef TZ_ABBR_MAX_LEN
-#define TZ_ABBR_MAX_LEN 16
-#endif /* !defined TZ_ABBR_MAX_LEN */
-
-#ifndef TZ_ABBR_CHAR_SET
-#define TZ_ABBR_CHAR_SET "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
-#endif /* !defined TZ_ABBR_CHAR_SET */
-
-#ifndef TZ_ABBR_ERR_CHAR
-#define TZ_ABBR_ERR_CHAR '_'
-#endif /* !defined TZ_ABBR_ERR_CHAR */
-
-#ifndef WILDABBR
-/*
-** Someone might make incorrect use of a time zone abbreviation:
-**	1.	They might reference tzname[0] before calling tzset (explicitly
-**		or implicitly).
-**	2.	They might reference tzname[1] before calling tzset (explicitly
-**		or implicitly).
-**	3.	They might reference tzname[1] after setting to a time zone
-**		in which Daylight Saving Time is never observed.
-**	4.	They might reference tzname[0] after setting to a time zone
-**		in which Standard Time is never observed.
-**	5.	They might reference tm.TM_ZONE after calling offtime.
-** What's best to do in the above cases is open to debate;
-** for now, we just set things up so that in any of the five cases
-** WILDABBR is used. Another possibility: initialize tzname[0] to the
-** string "tzname[0] used before set", and similarly for the other cases.
-** And another: initialize tzname[0] to "ERA", with an explanation in the
-** manual page of what this "time zone abbreviation" means (doing this so
-** that tzname[0] has the "normal" length of three characters).
-*/
-#define WILDABBR "   "
-#endif /* !defined WILDABBR */
-
-#ifdef TM_ZONE
-static const char wildabbr[] = WILDABBR;
-static const char gmt[] = "GMT";
-#endif
-
 struct ttinfo {            /* time type information */
    int_fast32_t tt_gmtoff; /* UT offset in seconds */
    int tt_isdst;           /* used to set tm_isdst */
@@ -206,10 +120,6 @@ struct rule {
    int_fast32_t r_time; /* transition time of rule */
 };
 
-#define JULIAN_DAY 0            /* Jn - Julian day */
-#define DAY_OF_YEAR 1           /* n - day of year */
-#define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d - month, week, day of week */
-
 /*
 ** Prototypes for static functions.
 */
@@ -286,14 +196,6 @@ gmtsub (const int64_t *const timep, cons
       gmtload (gmtptr);
    }
    result = timesub (timep, offset, gmtptr, tmp);
-#ifdef TM_ZONE
-   /*
-   ** Could get fancy here and deliver something such as
-   ** "UT+xxxx" or "UT-xxxx" if offset is non-zero,
-   ** but this is no time for a treasure hunt.
-   */
-   tmp->TM_ZONE = offset ? wildabbr : gmtptr ? gmtptr->chars : gmt;
-#endif /* defined TM_ZONE */
    return result;
 }
 
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-types.h 2.0.2-1/src/libbson/src/bson/bson-types.h
--- 1.30.4-1/src/libbson/src/bson/bson-types.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-types.h	2025-06-19 15:42:22.000000000 +0000
@@ -41,9 +41,6 @@ BSON_BEGIN_DECLS
  *       unicode characters. When iterating UTF-8 sequences, this should
  *       be used to avoid losing the high-bits of non-ascii characters.
  *
- * See also:
- *       bson_string_append_unichar()
- *
  *--------------------------------------------------------------------------
  */
 
@@ -123,20 +120,11 @@ typedef struct _bson_json_opts_t bson_js
  *
  * This structure is meant to fit in two sequential 64-byte cachelines.
  */
-#ifdef BSON_MEMCHECK
-BSON_ALIGNED_BEGIN (128) typedef struct _bson_t {
-   uint32_t flags; /* Internal flags for the bson_t. */
-   uint32_t len;   /* Length of BSON data. */
-   char *canary;   /* For leak checks. */
-   uint8_t padding[120 - sizeof (char *)];
-} bson_t BSON_ALIGNED_END (128);
-#else
-BSON_ALIGNED_BEGIN (128) typedef struct _bson_t {
+BSON_ALIGNED_BEGIN (BSON_ALIGN_OF_PTR) typedef struct _bson_t {
    uint32_t flags;       /* Internal flags for the bson_t. */
    uint32_t len;         /* Length of BSON data. */
    uint8_t padding[120]; /* Padding for stack allocation. */
-} bson_t BSON_ALIGNED_END (128);
-#endif
+} bson_t BSON_ALIGNED_END (BSON_ALIGN_OF_PTR);
 
 /**
  * BSON_INITIALIZER:
@@ -148,12 +136,6 @@ BSON_ALIGNED_BEGIN (128) typedef struct
  * bson_t b = BSON_INITIALIZER;
  * ]|
  */
-#ifdef BSON_MEMCHECK
-#define BSON_INITIALIZER          \
-   {                              \
-      3, 5, bson_malloc (1), {5}, \
-   }
-#else
 #define BSON_INITIALIZER \
    {                     \
       3, 5,              \
@@ -161,7 +143,6 @@ BSON_ALIGNED_BEGIN (128) typedef struct
          5               \
       }                  \
    }
-#endif
 
 
 BSON_STATIC_ASSERT2 (bson_t, sizeof (bson_t) == 128);
@@ -204,25 +185,54 @@ typedef struct {
 
 
 /**
- * bson_validate_flags_t:
+ * @brief Flags and error codes for BSON validation functions.
  *
- * This enumeration is used for validation of BSON documents. It allows
- * selective control on what you wish to validate.
+ * Pass these flags bits to control the behavior of the `bson_validate` family
+ * of functions.
  *
- * %BSON_VALIDATE_NONE: No additional validation occurs.
- * %BSON_VALIDATE_UTF8: Check that strings are valid UTF-8.
- * %BSON_VALIDATE_DOLLAR_KEYS: Check that keys do not start with $.
- * %BSON_VALIDATE_DOT_KEYS: Check that keys do not contain a period.
- * %BSON_VALIDATE_UTF8_ALLOW_NULL: Allow NUL bytes in UTF-8 text.
- * %BSON_VALIDATE_EMPTY_KEYS: Prohibit zero-length field names
+ * Additionally, if validation fails, then the error code set on a `bson_error_t`
+ * will have the value corresponding to the reason that validation failed.
  */
 typedef enum {
+   /**
+    * @brief No special validation behavior specified.
+    */
    BSON_VALIDATE_NONE = 0,
+   /**
+    * @brief Check that all text components of the BSON data are valid UTF-8.
+    *
+    * Note that this will also cause validation to reject valid text that contains
+    * a null character. This can be changed by also passing
+    * `BSON_VALIDATE_UTF8_ALLOW_NULL`
+    */
    BSON_VALIDATE_UTF8 = (1 << 0),
+   /**
+    * @brief Check that element keys do not begin with an ASCII dollar `$`
+    */
    BSON_VALIDATE_DOLLAR_KEYS = (1 << 1),
+   /**
+    * @brief Check that element keys do not contain an ASCII period `.`
+    */
    BSON_VALIDATE_DOT_KEYS = (1 << 2),
+   /**
+    * @brief If set then it is *not* an error for a UTF-8 string to contain
+    * embedded null characters.
+    *
+    * This has no effect unless `BSON_VALIDATE_UTF8` is also passed.
+    */
    BSON_VALIDATE_UTF8_ALLOW_NULL = (1 << 3),
+   /**
+    * @brief Check that no element key is a zero-length empty string.
+    */
    BSON_VALIDATE_EMPTY_KEYS = (1 << 4),
+   /**
+    * @brief This is not a flag that controls behavior, but is instead used to indicate
+    * that a BSON document is corrupted in some way. This is the value that will
+    * appear as an error code.
+    *
+    * Passing this as a flag has no effect.
+    */
+   BSON_VALIDATE_CORRUPT = (1 << 5),
 } bson_validate_flags_t;
 
 
@@ -274,6 +284,7 @@ typedef enum {
    BSON_SUBTYPE_ENCRYPTED = 0x06,
    BSON_SUBTYPE_COLUMN = 0x07,
    BSON_SUBTYPE_SENSITIVE = 0x08,
+   BSON_SUBTYPE_VECTOR = 0x09,
    BSON_SUBTYPE_USER = 0x80,
 } bson_subtype_t;
 
@@ -292,7 +303,6 @@ typedef enum {
  *--------------------------------------------------------------------------
  */
 
-BSON_ALIGNED_BEGIN (8)
 typedef struct _bson_value_t {
    bson_type_t value_type;
    int32_t padding;
@@ -346,7 +356,7 @@ typedef struct _bson_value_t {
       } v_symbol;
       bson_decimal128_t v_decimal128;
    } value;
-} bson_value_t BSON_ALIGNED_END (8);
+} bson_value_t;
 
 
 /**
@@ -360,7 +370,6 @@ typedef struct _bson_value_t {
  * This structure is safe to discard on the stack. No cleanup is necessary
  * after using it.
  */
-BSON_ALIGNED_BEGIN (128)
 typedef struct {
    const uint8_t *raw; /* The raw buffer being iterated. */
    uint32_t len;       /* The length of raw. */
@@ -374,7 +383,7 @@ typedef struct {
    uint32_t next_off;  /* The offset of the next field. */
    uint32_t err_off;   /* The offset of the error. */
    bson_value_t value; /* Internal value for various state. */
-} bson_iter_t BSON_ALIGNED_END (128);
+} bson_iter_t;
 
 
 /**
@@ -407,72 +416,74 @@ typedef struct {
  * You may pre-maturely stop the visitation of fields by returning true in your
  * visitor. Returning false will continue visitation to further fields.
  */
-BSON_ALIGNED_BEGIN (8)
 typedef struct {
    /* run before / after descending into a document */
-   bool (*visit_before) (const bson_iter_t *iter, const char *key, void *data);
-   bool (*visit_after) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_before) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_after) (const bson_iter_t *iter, const char *key, void *data);
    /* corrupt BSON, or unsupported type and visit_unsupported_type not set */
-   void (*visit_corrupt) (const bson_iter_t *iter, void *data);
+   void (BSON_CALL *visit_corrupt) (const bson_iter_t *iter, void *data);
    /* normal bson field callbacks */
-   bool (*visit_double) (const bson_iter_t *iter, const char *key, double v_double, void *data);
-   bool (*visit_utf8) (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data);
-   bool (*visit_document) (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data);
-   bool (*visit_array) (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data);
-   bool (*visit_binary) (const bson_iter_t *iter,
-                         const char *key,
-                         bson_subtype_t v_subtype,
-                         size_t v_binary_len,
-                         const uint8_t *v_binary,
-                         void *data);
+   bool (BSON_CALL *visit_double) (const bson_iter_t *iter, const char *key, double v_double, void *data);
+   bool (BSON_CALL *visit_utf8) (
+      const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data);
+   bool (BSON_CALL *visit_document) (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data);
+   bool (BSON_CALL *visit_array) (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data);
+   bool (BSON_CALL *visit_binary) (const bson_iter_t *iter,
+                                   const char *key,
+                                   bson_subtype_t v_subtype,
+                                   size_t v_binary_len,
+                                   const uint8_t *v_binary,
+                                   void *data);
    /* normal field with deprecated "Undefined" BSON type */
-   bool (*visit_undefined) (const bson_iter_t *iter, const char *key, void *data);
-   bool (*visit_oid) (const bson_iter_t *iter, const char *key, const bson_oid_t *v_oid, void *data);
-   bool (*visit_bool) (const bson_iter_t *iter, const char *key, bool v_bool, void *data);
-   bool (*visit_date_time) (const bson_iter_t *iter, const char *key, int64_t msec_since_epoch, void *data);
-   bool (*visit_null) (const bson_iter_t *iter, const char *key, void *data);
-   bool (*visit_regex) (
+   bool (BSON_CALL *visit_undefined) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_oid) (const bson_iter_t *iter, const char *key, const bson_oid_t *v_oid, void *data);
+   bool (BSON_CALL *visit_bool) (const bson_iter_t *iter, const char *key, bool v_bool, void *data);
+   bool (BSON_CALL *visit_date_time) (const bson_iter_t *iter, const char *key, int64_t msec_since_epoch, void *data);
+   bool (BSON_CALL *visit_null) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_regex) (
       const bson_iter_t *iter, const char *key, const char *v_regex, const char *v_options, void *data);
-   bool (*visit_dbpointer) (const bson_iter_t *iter,
-                            const char *key,
-                            size_t v_collection_len,
-                            const char *v_collection,
-                            const bson_oid_t *v_oid,
-                            void *data);
-   bool (*visit_code) (const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, void *data);
-   bool (*visit_symbol) (
+   bool (BSON_CALL *visit_dbpointer) (const bson_iter_t *iter,
+                                      const char *key,
+                                      size_t v_collection_len,
+                                      const char *v_collection,
+                                      const bson_oid_t *v_oid,
+                                      void *data);
+   bool (BSON_CALL *visit_code) (
+      const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, void *data);
+   bool (BSON_CALL *visit_symbol) (
       const bson_iter_t *iter, const char *key, size_t v_symbol_len, const char *v_symbol, void *data);
-   bool (*visit_codewscope) (const bson_iter_t *iter,
-                             const char *key,
-                             size_t v_code_len,
-                             const char *v_code,
-                             const bson_t *v_scope,
-                             void *data);
-   bool (*visit_int32) (const bson_iter_t *iter, const char *key, int32_t v_int32, void *data);
-   bool (*visit_timestamp) (
+   bool (BSON_CALL *visit_codewscope) (const bson_iter_t *iter,
+                                       const char *key,
+                                       size_t v_code_len,
+                                       const char *v_code,
+                                       const bson_t *v_scope,
+                                       void *data);
+   bool (BSON_CALL *visit_int32) (const bson_iter_t *iter, const char *key, int32_t v_int32, void *data);
+   bool (BSON_CALL *visit_timestamp) (
       const bson_iter_t *iter, const char *key, uint32_t v_timestamp, uint32_t v_increment, void *data);
-   bool (*visit_int64) (const bson_iter_t *iter, const char *key, int64_t v_int64, void *data);
-   bool (*visit_maxkey) (const bson_iter_t *iter, const char *key, void *data);
-   bool (*visit_minkey) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_int64) (const bson_iter_t *iter, const char *key, int64_t v_int64, void *data);
+   bool (BSON_CALL *visit_maxkey) (const bson_iter_t *iter, const char *key, void *data);
+   bool (BSON_CALL *visit_minkey) (const bson_iter_t *iter, const char *key, void *data);
    /* if set, called instead of visit_corrupt when an apparently valid BSON
     * includes an unrecognized field type (reading future version of BSON) */
-   void (*visit_unsupported_type) (const bson_iter_t *iter, const char *key, uint32_t type_code, void *data);
-   bool (*visit_decimal128) (const bson_iter_t *iter,
-                             const char *key,
-                             const bson_decimal128_t *v_decimal128,
-                             void *data);
+   void (BSON_CALL *visit_unsupported_type) (const bson_iter_t *iter, const char *key, uint32_t type_code, void *data);
+   bool (BSON_CALL *visit_decimal128) (const bson_iter_t *iter,
+                                       const char *key,
+                                       const bson_decimal128_t *v_decimal128,
+                                       void *data);
 
    void *padding[7];
-} bson_visitor_t BSON_ALIGNED_END (8);
+} bson_visitor_t;
 
-#define BSON_ERROR_BUFFER_SIZE 504
+#define BSON_ERROR_BUFFER_SIZE 503
 
-BSON_ALIGNED_BEGIN (8)
+BSON_ALIGNED_BEGIN (BSON_ALIGN_OF_PTR) // Aligned for backwards-compatibility.
 typedef struct _bson_error_t {
    uint32_t domain;
    uint32_t code;
    char message[BSON_ERROR_BUFFER_SIZE];
-} bson_error_t BSON_ALIGNED_END (8);
+   uint8_t reserved; // For internal use only!
+} bson_error_t BSON_ALIGNED_END (BSON_ALIGN_OF_PTR);
 
 
 BSON_STATIC_ASSERT2 (error_t, sizeof (bson_error_t) == 512);
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-utf8.c 2.0.2-1/src/libbson/src/bson/bson-utf8.c
--- 1.30.4-1/src/libbson/src/bson/bson-utf8.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-utf8.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,7 +18,7 @@
 #include <string.h>
 
 #include <bson/bson-memory.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-json-private.h>
 #include <common-macros-private.h>
 #include <common-string-private.h>
@@ -226,7 +226,7 @@ bson_utf8_escape_for_json (const char *u
          return NULL;
       }
    } else {
-      if (mcommon_in_range_signed (uint32_t, utf8_len) && (uint32_t) utf8_len < UINT32_MAX) {
+      if (mlib_in_range (uint32_t, utf8_len) && (uint32_t) utf8_len < UINT32_MAX) {
          len32 = utf8_len;
          allow_nul = true;
       } else {
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-value.c 2.0.2-1/src/libbson/src/bson/bson-value.c
--- 1.30.4-1/src/libbson/src/bson/bson-value.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-value.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,7 @@
 #include <common-string-private.h>
 #include <bson/bson-value.h>
 #include <bson/bson-oid.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 void
@@ -36,7 +36,7 @@ bson_value_copy (const bson_value_t *src
       dst->value.v_double = src->value.v_double;
       break;
    case BSON_TYPE_UTF8:
-      BSON_ASSERT (mcommon_in_range_size_t_unsigned (src->value.v_utf8.len));
+      BSON_ASSERT (mlib_in_range (size_t, src->value.v_utf8.len));
       size_t utf8_len_sz = (size_t) src->value.v_utf8.len;
       if (utf8_len_sz == SIZE_MAX) {
          // If the string is at maximum length, do not NULL terminate. The source necessarily cannot fit it.
@@ -79,7 +79,7 @@ bson_value_copy (const bson_value_t *src
       dst->value.v_regex.options = bson_strdup (src->value.v_regex.options);
       break;
    case BSON_TYPE_DBPOINTER:
-      BSON_ASSERT (mcommon_in_range_size_t_unsigned (src->value.v_dbpointer.collection_len));
+      BSON_ASSERT (mlib_in_range (size_t, src->value.v_dbpointer.collection_len));
       size_t dbpointer_len_sz = (size_t) src->value.v_dbpointer.collection_len;
       BSON_ASSERT (dbpointer_len_sz <= SIZE_MAX - 1);
       dst->value.v_dbpointer.collection_len = src->value.v_dbpointer.collection_len;
@@ -90,7 +90,7 @@ bson_value_copy (const bson_value_t *src
       bson_oid_copy (&src->value.v_dbpointer.oid, &dst->value.v_dbpointer.oid);
       break;
    case BSON_TYPE_CODE:
-      BSON_ASSERT (mcommon_in_range_size_t_unsigned (src->value.v_code.code_len));
+      BSON_ASSERT (mlib_in_range (size_t, src->value.v_code.code_len));
       size_t code_len_sz = (size_t) src->value.v_code.code_len;
       BSON_ASSERT (code_len_sz <= SIZE_MAX - 1);
       dst->value.v_code.code_len = src->value.v_code.code_len;
@@ -99,7 +99,7 @@ bson_value_copy (const bson_value_t *src
       dst->value.v_code.code[dst->value.v_code.code_len] = '\0';
       break;
    case BSON_TYPE_SYMBOL:
-      BSON_ASSERT (mcommon_in_range_size_t_unsigned (src->value.v_symbol.len));
+      BSON_ASSERT (mlib_in_range (size_t, src->value.v_symbol.len));
       size_t symbol_len_sz = (size_t) src->value.v_symbol.len;
       BSON_ASSERT (symbol_len_sz <= SIZE_MAX - 1);
       dst->value.v_symbol.len = src->value.v_symbol.len;
@@ -108,7 +108,7 @@ bson_value_copy (const bson_value_t *src
       dst->value.v_symbol.symbol[dst->value.v_symbol.len] = '\0';
       break;
    case BSON_TYPE_CODEWSCOPE:
-      BSON_ASSERT (mcommon_in_range_size_t_unsigned (src->value.v_codewscope.code_len));
+      BSON_ASSERT (mlib_in_range (size_t, src->value.v_codewscope.code_len));
       size_t codewscope_len_sz = (size_t) src->value.v_codewscope.code_len;
       BSON_ASSERT (codewscope_len_sz <= SIZE_MAX - 1);
       dst->value.v_codewscope.code_len = src->value.v_codewscope.code_len;
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-vector-private.h 2.0.2-1/src/libbson/src/bson/bson-vector-private.h
--- 1.30.4-1/src/libbson/src/bson/bson-vector-private.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-vector-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bson/bson-prelude.h>
+
+#ifndef BSON_VECTOR_PRIVATE_H
+#define BSON_VECTOR_PRIVATE_H
+
+#include <bson/bson-macros.h>
+#include <bson/bson-compat.h>
+
+BSON_BEGIN_DECLS
+
+
+typedef enum {
+   BSON_VECTOR_ELEMENT_SIGNED_INT = 0,
+   BSON_VECTOR_ELEMENT_UNSIGNED_INT = 1,
+   BSON_VECTOR_ELEMENT_FLOAT = 2,
+} bson_vector_element_type_t;
+
+typedef enum {
+   BSON_VECTOR_ELEMENT_1_BIT = 0,
+   BSON_VECTOR_ELEMENT_8_BITS = 3,
+   BSON_VECTOR_ELEMENT_32_BITS = 7,
+} bson_vector_element_size_t;
+
+
+static BSON_INLINE uint8_t
+bson_vector_header_byte_0 (bson_vector_element_type_t element_type, bson_vector_element_size_t element_size)
+{
+   BSON_ASSERT ((unsigned) element_type <= 0x0f);
+   BSON_ASSERT ((unsigned) element_size <= 0x0f);
+   return (uint8_t) (((unsigned) element_type << 4) | (unsigned) element_size);
+}
+
+// See also `bson_vector_padding_from_header_byte_1` defined in <bson/bson-vector.h> for use by public inline functions.
+static BSON_INLINE uint8_t
+bson_vector_header_byte_1 (size_t padding)
+{
+   BSON_ASSERT (padding <= 7);
+   return (uint8_t) padding;
+}
+
+
+BSON_END_DECLS
+
+#endif /* BSON_VECTOR_PRIVATE_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-vector.c 2.0.2-1/src/libbson/src/bson/bson-vector.c
--- 1.30.4-1/src/libbson/src/bson/bson-vector.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-vector.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,681 @@
+/*
+ * Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <bson/bson.h>
+#include <bson/bson-vector-private.h>
+
+
+static BSON_INLINE bool
+bson_vector_binary_header_impl_init (bson_vector_binary_header_impl_t *header_out,
+                                     const uint8_t *binary_data,
+                                     uint32_t binary_data_len)
+{
+   if (binary_data_len >= BSON_VECTOR_HEADER_LEN) {
+      memcpy (header_out->bytes, binary_data, BSON_VECTOR_HEADER_LEN);
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static BSON_INLINE bool
+bson_vector_int8_validate (bson_vector_binary_header_impl_t header)
+{
+   return header.bytes[0] == bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_SIGNED_INT, BSON_VECTOR_ELEMENT_8_BITS) &&
+          header.bytes[1] == bson_vector_header_byte_1 (0);
+}
+
+static BSON_INLINE bool
+bson_vector_float32_validate (bson_vector_binary_header_impl_t header, uint32_t binary_data_len)
+{
+   return (binary_data_len - BSON_VECTOR_HEADER_LEN) % sizeof (float) == 0 &&
+          header.bytes[0] == bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_FLOAT, BSON_VECTOR_ELEMENT_32_BITS) &&
+          header.bytes[1] == bson_vector_header_byte_1 (0);
+}
+
+static BSON_INLINE bool
+bson_vector_packed_bit_validate (bson_vector_binary_header_impl_t header,
+                                 const uint8_t *binary_data,
+                                 uint32_t binary_data_len)
+{
+   if (header.bytes[0] == bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_UNSIGNED_INT, BSON_VECTOR_ELEMENT_1_BIT)) {
+      size_t padding = bson_vector_padding_from_header_byte_1 (header.bytes[1]);
+      if (header.bytes[1] != bson_vector_header_byte_1 (padding)) {
+         return false;
+      }
+      uint32_t vector_data_len = binary_data_len - BSON_VECTOR_HEADER_LEN;
+      if (vector_data_len == 0) {
+         return padding == 0;
+      } else {
+         // We need to read the last byte of the binary block to validate that unused bits are zero.
+         uint8_t last_data_byte = binary_data[binary_data_len - 1];
+         uint8_t mask_of_unused_bits = (uint8_t) ((1u << padding) - 1u);
+         return (last_data_byte & mask_of_unused_bits) == 0;
+      }
+   } else {
+      return false;
+   }
+}
+
+
+bool
+bson_vector_int8_view_init (bson_vector_int8_view_t *view_out, uint8_t *binary_data, uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_int8_validate (header)) {
+      if (view_out) {
+         *view_out = (bson_vector_int8_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_int8_const_view_init (bson_vector_int8_const_view_t *view_out,
+                                  const uint8_t *binary_data,
+                                  uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_int8_validate (header)) {
+      if (view_out) {
+         *view_out = (bson_vector_int8_const_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_float32_view_init (bson_vector_float32_view_t *view_out, uint8_t *binary_data, uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_float32_validate (header, binary_data_len)) {
+      if (view_out) {
+         *view_out = (bson_vector_float32_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_float32_const_view_init (bson_vector_float32_const_view_t *view_out,
+                                     const uint8_t *binary_data,
+                                     uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_float32_validate (header, binary_data_len)) {
+      if (view_out) {
+         *view_out = (bson_vector_float32_const_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_packed_bit_view_init (bson_vector_packed_bit_view_t *view_out,
+                                  uint8_t *binary_data,
+                                  uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_packed_bit_validate (header, binary_data, binary_data_len)) {
+      if (view_out) {
+         *view_out = (bson_vector_packed_bit_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_packed_bit_const_view_init (bson_vector_packed_bit_const_view_t *view_out,
+                                        const uint8_t *binary_data,
+                                        uint32_t binary_data_len)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (binary_data);
+   bson_vector_binary_header_impl_t header;
+   if (bson_vector_binary_header_impl_init (&header, binary_data, binary_data_len) &&
+       bson_vector_packed_bit_validate (header, binary_data, binary_data_len)) {
+      if (view_out) {
+         *view_out = (bson_vector_packed_bit_const_view_t){
+            .binary.data = binary_data, .binary.data_len = binary_data_len, .binary.header_copy = header};
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+bool
+bson_vector_int8_view_from_iter (bson_vector_int8_view_t *view_out, bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      uint32_t binary_len;
+      uint8_t *binary;
+      bson_iter_overwrite_binary (iter, BSON_SUBTYPE_VECTOR, &binary_len, &binary);
+      return binary && bson_vector_int8_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_int8_const_view_from_iter (bson_vector_int8_const_view_t *view_out, const bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      bson_subtype_t subtype;
+      uint32_t binary_len;
+      const uint8_t *binary;
+      bson_iter_binary (iter, &subtype, &binary_len, &binary);
+      return binary && subtype == BSON_SUBTYPE_VECTOR &&
+             bson_vector_int8_const_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_float32_view_from_iter (bson_vector_float32_view_t *view_out, bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      uint32_t binary_len;
+      uint8_t *binary;
+      bson_iter_overwrite_binary (iter, BSON_SUBTYPE_VECTOR, &binary_len, &binary);
+      return binary && bson_vector_float32_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_float32_const_view_from_iter (bson_vector_float32_const_view_t *view_out, const bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      bson_subtype_t subtype;
+      uint32_t binary_len;
+      const uint8_t *binary;
+      bson_iter_binary (iter, &subtype, &binary_len, &binary);
+      return binary && subtype == BSON_SUBTYPE_VECTOR &&
+             bson_vector_float32_const_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_packed_bit_view_from_iter (bson_vector_packed_bit_view_t *view_out, bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      uint32_t binary_len;
+      uint8_t *binary;
+      bson_iter_overwrite_binary (iter, BSON_SUBTYPE_VECTOR, &binary_len, &binary);
+      return binary && bson_vector_packed_bit_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_vector_packed_bit_const_view_from_iter (bson_vector_packed_bit_const_view_t *view_out, const bson_iter_t *iter)
+{
+   BSON_OPTIONAL_PARAM (view_out);
+   BSON_ASSERT_PARAM (iter);
+   if (BSON_ITER_HOLDS_BINARY (iter)) {
+      bson_subtype_t subtype;
+      uint32_t binary_len;
+      const uint8_t *binary;
+      bson_iter_binary (iter, &subtype, &binary_len, &binary);
+      return binary && subtype == BSON_SUBTYPE_VECTOR &&
+             bson_vector_packed_bit_const_view_init (view_out, binary, binary_len);
+   } else {
+      return false;
+   }
+}
+
+
+bool
+bson_append_vector_int8_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_int8_view_t *view_out)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (view_out);
+
+   uint32_t length = bson_vector_int8_binary_data_length (element_count);
+   if (length < BSON_VECTOR_HEADER_LEN) {
+      return false;
+   }
+   uint8_t *binary;
+   if (bson_append_binary_uninit (bson, key, key_length, BSON_SUBTYPE_VECTOR, &binary, length)) {
+      bson_vector_binary_header_impl_t header = {
+         .bytes[0] = bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_SIGNED_INT, BSON_VECTOR_ELEMENT_8_BITS),
+         .bytes[1] = bson_vector_header_byte_1 (0)};
+      memcpy (binary, header.bytes, BSON_VECTOR_HEADER_LEN);
+      *view_out =
+         (bson_vector_int8_view_t){.binary.data = binary, .binary.data_len = length, .binary.header_copy = header};
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_append_vector_float32_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_float32_view_t *view_out)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (view_out);
+
+   uint32_t length = bson_vector_float32_binary_data_length (element_count);
+   if (length < BSON_VECTOR_HEADER_LEN) {
+      return false;
+   }
+   uint8_t *binary;
+   if (bson_append_binary_uninit (bson, key, key_length, BSON_SUBTYPE_VECTOR, &binary, length)) {
+      bson_vector_binary_header_impl_t header = {
+         .bytes[0] = bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_FLOAT, BSON_VECTOR_ELEMENT_32_BITS),
+         .bytes[1] = bson_vector_header_byte_1 (0)};
+      memcpy (binary, header.bytes, BSON_VECTOR_HEADER_LEN);
+      *view_out =
+         (bson_vector_float32_view_t){.binary.data = binary, .binary.data_len = length, .binary.header_copy = header};
+      return true;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_append_vector_packed_bit_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_packed_bit_view_t *view_out)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (view_out);
+
+   uint32_t length = bson_vector_packed_bit_binary_data_length (element_count);
+   if (length < BSON_VECTOR_HEADER_LEN) {
+      return false;
+   }
+   uint8_t *binary;
+   if (bson_append_binary_uninit (bson, key, key_length, BSON_SUBTYPE_VECTOR, &binary, length)) {
+      size_t padding = (size_t) 7 & -element_count;
+      bson_vector_binary_header_impl_t header = {
+         .bytes[0] = bson_vector_header_byte_0 (BSON_VECTOR_ELEMENT_UNSIGNED_INT, BSON_VECTOR_ELEMENT_1_BIT),
+         .bytes[1] = bson_vector_header_byte_1 (padding)};
+      memcpy (binary, header.bytes, BSON_VECTOR_HEADER_LEN);
+      if (element_count > 0 && padding > 0) {
+         // We must explicitly zero bits in the final byte that aren't part of any element.
+         // No reason to read-modify-write here, it's better to write the whole byte.
+         binary[length - 1u] = 0u;
+      }
+      *view_out = (bson_vector_packed_bit_view_t){
+         .binary.data = binary, .binary.data_len = length, .binary.header_copy = header};
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static bool
+bson_vector_from_array_expect_key (const bson_iter_t *iter, uint32_t numeric_key, bson_error_t *error)
+{
+   char buffer[16];
+   const char *key;
+   bson_uint32_to_string (numeric_key, &key, buffer, sizeof buffer);
+   if (0 == strcmp (key, bson_iter_key (iter))) {
+      return true;
+   } else {
+      bson_set_error (error,
+                      BSON_ERROR_VECTOR,
+                      BSON_VECTOR_ERROR_ARRAY_KEY,
+                      "expected BSON array key '%s', found key '%s'",
+                      key,
+                      bson_iter_key (iter));
+      return false;
+   }
+}
+
+static void
+bson_vector_set_error_max_size (bson_error_t *error)
+{
+   bson_set_error (
+      error, BSON_ERROR_VECTOR, BSON_VECTOR_ERROR_MAX_SIZE, "maximum BSON document size would be exceeded");
+}
+
+bool
+bson_append_vector_int8_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   BSON_ASSERT_PARAM (iter);
+
+   uint32_t element_count = 0;
+   {
+      bson_iter_t validation_iter = *iter;
+      while (bson_iter_next (&validation_iter)) {
+         if (!bson_vector_from_array_expect_key (&validation_iter, element_count, error)) {
+            return false;
+         }
+         if (!BSON_ITER_HOLDS_INT (&validation_iter)) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE,
+                            "expected int32 or int64 in BSON array key '%s', found item type 0x%02X",
+                            bson_iter_key (&validation_iter),
+                            (unsigned) bson_iter_type (&validation_iter));
+            return false;
+         }
+         int64_t element_as_int64 = bson_iter_as_int64 (&validation_iter);
+         if (element_as_int64 < INT8_MIN || element_as_int64 > INT8_MAX) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE,
+                            "BSON array key '%s' value %" PRId64 " is out of range for vector of int8",
+                            bson_iter_key (&validation_iter),
+                            element_as_int64);
+            return false;
+         }
+         element_count++;
+      }
+   }
+
+   bson_vector_int8_view_t view;
+   if (!bson_append_vector_int8_uninit (bson, key, key_length, element_count, &view)) {
+      bson_vector_set_error_max_size (error);
+      return false;
+   }
+   bson_iter_t copy_iter = *iter;
+   for (uint32_t i = 0; i < element_count; i++) {
+      BSON_ASSERT (bson_iter_next (&copy_iter));
+      int8_t element = (int8_t) bson_iter_as_int64 (&copy_iter);
+      BSON_ASSERT (bson_vector_int8_view_write (view, &element, 1, i));
+   }
+   return true;
+}
+
+bool
+bson_append_vector_float32_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   BSON_ASSERT_PARAM (iter);
+
+   uint32_t element_count = 0;
+   {
+      bson_iter_t validation_iter = *iter;
+      while (bson_iter_next (&validation_iter)) {
+         if (!bson_vector_from_array_expect_key (&validation_iter, element_count, error)) {
+            return false;
+         }
+         if (!BSON_ITER_HOLDS_DOUBLE (&validation_iter)) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE,
+                            "expected 'double' number type in BSON array key '%s', found item type 0x%02X",
+                            bson_iter_key (&validation_iter),
+                            (unsigned) bson_iter_type (&validation_iter));
+            return false;
+         }
+         element_count++;
+      }
+   }
+
+   bson_vector_float32_view_t view;
+   if (!bson_append_vector_float32_uninit (bson, key, key_length, element_count, &view)) {
+      bson_vector_set_error_max_size (error);
+      return false;
+   }
+   bson_iter_t copy_iter = *iter;
+   for (uint32_t i = 0; i < element_count; i++) {
+      BSON_ASSERT (bson_iter_next (&copy_iter));
+      float element = (float) bson_iter_double (&copy_iter);
+      BSON_ASSERT (bson_vector_float32_view_write (view, &element, 1, i));
+   }
+   return true;
+}
+
+bool
+bson_append_vector_packed_bit_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   BSON_ASSERT_PARAM (iter);
+
+   uint32_t element_count = 0;
+   {
+      bson_iter_t validation_iter = *iter;
+      while (bson_iter_next (&validation_iter)) {
+         if (!bson_vector_from_array_expect_key (&validation_iter, element_count, error)) {
+            return false;
+         }
+         if (!BSON_ITER_HOLDS_INT (&validation_iter) && !BSON_ITER_HOLDS_BOOL (&validation_iter)) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE,
+                            "expected int32, int64, or bool in BSON array key '%s', found item type 0x%02X",
+                            bson_iter_key (&validation_iter),
+                            (unsigned) bson_iter_type (&validation_iter));
+            return false;
+         }
+         int64_t element_as_int64 = bson_iter_as_int64 (&validation_iter);
+         if (element_as_int64 < 0 || element_as_int64 > 1) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE,
+                            "BSON array key '%s' value %" PRId64 " is out of range for vector of packed_bit",
+                            bson_iter_key (&validation_iter),
+                            element_as_int64);
+            return false;
+         }
+         element_count++;
+      }
+   }
+
+   bson_vector_packed_bit_view_t view;
+   if (!bson_append_vector_packed_bit_uninit (bson, key, key_length, element_count, &view)) {
+      bson_vector_set_error_max_size (error);
+      return false;
+   }
+   bson_iter_t copy_iter = *iter;
+   for (uint32_t i = 0; i < element_count; i++) {
+      BSON_ASSERT (bson_iter_next (&copy_iter));
+      bool element_as_bool = (bool) bson_iter_as_int64 (&copy_iter);
+      BSON_ASSERT (bson_vector_packed_bit_view_pack_bool (view, &element_as_bool, 1, i));
+   }
+   return true;
+}
+
+
+bool
+bson_array_builder_append_vector_int8_elements (bson_array_builder_t *builder, bson_vector_int8_const_view_t view)
+{
+   BSON_ASSERT_PARAM (builder);
+   size_t length = bson_vector_int8_const_view_length (view);
+   for (size_t i = 0; i < length; i++) {
+      // Note, the zero initializer is only needed due to a false positive -Wmaybe-uninitialized warning in uncommon
+      // configurations where the compiler does not have visibility into memcpy().
+      int8_t element = 0;
+      BSON_ASSERT (bson_vector_int8_const_view_read (view, &element, 1, i));
+      if (!bson_array_builder_append_int32 (builder, (int32_t) element)) {
+         return false;
+      }
+   }
+   return true;
+}
+
+bool
+bson_array_builder_append_vector_float32_elements (bson_array_builder_t *builder, bson_vector_float32_const_view_t view)
+{
+   BSON_ASSERT_PARAM (builder);
+   size_t length = bson_vector_float32_const_view_length (view);
+   for (size_t i = 0; i < length; i++) {
+      float element;
+      BSON_ASSERT (bson_vector_float32_const_view_read (view, &element, 1, i));
+      if (!bson_array_builder_append_double (builder, (double) element)) {
+         return false;
+      }
+   }
+   return true;
+}
+
+bool
+bson_array_builder_append_vector_packed_bit_elements (bson_array_builder_t *builder,
+                                                      bson_vector_packed_bit_const_view_t view)
+{
+   BSON_ASSERT_PARAM (builder);
+   size_t length = bson_vector_packed_bit_const_view_length (view);
+   for (size_t i = 0; i < length; i++) {
+      bool element;
+      BSON_ASSERT (bson_vector_packed_bit_const_view_unpack_bool (view, &element, 1, i));
+      if (!bson_array_builder_append_int32 (builder, element ? 1 : 0)) {
+         return false;
+      }
+   }
+   return true;
+}
+
+
+bool
+bson_array_builder_append_vector_elements (bson_array_builder_t *builder, const bson_iter_t *iter)
+{
+   BSON_ASSERT_PARAM (builder);
+   BSON_ASSERT_PARAM (iter);
+   {
+      bson_vector_int8_const_view_t view;
+      if (bson_vector_int8_const_view_from_iter (&view, iter)) {
+         return bson_array_builder_append_vector_int8_elements (builder, view);
+      }
+   }
+   {
+      bson_vector_float32_const_view_t view;
+      if (bson_vector_float32_const_view_from_iter (&view, iter)) {
+         return bson_array_builder_append_vector_float32_elements (builder, view);
+      }
+   }
+   {
+      bson_vector_packed_bit_const_view_t view;
+      if (bson_vector_packed_bit_const_view_from_iter (&view, iter)) {
+         return bson_array_builder_append_vector_packed_bit_elements (builder, view);
+      }
+   }
+   return false;
+}
+
+
+bool
+bson_append_array_from_vector_int8 (bson_t *bson, const char *key, int key_length, bson_vector_int8_const_view_t view)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   bson_array_builder_t *child;
+   if (bson_append_array_builder_begin (bson, key, key_length, &child)) {
+      bool ok = bson_array_builder_append_vector_int8_elements (child, view);
+      return bson_append_array_builder_end (bson, child) && ok;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_append_array_from_vector_float32 (bson_t *bson,
+                                       const char *key,
+                                       int key_length,
+                                       bson_vector_float32_const_view_t view)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   bson_array_builder_t *child;
+   if (bson_append_array_builder_begin (bson, key, key_length, &child)) {
+      bool ok = bson_array_builder_append_vector_float32_elements (child, view);
+      return bson_append_array_builder_end (bson, child) && ok;
+   } else {
+      return false;
+   }
+}
+
+bool
+bson_append_array_from_vector_packed_bit (bson_t *bson,
+                                          const char *key,
+                                          int key_length,
+                                          bson_vector_packed_bit_const_view_t view)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   bson_array_builder_t *child;
+   if (bson_append_array_builder_begin (bson, key, key_length, &child)) {
+      bool ok = bson_array_builder_append_vector_packed_bit_elements (child, view);
+      return bson_append_array_builder_end (bson, child) && ok;
+   } else {
+      return false;
+   }
+}
+
+
+bool
+bson_append_array_from_vector (bson_t *bson, const char *key, int key_length, const bson_iter_t *iter)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   BSON_ASSERT_PARAM (iter);
+   bson_array_builder_t *child;
+   if (bson_append_array_builder_begin (bson, key, key_length, &child)) {
+      bool ok = bson_array_builder_append_vector_elements (child, iter);
+      return bson_append_array_builder_end (bson, child) && ok;
+   } else {
+      return false;
+   }
+}
diff -pruN 1.30.4-1/src/libbson/src/bson/bson-vector.h 2.0.2-1/src/libbson/src/bson/bson-vector.h
--- 1.30.4-1/src/libbson/src/bson/bson-vector.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson-vector.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,613 @@
+/*
+ * Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bson/bson-prelude.h>
+
+#ifndef BSON_VECTOR_H
+#define BSON_VECTOR_H
+
+#include <bson/bson-macros.h>
+#include <bson/bson-compat.h>
+#include <bson/bson-endian.h>
+
+BSON_BEGIN_DECLS
+
+
+// Length of the required header for BSON_SUBTYPE_VECTOR, in bytes
+#define BSON_VECTOR_HEADER_LEN 2
+
+// Forward declaration (typedef bson_array_builder_t in bson.h)
+struct _bson_array_builder_t;
+
+/** @brief Error codes for domain BSON_ERROR_VECTOR */
+typedef enum {
+   BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE = 1,
+   BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE,
+   BSON_VECTOR_ERROR_ARRAY_KEY,
+   BSON_VECTOR_ERROR_MAX_SIZE,
+} bson_vector_error_code_t;
+
+
+/** @brief Implementation detail. A copy of the BSON_SUBTYPE_VECTOR header, suitable for pass-by-value. */
+typedef struct bson_vector_binary_header_impl_t {
+   uint8_t bytes[BSON_VECTOR_HEADER_LEN];
+} bson_vector_binary_header_impl_t;
+
+/** @brief Implementation detail. A reference to non-owned const BSON Binary data of subtype BSON_SUBTYPE_VECTOR */
+typedef struct bson_vector_binary_const_view_impl_t {
+   const uint8_t *data;
+   uint32_t data_len;
+   bson_vector_binary_header_impl_t header_copy;
+} bson_vector_binary_const_view_impl_t;
+
+/** @brief Implementation detail. A reference to non-owned BSON Binary data of subtype BSON_SUBTYPE_VECTOR */
+typedef struct bson_vector_binary_view_impl_t {
+   uint8_t *data;
+   uint32_t data_len;
+   bson_vector_binary_header_impl_t header_copy;
+} bson_vector_binary_view_impl_t;
+
+/** @brief Implementation detail. Obtain a const reference from a non-const reference without re-validating. */
+static BSON_INLINE bson_vector_binary_const_view_impl_t
+bson_vector_binary_view_impl_as_const (bson_vector_binary_view_impl_t view)
+{
+   bson_vector_binary_const_view_impl_t result;
+   result.data = view.data;
+   result.data_len = view.data_len;
+   result.header_copy = view.header_copy;
+   return result;
+}
+
+
+/** @brief A reference to non-owned BSON Binary data holding a valid Vector of int8 element type */
+typedef struct bson_vector_int8_view_t {
+   bson_vector_binary_view_impl_t binary;
+} bson_vector_int8_view_t;
+
+/** @brief A reference to non-owned const BSON Binary data holding a valid Vector of int8 element type */
+typedef struct bson_vector_int8_const_view_t {
+   bson_vector_binary_const_view_impl_t binary;
+} bson_vector_int8_const_view_t;
+
+/** @brief A reference to non-owned BSON Binary data holding a valid Vector of float32 element type */
+typedef struct bson_vector_float32_view_t {
+   bson_vector_binary_view_impl_t binary;
+} bson_vector_float32_view_t;
+
+/** @brief A reference to non-owned const BSON Binary data holding a valid Vector of float32 element type */
+typedef struct bson_vector_float32_const_view_t {
+   bson_vector_binary_const_view_impl_t binary;
+} bson_vector_float32_const_view_t;
+
+/** @brief A reference to non-owned BSON Binary data holding a valid Vector of packed_bit */
+typedef struct bson_vector_packed_bit_view_t {
+   bson_vector_binary_view_impl_t binary;
+} bson_vector_packed_bit_view_t;
+
+/** @brief A reference to non-owned const BSON Binary data holding a valid Vector of packed_bit */
+typedef struct bson_vector_packed_bit_const_view_t {
+   bson_vector_binary_const_view_impl_t binary;
+} bson_vector_packed_bit_const_view_t;
+
+
+static BSON_INLINE bson_vector_int8_const_view_t
+bson_vector_int8_view_as_const (bson_vector_int8_view_t view)
+{
+   bson_vector_int8_const_view_t result;
+   result.binary = bson_vector_binary_view_impl_as_const (view.binary);
+   return result;
+}
+
+static BSON_INLINE bson_vector_float32_const_view_t
+bson_vector_float32_view_as_const (bson_vector_float32_view_t view)
+{
+   bson_vector_float32_const_view_t result;
+   result.binary = bson_vector_binary_view_impl_as_const (view.binary);
+   return result;
+}
+
+static BSON_INLINE bson_vector_packed_bit_const_view_t
+bson_vector_packed_bit_view_as_const (bson_vector_packed_bit_view_t view)
+{
+   bson_vector_packed_bit_const_view_t result;
+   result.binary = bson_vector_binary_view_impl_as_const (view.binary);
+   return result;
+}
+
+
+BSON_EXPORT (bool)
+bson_vector_int8_view_init (bson_vector_int8_view_t *view_out, uint8_t *binary_data, uint32_t binary_data_len);
+
+BSON_EXPORT (bool)
+bson_vector_int8_const_view_init (bson_vector_int8_const_view_t *view_out,
+                                  const uint8_t *binary_data,
+                                  uint32_t binary_data_len);
+
+BSON_EXPORT (bool)
+bson_vector_float32_view_init (bson_vector_float32_view_t *view_out, uint8_t *binary_data, uint32_t binary_data_len);
+
+
+BSON_EXPORT (bool)
+bson_vector_float32_const_view_init (bson_vector_float32_const_view_t *view_out,
+                                     const uint8_t *binary_data,
+                                     uint32_t binary_data_len);
+
+BSON_EXPORT (bool)
+bson_vector_packed_bit_view_init (bson_vector_packed_bit_view_t *view_out,
+                                  uint8_t *binary_data,
+                                  uint32_t binary_data_len);
+
+BSON_EXPORT (bool)
+bson_vector_packed_bit_const_view_init (bson_vector_packed_bit_const_view_t *view_out,
+                                        const uint8_t *binary_data,
+                                        uint32_t binary_data_len);
+
+
+BSON_EXPORT (bool)
+bson_vector_int8_view_from_iter (bson_vector_int8_view_t *view_out, bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_vector_int8_const_view_from_iter (bson_vector_int8_const_view_t *view_out, const bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_vector_float32_view_from_iter (bson_vector_float32_view_t *view_out, bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_vector_float32_const_view_from_iter (bson_vector_float32_const_view_t *view_out, const bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_vector_packed_bit_view_from_iter (bson_vector_packed_bit_view_t *view_out, bson_iter_t *iter);
+
+BSON_EXPORT (bool)
+bson_vector_packed_bit_const_view_from_iter (bson_vector_packed_bit_const_view_t *view_out, const bson_iter_t *iter);
+
+
+BSON_EXPORT (bool)
+bson_array_builder_append_vector_int8_elements (struct _bson_array_builder_t *builder,
+                                                bson_vector_int8_const_view_t view);
+
+BSON_EXPORT (bool)
+bson_array_builder_append_vector_float32_elements (struct _bson_array_builder_t *builder,
+                                                   bson_vector_float32_const_view_t view);
+
+BSON_EXPORT (bool)
+bson_array_builder_append_vector_packed_bit_elements (struct _bson_array_builder_t *builder,
+                                                      bson_vector_packed_bit_const_view_t view);
+
+BSON_EXPORT (bool)
+bson_array_builder_append_vector_elements (struct _bson_array_builder_t *builder, const bson_iter_t *iter);
+
+
+BSON_EXPORT (bool)
+bson_append_vector_int8_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_int8_view_t *view_out);
+
+#define BSON_APPEND_VECTOR_INT8_UNINIT(b, key, count, view) \
+   bson_append_vector_int8_uninit (b, key, (int) strlen (key), count, view)
+
+BSON_EXPORT (bool)
+bson_append_vector_float32_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_float32_view_t *view_out);
+
+#define BSON_APPEND_VECTOR_FLOAT32_UNINIT(b, key, count, view) \
+   bson_append_vector_float32_uninit (b, key, (int) strlen (key), count, view)
+
+BSON_EXPORT (bool)
+bson_append_vector_packed_bit_uninit (
+   bson_t *bson, const char *key, int key_length, size_t element_count, bson_vector_packed_bit_view_t *view_out);
+
+#define BSON_APPEND_VECTOR_PACKED_BIT_UNINIT(b, key, count, view) \
+   bson_append_vector_packed_bit_uninit (b, key, (int) strlen (key), count, view)
+
+
+BSON_EXPORT (bool)
+bson_append_vector_int8_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error);
+
+#define BSON_APPEND_VECTOR_INT8_FROM_ARRAY(b, key, iter, err) \
+   bson_append_vector_int8_from_array (b, key, (int) strlen (key), iter, err)
+
+BSON_EXPORT (bool)
+bson_append_vector_float32_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error);
+
+#define BSON_APPEND_VECTOR_FLOAT32_FROM_ARRAY(b, key, iter, err) \
+   bson_append_vector_float32_from_array (b, key, (int) strlen (key), iter, err)
+
+BSON_EXPORT (bool)
+bson_append_vector_packed_bit_from_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, bson_error_t *error);
+
+#define BSON_APPEND_VECTOR_PACKED_BIT_FROM_ARRAY(b, key, iter, err) \
+   bson_append_vector_packed_bit_from_array (b, key, (int) strlen (key), iter, err)
+
+
+BSON_EXPORT (bool)
+bson_append_array_from_vector_int8 (bson_t *bson, const char *key, int key_length, bson_vector_int8_const_view_t view);
+
+#define BSON_APPEND_ARRAY_FROM_VECTOR_INT8(b, key, view) \
+   bson_append_array_from_vector_int8 (b, key, (int) strlen (key), view)
+
+BSON_EXPORT (bool)
+bson_append_array_from_vector_float32 (bson_t *bson,
+                                       const char *key,
+                                       int key_length,
+                                       bson_vector_float32_const_view_t view);
+
+#define BSON_APPEND_ARRAY_FROM_VECTOR_FLOAT32(b, key, view) \
+   bson_append_array_from_vector_float32 (b, key, (int) strlen (key), view)
+
+BSON_EXPORT (bool)
+bson_append_array_from_vector_packed_bit (bson_t *bson,
+                                          const char *key,
+                                          int key_length,
+                                          bson_vector_packed_bit_const_view_t view);
+
+#define BSON_APPEND_ARRAY_FROM_VECTOR_PACKED_BIT(b, key, view) \
+   bson_append_array_from_vector_packed_bit (b, key, (int) strlen (key), view)
+
+
+static BSON_INLINE const int8_t *
+bson_vector_int8_const_view_pointer (bson_vector_int8_const_view_t view)
+{
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+   return (const int8_t *) (view.binary.data + BSON_VECTOR_HEADER_LEN);
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+}
+
+static BSON_INLINE int8_t *
+bson_vector_int8_view_pointer (bson_vector_int8_view_t view)
+{
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+   return (int8_t *) (view.binary.data + BSON_VECTOR_HEADER_LEN);
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+}
+
+
+static BSON_INLINE uint32_t
+bson_vector_int8_binary_data_length (size_t element_count)
+{
+   const size_t max_representable = (size_t) UINT32_MAX - (size_t) BSON_VECTOR_HEADER_LEN;
+   return element_count > max_representable ? 0u : (uint32_t) element_count + (uint32_t) BSON_VECTOR_HEADER_LEN;
+}
+
+static BSON_INLINE uint32_t
+bson_vector_float32_binary_data_length (size_t element_count)
+{
+   const size_t max_representable = ((size_t) UINT32_MAX - (size_t) BSON_VECTOR_HEADER_LEN) / sizeof (float);
+   return element_count > max_representable
+             ? 0u
+             : (uint32_t) element_count * sizeof (float) + (uint32_t) BSON_VECTOR_HEADER_LEN;
+}
+
+static BSON_INLINE uint32_t
+bson_vector_packed_bit_binary_data_length (size_t element_count)
+{
+   const size_t max_representable =
+      (size_t) BSON_MIN ((uint64_t) SIZE_MAX, ((uint64_t) UINT32_MAX - (uint64_t) BSON_VECTOR_HEADER_LEN) * 8u);
+   return element_count > max_representable
+             ? 0u
+             : (uint32_t) (((uint64_t) element_count + 7u) / 8u) + (uint32_t) BSON_VECTOR_HEADER_LEN;
+}
+
+
+static BSON_INLINE size_t
+bson_vector_int8_const_view_length (bson_vector_int8_const_view_t view)
+{
+   return view.binary.data_len - (uint32_t) BSON_VECTOR_HEADER_LEN;
+}
+
+static BSON_INLINE size_t
+bson_vector_int8_view_length (bson_vector_int8_view_t view)
+{
+   return bson_vector_int8_const_view_length (bson_vector_int8_view_as_const (view));
+}
+
+static BSON_INLINE size_t
+bson_vector_float32_const_view_length (bson_vector_float32_const_view_t view)
+{
+   return (view.binary.data_len - (uint32_t) BSON_VECTOR_HEADER_LEN) / (uint32_t) sizeof (float);
+}
+
+static BSON_INLINE size_t
+bson_vector_float32_view_length (bson_vector_float32_view_t view)
+{
+   return bson_vector_float32_const_view_length (bson_vector_float32_view_as_const (view));
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_const_view_length_bytes (bson_vector_packed_bit_const_view_t view)
+{
+   return view.binary.data_len - (uint32_t) BSON_VECTOR_HEADER_LEN;
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_view_length_bytes (bson_vector_packed_bit_view_t view)
+{
+   return bson_vector_packed_bit_const_view_length_bytes (bson_vector_packed_bit_view_as_const (view));
+}
+
+// Implementation detail, not part of documented API.
+static BSON_INLINE size_t
+bson_vector_padding_from_header_byte_1 (uint8_t byte_1)
+{
+   return byte_1 & 7;
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_const_view_padding (bson_vector_packed_bit_const_view_t view)
+{
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+   return bson_vector_padding_from_header_byte_1 (view.binary.header_copy.bytes[1]);
+   BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_view_padding (bson_vector_packed_bit_view_t view)
+{
+   return bson_vector_packed_bit_const_view_padding (bson_vector_packed_bit_view_as_const (view));
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_const_view_length (bson_vector_packed_bit_const_view_t view)
+{
+   return bson_vector_packed_bit_const_view_length_bytes (view) * 8u - bson_vector_packed_bit_const_view_padding (view);
+}
+
+static BSON_INLINE size_t
+bson_vector_packed_bit_view_length (bson_vector_packed_bit_view_t view)
+{
+   return bson_vector_packed_bit_const_view_length (bson_vector_packed_bit_view_as_const (view));
+}
+
+
+static BSON_INLINE bool
+bson_vector_int8_const_view_read (bson_vector_int8_const_view_t view,
+                                  int8_t *BSON_RESTRICT values_out,
+                                  size_t element_count,
+                                  size_t vector_offset_elements)
+{
+   size_t length = bson_vector_int8_const_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+      memcpy (values_out, bson_vector_int8_const_view_pointer (view) + vector_offset_elements, element_count);
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static BSON_INLINE bool
+bson_vector_int8_view_read (bson_vector_int8_view_t view,
+                            int8_t *BSON_RESTRICT values_out,
+                            size_t element_count,
+                            uint32_t vector_offset_elements)
+{
+   return bson_vector_int8_const_view_read (
+      bson_vector_int8_view_as_const (view), values_out, element_count, vector_offset_elements);
+}
+
+static BSON_INLINE bool
+bson_vector_int8_view_write (bson_vector_int8_view_t view,
+                             const int8_t *BSON_RESTRICT values,
+                             size_t element_count,
+                             size_t vector_offset_elements)
+{
+   size_t length = bson_vector_int8_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+      memcpy (bson_vector_int8_view_pointer (view) + vector_offset_elements, values, element_count);
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+BSON_STATIC_ASSERT2 (float_is_float32, sizeof (float) == 4);
+
+static BSON_INLINE bool
+bson_vector_float32_const_view_read (bson_vector_float32_const_view_t view,
+                                     float *BSON_RESTRICT values_out,
+                                     size_t element_count,
+                                     size_t vector_offset_elements)
+{
+   size_t length = bson_vector_float32_const_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      size_t byte_offset = BSON_VECTOR_HEADER_LEN + vector_offset_elements * 4;
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+#if BSON_BYTE_ORDER == BSON_LITTLE_ENDIAN
+      memcpy (values_out, view.binary.data + byte_offset, element_count * 4);
+#else
+      size_t i;
+      for (i = 0; i < element_count; i++) {
+         float aligned_tmp;
+         memcpy (&aligned_tmp, view.binary.data + byte_offset + i * 4, 4);
+         values_out[i] = BSON_FLOAT_FROM_LE (aligned_tmp);
+      }
+#endif
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static BSON_INLINE bool
+bson_vector_float32_view_read (bson_vector_float32_view_t view,
+                               float *BSON_RESTRICT values_out,
+                               size_t element_count,
+                               size_t vector_offset_elements)
+{
+   return bson_vector_float32_const_view_read (
+      bson_vector_float32_view_as_const (view), values_out, element_count, vector_offset_elements);
+}
+
+static BSON_INLINE bool
+bson_vector_float32_view_write (bson_vector_float32_view_t view,
+                                const float *BSON_RESTRICT values,
+                                size_t element_count,
+                                size_t vector_offset_elements)
+{
+   size_t length = bson_vector_float32_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      size_t byte_offset = BSON_VECTOR_HEADER_LEN + vector_offset_elements * 4;
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+#if BSON_BYTE_ORDER == BSON_LITTLE_ENDIAN
+      memcpy (view.binary.data + byte_offset, values, element_count * 4);
+#else
+      size_t i;
+      for (i = 0; i < element_count; i++) {
+         float aligned_tmp = BSON_FLOAT_TO_LE (values[i]);
+         memcpy (view.binary.data + byte_offset + i * 4, &aligned_tmp, 4);
+      }
+#endif
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+static BSON_INLINE bool
+bson_vector_packed_bit_const_view_read_packed (bson_vector_packed_bit_const_view_t view,
+                                               uint8_t *BSON_RESTRICT packed_values_out,
+                                               size_t byte_count,
+                                               size_t vector_offset_bytes)
+{
+   size_t length_bytes = bson_vector_packed_bit_const_view_length_bytes (view);
+   if (BSON_LIKELY (vector_offset_bytes <= length_bytes && byte_count <= length_bytes - vector_offset_bytes)) {
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+      memcpy (packed_values_out, view.binary.data + BSON_VECTOR_HEADER_LEN + vector_offset_bytes, byte_count);
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static BSON_INLINE bool
+bson_vector_packed_bit_view_read_packed (bson_vector_packed_bit_view_t view,
+                                         uint8_t *BSON_RESTRICT packed_values_out,
+                                         size_t byte_count,
+                                         size_t vector_offset_bytes)
+{
+   return bson_vector_packed_bit_const_view_read_packed (
+      bson_vector_packed_bit_view_as_const (view), packed_values_out, byte_count, vector_offset_bytes);
+}
+
+static BSON_INLINE bool
+bson_vector_packed_bit_view_write_packed (bson_vector_packed_bit_view_t view,
+                                          const uint8_t *BSON_RESTRICT packed_values,
+                                          size_t byte_count,
+                                          size_t vector_offset_bytes)
+{
+   size_t length_bytes = bson_vector_packed_bit_view_length_bytes (view);
+   if (BSON_LIKELY (vector_offset_bytes <= length_bytes && byte_count <= length_bytes - vector_offset_bytes)) {
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+      if (byte_count == length_bytes - vector_offset_bytes && byte_count >= 1u) {
+         // This write touches the last byte in the vector:
+         // special-case that byte so we can ensure unused bits remain set to zero.
+         size_t other_bytes = byte_count - 1u;
+         memcpy (view.binary.data + BSON_VECTOR_HEADER_LEN + vector_offset_bytes, packed_values, other_bytes);
+         view.binary.data[BSON_VECTOR_HEADER_LEN + vector_offset_bytes + other_bytes] =
+            (UINT8_C (0xFF) << bson_vector_packed_bit_view_padding (view)) & packed_values[other_bytes];
+      } else {
+         memcpy (view.binary.data + BSON_VECTOR_HEADER_LEN + vector_offset_bytes, packed_values, byte_count);
+      }
+      BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+static BSON_INLINE bool
+bson_vector_packed_bit_const_view_unpack_bool (bson_vector_packed_bit_const_view_t view,
+                                               bool *BSON_RESTRICT unpacked_values_out,
+                                               size_t element_count,
+                                               size_t vector_offset_elements)
+{
+   size_t length = bson_vector_packed_bit_const_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      size_t i;
+      for (i = 0; i < element_count; i++) {
+         size_t element_index = vector_offset_elements + i;
+         BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+         uint8_t packed_byte = view.binary.data[BSON_VECTOR_HEADER_LEN + (element_index >> 3)];
+         unpacked_values_out[i] = 0 != (packed_byte & ((uint8_t) 0x80 >> (element_index & 7)));
+         BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static BSON_INLINE bool
+bson_vector_packed_bit_view_unpack_bool (bson_vector_packed_bit_view_t view,
+                                         bool *BSON_RESTRICT unpacked_values_out,
+                                         size_t element_count,
+                                         size_t vector_offset_elements)
+{
+   return bson_vector_packed_bit_const_view_unpack_bool (
+      bson_vector_packed_bit_view_as_const (view), unpacked_values_out, element_count, vector_offset_elements);
+}
+
+static BSON_INLINE bool
+bson_vector_packed_bit_view_pack_bool (bson_vector_packed_bit_view_t view,
+                                       const bool *BSON_RESTRICT unpacked_values,
+                                       size_t element_count,
+                                       size_t vector_offset_elements)
+{
+   size_t length = bson_vector_packed_bit_view_length (view);
+   if (BSON_LIKELY (vector_offset_elements <= length && element_count <= length - vector_offset_elements)) {
+      while (element_count > 0) {
+         BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_BEGIN
+         uint8_t *BSON_RESTRICT packed_byte = BSON_VECTOR_HEADER_LEN + (vector_offset_elements >> 3) + view.binary.data;
+         if (element_count >= 8 && (vector_offset_elements & 7) == 0) {
+            uint8_t complete_byte = 0;
+            unsigned i;
+            for (i = 0; i < 8; i++) {
+               complete_byte |= unpacked_values[i] ? ((uint8_t) 0x80 >> i) : 0;
+            }
+            *packed_byte = complete_byte;
+            unpacked_values += 8;
+            vector_offset_elements += 8;
+            element_count -= 8;
+         } else {
+            uint8_t mask = (uint8_t) 0x80 >> (vector_offset_elements & 7);
+            *packed_byte = (*packed_byte & ~mask) | (*unpacked_values ? mask : 0);
+            unpacked_values++;
+            vector_offset_elements++;
+            element_count--;
+         }
+         BSON_DISABLE_UNSAFE_BUFFER_USAGE_WARNING_END
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+BSON_END_DECLS
+
+#endif /* BSON_VECTOR_H */
diff -pruN 1.30.4-1/src/libbson/src/bson/bson.c 2.0.2-1/src/libbson/src/bson/bson.c
--- 1.30.4-1/src/libbson/src/bson/bson.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,8 @@
  */
 
 
+#include <bson/validate-private.h>
+#include <mlib/intencode.h>
 #include <bson/bson.h>
 #include <bson/bson-config.h>
 #include <bson/bson-private.h>
@@ -23,39 +25,10 @@
 #include <common-json-private.h>
 #include <common-macros-private.h>
 #include <bson/bson-iso8601-private.h>
-#include <common-cmp-private.h>
 
 #include <string.h>
 #include <math.h>
 
-#ifdef BSON_MEMCHECK
-#pragma message( \
-   "Do not define BSON_MEMCHECK. BSON_MEMCHECK changes the data layout of bson_t. BSON_MEMCHECK is deprecated may be removed in a future major release")
-#endif
-
-
-typedef enum {
-   BSON_VALIDATE_PHASE_START,
-   BSON_VALIDATE_PHASE_TOP,
-   BSON_VALIDATE_PHASE_LF_REF_KEY,
-   BSON_VALIDATE_PHASE_LF_REF_UTF8,
-   BSON_VALIDATE_PHASE_LF_ID_KEY,
-   BSON_VALIDATE_PHASE_LF_DB_KEY,
-   BSON_VALIDATE_PHASE_LF_DB_UTF8,
-   BSON_VALIDATE_PHASE_NOT_DBREF,
-} bson_validate_phase_t;
-
-
-/*
- * Structures.
- */
-typedef struct {
-   bson_validate_flags_t flags;
-   ssize_t err_offset;
-   bson_validate_phase_t phase;
-   bson_error_t error;
-} bson_validate_state_t;
-
 
 /*
  * Globals.
@@ -131,9 +104,6 @@ _bson_impl_inline_grow (bson_impl_inline
       data = bson_malloc (req);
 
       memcpy (data, impl->data, impl->len);
-#ifdef BSON_MEMCHECK
-      bson_free (impl->canary);
-#endif
       alloc->flags &= ~BSON_FLAG_INLINE;
       alloc->parent = NULL;
       alloc->depth = 0;
@@ -289,17 +259,12 @@ _bson_data (const bson_t *bson) /* IN */
 static BSON_INLINE void
 _bson_encode_length (bson_t *bson) /* IN */
 {
-#if BSON_BYTE_ORDER == BSON_LITTLE_ENDIAN
-   memcpy (_bson_data (bson), &bson->len, sizeof (bson->len));
-#else
-   uint32_t length_le = BSON_UINT32_TO_LE (bson->len);
-   memcpy (_bson_data (bson), &length_le, sizeof (length_le));
-#endif
+   mlib_write_u32le (_bson_data (bson), bson->len);
 }
 
 
 typedef struct _bson_append_bytes_arg {
-   const uint8_t *bytes; // Not null.
+   const uint8_t *bytes; // Optional.
    uint32_t length;      // > 0.
 } _bson_append_bytes_arg;
 
@@ -370,7 +335,9 @@ BSON_STATIC_ASSERT2 (max_alloc_grow_fits
    } else {                                                                                   \
       uint8_t *data = _bson_data ((_bson)) + ((_bson)->len - 1u);                             \
       for (const _bson_append_bytes_arg *arg = (_list).args; arg != (_list).current; ++arg) { \
-         memcpy (data, arg->bytes, arg->length);                                              \
+         if (arg->bytes) {                                                                    \
+            memcpy (data, arg->bytes, arg->length);                                           \
+         }                                                                                    \
          (_bson)->len += arg->length;                                                         \
          data += arg->length;                                                                 \
       }                                                                                       \
@@ -745,16 +712,15 @@ append_failure:
 /*
  *--------------------------------------------------------------------------
  *
- * bson_append_binary --
+ * _bson_append_binary --
  *
- *       Append binary data to @bson. The field will have the
- *       BSON_TYPE_BINARY type.
+ *       Append a BSON_TYPE_BINARY field, optionally copying @binary into the field.
  *
  * Parameters:
  *       @subtype: the BSON Binary Subtype. See bsonspec.org for more
  *                 information.
- *       @binary: a pointer to the raw binary data.
- *       @length: the size of @binary in bytes.
+ *       @binary: Optional pointer to the raw binary data.
+ *       @length: the size of the field's binary data in bytes.
  *
  * Returns:
  *       true if successful; otherwise false.
@@ -765,22 +731,19 @@ append_failure:
  *--------------------------------------------------------------------------
  */
 
-bool
-bson_append_binary (bson_t *bson,           /* IN */
-                    const char *key,        /* IN */
-                    int key_length,         /* IN */
-                    bson_subtype_t subtype, /* IN */
-                    const uint8_t *binary,  /* IN */
-                    uint32_t length)        /* IN */
+static bool
+_bson_append_binary (bson_t *bson,           /* IN */
+                     const char *key,        /* IN */
+                     int key_length,         /* IN */
+                     bson_subtype_t subtype, /* IN */
+                     const uint8_t *binary,  /* IN */
+                     uint32_t length)        /* IN */
 {
    static const uint8_t type = BSON_TYPE_BINARY;
 
    BSON_ASSERT_PARAM (bson);
    BSON_ASSERT_PARAM (key);
-
-   if (!binary && length > 0u) {
-      return false;
-   }
+   BSON_OPTIONAL_PARAM (binary);
 
    BSON_APPEND_BYTES_LIST_DECLARE (args);
 
@@ -824,6 +787,87 @@ append_failure:
 /*
  *--------------------------------------------------------------------------
  *
+ * bson_append_binary --
+ *
+ *       Append binary data to @bson. The field will have the
+ *       BSON_TYPE_BINARY type.
+ *
+ * Parameters:
+ *       @subtype: the BSON Binary Subtype. See bsonspec.org for more
+ *                 information.
+ *       @binary: a pointer to the raw binary data.
+ *       @length: the size of @binary in bytes.
+ *
+ * Returns:
+ *       true if successful; otherwise false.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+bool
+bson_append_binary (bson_t *bson,           /* IN */
+                    const char *key,        /* IN */
+                    int key_length,         /* IN */
+                    bson_subtype_t subtype, /* IN */
+                    const uint8_t *binary,  /* IN */
+                    uint32_t length)        /* IN */
+{
+   if (!binary && length > 0u) {
+      return false;
+   }
+   return _bson_append_binary (bson, key, key_length, subtype, binary, length);
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
+ * bson_append_binary_uninit --
+ *
+ *       Append binary data to @bson by framing an uninitialized field to be written by the caller.
+ *       The field will have the BSON_TYPE_BINARY type. On success, the caller MUST write to all
+ *       bytes in the binary data field. The returned `*binary` pointer may be invalidated by
+ *       subsequent modifications to @bson.
+ *
+ * Parameters:
+ *       @subtype: the BSON Binary Subtype. See bsonspec.org for more
+ *                 information.
+ *       @binary: Output parameter for a temporary pointer where the binary item's contents must be written.
+ *       @length: the size of @binary in bytes.
+ *
+ * Returns:
+ *       true if successful; otherwise false.
+ *
+ * Side effects:
+ *       None.
+ *
+ *--------------------------------------------------------------------------
+ */
+
+bool
+bson_append_binary_uninit (bson_t *bson,           /* IN */
+                           const char *key,        /* IN */
+                           int key_length,         /* IN */
+                           bson_subtype_t subtype, /* IN */
+                           uint8_t **binary,       /* IN */
+                           uint32_t length)        /* IN */
+{
+   BSON_ASSERT_PARAM (binary);
+   if (_bson_append_binary (bson, key, key_length, subtype, NULL, length)) {
+      *binary = _bson_data (bson) + bson->len - 1u - length;
+      return true;
+   } else {
+      return false;
+   }
+}
+
+
+/*
+ *--------------------------------------------------------------------------
+ *
  * bson_append_bool --
  *
  *       Append a new field to @bson with the name @key. The value is
@@ -1823,9 +1867,6 @@ bson_init (bson_t *bson)
 
    BSON_ASSERT (bson);
 
-#ifdef BSON_MEMCHECK
-   impl->canary = bson_malloc (1);
-#endif
    impl->flags = BSON_FLAG_INLINE | BSON_FLAG_STATIC;
    impl->len = 5;
    impl->data[0] = 5;
@@ -1859,7 +1900,6 @@ bool
 bson_init_static (bson_t *bson, const uint8_t *data, size_t length)
 {
    bson_impl_alloc_t *impl = (bson_impl_alloc_t *) bson;
-   uint32_t len_le;
 
    BSON_ASSERT (bson);
    BSON_ASSERT (data);
@@ -1868,9 +1908,9 @@ bson_init_static (bson_t *bson, const ui
       return false;
    }
 
-   memcpy (&len_le, data, sizeof (len_le));
+   const uint32_t hdr_len = mlib_read_u32le (data);
 
-   if ((size_t) BSON_UINT32_FROM_LE (len_le) != length) {
+   if (hdr_len != length) {
       return false;
    }
 
@@ -1905,9 +1945,6 @@ bson_new (void)
    impl = (bson_impl_inline_t *) bson;
    impl->flags = BSON_FLAG_INLINE;
    impl->len = 5;
-#ifdef BSON_MEMCHECK
-   impl->canary = bson_malloc (1);
-#endif
    impl->data[0] = 5;
    impl->data[1] = 0;
    impl->data[2] = 0;
@@ -1960,22 +1997,21 @@ bson_sized_new (size_t size)
 bson_t *
 bson_new_from_data (const uint8_t *data, size_t length)
 {
-   uint32_t len_le;
-   bson_t *bson;
-
    BSON_ASSERT (data);
 
    if ((length < 5) || (length > BSON_MAX_SIZE) || data[length - 1]) {
+      // Invalid length, or not null-terminated
       return NULL;
    }
 
-   memcpy (&len_le, data, sizeof (len_le));
+   const int32_t hdr = mlib_read_i32le (data);
 
-   if (length != (size_t) BSON_UINT32_FROM_LE (len_le)) {
+   if (mlib_cmp (hdr, !=, length)) {
+      // Header's declared length is not equal to the length of the data buffer we were given
       return NULL;
    }
 
-   bson = bson_sized_new (length);
+   bson_t *const bson = bson_sized_new (length);
    memcpy (_bson_data (bson), data, length);
    bson->len = (uint32_t) length;
 
@@ -1987,7 +2023,6 @@ bson_t *
 bson_new_from_buffer (uint8_t **buf, size_t *buf_len, bson_realloc_func realloc_func, void *realloc_func_ctx)
 {
    bson_impl_alloc_t *impl;
-   uint32_t len_le;
    uint32_t length;
    bson_t *bson;
 
@@ -2003,20 +2038,17 @@ bson_new_from_buffer (uint8_t **buf, siz
 
    if (!*buf) {
       length = 5;
-      len_le = BSON_UINT32_TO_LE (length);
       *buf_len = 5;
       *buf = realloc_func (*buf, *buf_len, realloc_func_ctx);
-      memcpy (*buf, &len_le, sizeof (len_le));
+      mlib_write_u32le (*buf, length);
       (*buf)[4] = '\0';
    } else {
       if ((*buf_len < 5) || (*buf_len > BSON_MAX_SIZE)) {
          bson_free (bson);
          return NULL;
       }
-
-      memcpy (&len_le, *buf, sizeof (len_le));
-      length = BSON_UINT32_FROM_LE (len_le);
-      if ((size_t) length > *buf_len) {
+      length = mlib_read_u32le (*buf);
+      if (length > *buf_len) {
          bson_free (bson);
          return NULL;
       }
@@ -2061,13 +2093,7 @@ bson_copy_to (const bson_t *src, bson_t
    BSON_ASSERT (dst);
 
    if ((src->flags & BSON_FLAG_INLINE)) {
-#ifdef BSON_MEMCHECK
-      dst->len = src->len;
-      dst->canary = bson_malloc (1);
-      memcpy (dst->padding, src->padding, sizeof dst->padding);
-#else
       memcpy (dst, src, sizeof *dst);
-#endif
       dst->flags = (BSON_FLAG_STATIC | BSON_FLAG_INLINE);
       return;
    }
@@ -2137,22 +2163,6 @@ bson_copy_to_excluding_noinit_va (const
 
 
 void
-bson_copy_to_excluding (const bson_t *src, bson_t *dst, const char *first_exclude, ...)
-{
-   va_list args;
-
-   BSON_ASSERT (src);
-   BSON_ASSERT (dst);
-   BSON_ASSERT (first_exclude);
-
-   bson_init (dst);
-
-   va_start (args, first_exclude);
-   bson_copy_to_excluding_noinit_va (src, dst, first_exclude, args);
-   va_end (args);
-}
-
-void
 bson_copy_to_excluding_noinit (const bson_t *src, bson_t *dst, const char *first_exclude, ...)
 {
    va_list args;
@@ -2177,12 +2187,6 @@ bson_destroy (bson_t *bson)
       bson_free (*((bson_impl_alloc_t *) bson)->buf);
    }
 
-#ifdef BSON_MEMCHECK
-   if (bson->flags & BSON_FLAG_INLINE) {
-      bson_free (bson->canary);
-   }
-#endif
-
    if (!(bson->flags & BSON_FLAG_STATIC)) {
       bson_free (bson);
    }
@@ -2249,13 +2253,7 @@ bson_steal (bson_t *dst, bson_t *src)
 
       /* for consistency, src is always invalid after steal, even if inline */
       src->len = 0;
-#ifdef BSON_MEMCHECK
-      bson_free (src->canary);
-#endif
    } else {
-#ifdef BSON_MEMCHECK
-      bson_free (dst->canary);
-#endif
       memcpy (dst, src, sizeof (bson_t));
       alloc = (bson_impl_alloc_t *) dst;
       alloc->flags |= BSON_FLAG_STATIC;
@@ -2438,12 +2436,6 @@ bson_as_canonical_extended_json (const b
 
 
 char *
-bson_as_json (const bson_t *bson, size_t *length)
-{
-   return bson_as_legacy_extended_json (bson, length);
-}
-
-char *
 bson_as_legacy_extended_json (const bson_t *bson, size_t *length)
 {
    const bson_json_opts_t opts = {BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, false};
@@ -2460,12 +2452,6 @@ bson_as_relaxed_extended_json (const bso
 
 
 char *
-bson_array_as_json (const bson_t *bson, size_t *length)
-{
-   return bson_array_as_legacy_extended_json (bson, length);
-}
-
-char *
 bson_array_as_legacy_extended_json (const bson_t *bson, size_t *length)
 {
    const bson_json_opts_t opts = {BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, true};
@@ -2489,196 +2475,6 @@ bson_array_as_canonical_extended_json (c
 }
 
 
-#define VALIDATION_ERR(_flag, _msg, ...) bson_set_error (&state->error, BSON_ERROR_INVALID, _flag, _msg, __VA_ARGS__)
-
-static bool
-_bson_iter_validate_utf8 (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data)
-{
-   bson_validate_state_t *state = data;
-   bool allow_null;
-
-   if ((state->flags & BSON_VALIDATE_UTF8)) {
-      allow_null = !!(state->flags & BSON_VALIDATE_UTF8_ALLOW_NULL);
-
-      if (!bson_utf8_validate (v_utf8, v_utf8_len, allow_null)) {
-         state->err_offset = iter->off;
-         VALIDATION_ERR (BSON_VALIDATE_UTF8, "invalid utf8 string for key \"%s\"", key);
-         return true;
-      }
-   }
-
-   if ((state->flags & BSON_VALIDATE_DOLLAR_KEYS)) {
-      if (state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8) {
-         state->phase = BSON_VALIDATE_PHASE_LF_ID_KEY;
-      } else if (state->phase == BSON_VALIDATE_PHASE_LF_DB_UTF8) {
-         state->phase = BSON_VALIDATE_PHASE_NOT_DBREF;
-      }
-   }
-
-   return false;
-}
-
-
-static void
-_bson_iter_validate_corrupt (const bson_iter_t *iter, void *data)
-{
-   bson_validate_state_t *state = data;
-
-   state->err_offset = iter->err_off;
-   VALIDATION_ERR (BSON_VALIDATE_NONE, "%s", "corrupt BSON");
-}
-
-
-static bool
-_bson_iter_validate_before (const bson_iter_t *iter, const char *key, void *data)
-{
-   bson_validate_state_t *state = data;
-
-   if ((state->flags & BSON_VALIDATE_EMPTY_KEYS)) {
-      if (key[0] == '\0') {
-         state->err_offset = iter->off;
-         VALIDATION_ERR (BSON_VALIDATE_EMPTY_KEYS, "%s", "empty key");
-         return true;
-      }
-   }
-
-   if ((state->flags & BSON_VALIDATE_DOLLAR_KEYS)) {
-      if (key[0] == '$') {
-         if (state->phase == BSON_VALIDATE_PHASE_LF_REF_KEY && strcmp (key, "$ref") == 0) {
-            state->phase = BSON_VALIDATE_PHASE_LF_REF_UTF8;
-         } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY && strcmp (key, "$id") == 0) {
-            state->phase = BSON_VALIDATE_PHASE_LF_DB_KEY;
-         } else if (state->phase == BSON_VALIDATE_PHASE_LF_DB_KEY && strcmp (key, "$db") == 0) {
-            state->phase = BSON_VALIDATE_PHASE_LF_DB_UTF8;
-         } else {
-            state->err_offset = iter->off;
-            VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"%s\"", key);
-            return true;
-         }
-      } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 ||
-                 state->phase == BSON_VALIDATE_PHASE_LF_DB_UTF8) {
-         state->err_offset = iter->off;
-         VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, "invalid key within DBRef subdocument: \"%s\"", key);
-         return true;
-      } else {
-         state->phase = BSON_VALIDATE_PHASE_NOT_DBREF;
-      }
-   }
-
-   if ((state->flags & BSON_VALIDATE_DOT_KEYS)) {
-      if (strstr (key, ".")) {
-         state->err_offset = iter->off;
-         VALIDATION_ERR (BSON_VALIDATE_DOT_KEYS, "keys cannot contain \".\": \"%s\"", key);
-         return true;
-      }
-   }
-
-   return false;
-}
-
-
-static bool
-_bson_iter_validate_codewscope (
-   const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, const bson_t *v_scope, void *data)
-{
-   bson_validate_state_t *state = data;
-   size_t offset = 0;
-
-   BSON_UNUSED (key);
-   BSON_UNUSED (v_code_len);
-   BSON_UNUSED (v_code);
-
-   if (!bson_validate (v_scope, state->flags, &offset)) {
-      state->err_offset = iter->off + offset;
-      VALIDATION_ERR (BSON_VALIDATE_NONE, "%s", "corrupt code-with-scope");
-      return false;
-   }
-
-   return true;
-}
-
-
-static bool
-_bson_iter_validate_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data);
-
-
-static const bson_visitor_t bson_validate_funcs = {
-   _bson_iter_validate_before,
-   NULL, /* visit_after */
-   _bson_iter_validate_corrupt,
-   NULL, /* visit_double */
-   _bson_iter_validate_utf8,
-   _bson_iter_validate_document,
-   _bson_iter_validate_document, /* visit_array */
-   NULL,                         /* visit_binary */
-   NULL,                         /* visit_undefined */
-   NULL,                         /* visit_oid */
-   NULL,                         /* visit_bool */
-   NULL,                         /* visit_date_time */
-   NULL,                         /* visit_null */
-   NULL,                         /* visit_regex */
-   NULL,                         /* visit_dbpoint */
-   NULL,                         /* visit_code */
-   NULL,                         /* visit_symbol */
-   _bson_iter_validate_codewscope,
-};
-
-
-static bool
-_bson_iter_validate_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data)
-{
-   bson_validate_state_t *state = data;
-   bson_iter_t child;
-   bson_validate_phase_t phase = state->phase;
-
-   BSON_UNUSED (key);
-
-   if (!bson_iter_init (&child, v_document)) {
-      state->err_offset = iter->off;
-      return true;
-   }
-
-   if (state->phase == BSON_VALIDATE_PHASE_START) {
-      state->phase = BSON_VALIDATE_PHASE_TOP;
-   } else {
-      state->phase = BSON_VALIDATE_PHASE_LF_REF_KEY;
-   }
-
-   (void) bson_iter_visit_all (&child, &bson_validate_funcs, state);
-
-   if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 ||
-       state->phase == BSON_VALIDATE_PHASE_LF_DB_UTF8) {
-      if (state->err_offset <= 0) {
-         state->err_offset = iter->off;
-      }
-
-      return true;
-   }
-
-   state->phase = phase;
-
-   return false;
-}
-
-
-static void
-_bson_validate_internal (const bson_t *bson, bson_validate_state_t *state)
-{
-   bson_iter_t iter;
-
-   state->err_offset = -1;
-   state->phase = BSON_VALIDATE_PHASE_START;
-   memset (&state->error, 0, sizeof state->error);
-
-   if (!bson_iter_init (&iter, bson)) {
-      state->err_offset = 0;
-      VALIDATION_ERR (BSON_VALIDATE_NONE, "%s", "corrupt BSON");
-   } else {
-      _bson_iter_validate_document (&iter, NULL, bson, state);
-   }
-}
-
-
 bool
 bson_validate (const bson_t *bson, bson_validate_flags_t flags, size_t *offset)
 {
@@ -2692,29 +2488,26 @@ bson_validate_with_error (const bson_t *
    return bson_validate_with_error_and_offset (bson, flags, NULL, error);
 }
 
-
 bool
 bson_validate_with_error_and_offset (const bson_t *bson,
                                      bson_validate_flags_t flags,
                                      size_t *offset,
                                      bson_error_t *error)
 {
-   bson_validate_state_t state;
-
-   state.flags = flags;
-   _bson_validate_internal (bson, &state);
+   BSON_ASSERT_PARAM (bson);
+   BSON_OPTIONAL_PARAM (offset);
+   BSON_OPTIONAL_PARAM (error);
 
-   if (state.err_offset >= 0) {
-      if (offset) {
-         *offset = (size_t) state.err_offset;
-      }
-      if (error) {
-         memcpy (error, &state.error, sizeof *error);
-      }
-      return false;
+   size_t offset_local = 0;
+   if (!offset) {
+      offset = &offset_local;
+   }
+   bson_error_t error_local;
+   if (!error) {
+      error = &error_local;
    }
 
-   return true;
+   return _bson_validate_impl_v2 (bson, flags, offset, error);
 }
 
 
@@ -2795,6 +2588,7 @@ bson_array_builder_append_value (bson_ar
    bson_array_builder_append_impl (bson_append_value, value);
 }
 
+
 bool
 bson_array_builder_append_array (bson_array_builder_t *bab, const bson_t *array)
 {
@@ -2803,6 +2597,13 @@ bson_array_builder_append_array (bson_ar
 
 
 bool
+bson_array_builder_append_array_from_vector (bson_array_builder_t *bab, const bson_iter_t *iter)
+{
+   bson_array_builder_append_impl (bson_append_array_from_vector, iter);
+}
+
+
+bool
 bson_array_builder_append_binary (bson_array_builder_t *bab,
                                   bson_subtype_t subtype,
                                   const uint8_t *binary,
@@ -2812,6 +2613,16 @@ bson_array_builder_append_binary (bson_a
 }
 
 
+bool
+bson_array_builder_append_binary_uninit (bson_array_builder_t *bab,
+                                         bson_subtype_t subtype,
+                                         uint8_t **binary,
+                                         uint32_t length)
+{
+   bson_array_builder_append_impl (bson_append_binary_uninit, subtype, binary, length);
+}
+
+
 bool
 bson_array_builder_append_bool (bson_array_builder_t *bab, bool value)
 {
diff -pruN 1.30.4-1/src/libbson/src/bson/bson.h 2.0.2-1/src/libbson/src/bson/bson.h
--- 1.30.4-1/src/libbson/src/bson/bson.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/bson.h	2025-06-19 15:42:22.000000000 +0000
@@ -27,8 +27,6 @@
 
 #include <bson/bson-macros.h>
 #include <bson/bson-config.h>
-#include <bson/bson-atomic.h> // Deprecated.
-#include <bson/bson-cmp.h>    // Deprecated.
 #include <bson/bson-context.h>
 #include <bson/bson-clock.h>
 #include <bson/bson-decimal128.h>
@@ -36,7 +34,6 @@
 #include <bson/bson-iter.h>
 #include <bson/bson-json.h>
 #include <bson/bson-keys.h>
-#include <bson/bson-md5.h>
 #include <bson/bson-memory.h>
 #include <bson/bson-oid.h>
 #include <bson/bson-reader.h>
@@ -44,6 +41,7 @@
 #include <bson/bson-types.h>
 #include <bson/bson-utf8.h>
 #include <bson/bson-value.h>
+#include <bson/bson-vector.h>
 #include <bson/bson-version.h>
 #include <bson/bson-version-functions.h>
 #include <bson/bson-writer.h>
@@ -290,31 +288,13 @@ bson_copy (const bson_t *bson);
 BSON_EXPORT (void)
 bson_copy_to (const bson_t *src, bson_t *dst);
 
-
-/**
- * bson_copy_to_excluding:
- * @src: A bson_t.
- * @dst: A bson_t to initialize and copy into.
- * @first_exclude: First field name to exclude.
- *
- * Copies @src into @dst excluding any field that is provided.
- * This is handy for situations when you need to remove one or
- * more fields in a bson_t. Note that bson_init() will be called
- * on dst.
- */
-BSON_EXPORT (void)
-bson_copy_to_excluding (const bson_t *src, bson_t *dst, const char *first_exclude, ...) BSON_GNUC_NULL_TERMINATED
-   BSON_GNUC_DEPRECATED_FOR (bson_copy_to_excluding_noinit);
-
 /**
  * bson_copy_to_excluding_noinit:
  * @src: A bson_t.
  * @dst: A bson_t to initialize and copy into.
  * @first_exclude: First field name to exclude.
  *
- * The same as bson_copy_to_excluding, but does not call bson_init()
- * on the dst. This version should be preferred in new code, but the
- * old function is left for backwards compatibility.
+ * Does not call bson_init() on the dst.
  */
 BSON_EXPORT (void)
 bson_copy_to_excluding_noinit (const bson_t *src, bson_t *dst, const char *first_exclude, ...)
@@ -519,7 +499,7 @@ bson_as_canonical_extended_json (const b
 
 
 /**
- * bson_as_json:
+ * bson_as_legacy_extended_json:
  * @bson: A bson_t.
  * @length: A location for the string length, or NULL.
  *
@@ -531,10 +511,7 @@ bson_as_canonical_extended_json (const b
  *
  * Returns: A newly allocated string that should be freed with bson_free().
  */
-BSON_EXPORT (char *)
-bson_as_json (const bson_t *bson, size_t *length) BSON_GNUC_DEPRECATED_FOR (bson_as_legacy_extended_json);
 
-// `bson_as_legacy_extended_json` is a non-deprecated form of `bson_as_json`.
 BSON_EXPORT (char *)
 bson_as_legacy_extended_json (const bson_t *bson, size_t *length);
 
@@ -561,11 +538,7 @@ BSON_EXPORT (char *)
 bson_as_relaxed_extended_json (const bson_t *bson, size_t *length);
 
 
-/* like bson_as_json() but for outermost arrays. */
-BSON_EXPORT (char *)
-bson_array_as_json (const bson_t *bson, size_t *length) BSON_GNUC_DEPRECATED_FOR (bson_array_as_legacy_extended_json);
-
-// `bson_array_as_legacy_extended_json` is a non-deprecated form of `bson_array_as_json`.
+/* like bson_as_legacy_extended_json() but for outermost arrays. */
 BSON_EXPORT (char *)
 bson_array_as_legacy_extended_json (const bson_t *bson, size_t *length);
 
@@ -626,10 +599,30 @@ BSON_EXPORT (bool)
 bson_array_builder_append_array (bson_array_builder_t *bab, const bson_t *array);
 
 /**
+ * bson_append_array_from_vector:
+ * @bson: A bson_t that will be modified.
+ * @key: The key for the field.
+ * @iter: A bson_iter_t pointing to any supported vector in another bson_t.
+ *
+ * If @iter points to a supported vector type, converts the vector to a BSON array appended to @bson.
+ *
+ * Returns: true if successful; false if append would overflow max size or @iter does not point to a vector in a
+ * supported format.
+ */
+BSON_EXPORT (bool)
+bson_append_array_from_vector (bson_t *bson, const char *key, int key_length, const bson_iter_t *iter);
+
+#define BSON_APPEND_ARRAY_FROM_VECTOR(b, key, iter) bson_append_array_from_vector (b, key, (int) strlen (key), iter)
+
+BSON_EXPORT (bool)
+bson_array_builder_append_array_from_vector (bson_array_builder_t *bab, const bson_iter_t *iter);
+
+/**
  * bson_append_binary:
- * @bson: A bson_t to append.
+ * @bson: A bson_t.
  * @key: The key for the field.
- * @subtype: The bson_subtype_t of the binary.
+ * @key_length: Optional length of 'key' in bytes, or -1 to use strlen(key).
+ * @subtype: The bson_subtype_t of the binary item.
  * @binary: The binary buffer to append.
  * @length: The length of @binary.
  *
@@ -650,6 +643,30 @@ bson_array_builder_append_binary (bson_a
                                   uint32_t length);
 
 /**
+ * bson_append_binary_uninit:
+ * @bson: A bson_t.
+ * @key: The key for the field.
+ * @key_length: Optional length of 'key' in bytes, or -1 to use strlen(key).
+ * @binary: Output parameter, pointer for the binary data within bson_t to be written.
+ * @length: Length of the binary field to allocate, in bytes.
+ *
+ * Returns: true if successful; false if append would overflow max size.
+ */
+
+BSON_EXPORT (bool)
+bson_append_binary_uninit (
+   bson_t *bson, const char *key, int key_length, bson_subtype_t subtype, uint8_t **binary, uint32_t length);
+
+#define BSON_APPEND_BINARY_UNINIT(b, key, subtype, val, len) \
+   bson_append_binary_uninit (b, key, (int) strlen (key), subtype, val, len)
+
+BSON_EXPORT (bool)
+bson_array_builder_append_binary_uninit (bson_array_builder_t *bab,
+                                         bson_subtype_t subtype,
+                                         uint8_t **binary,
+                                         uint32_t length);
+
+/**
  * bson_append_bool:
  * @bson: A bson_t.
  * @key: The key for the field.
diff -pruN 1.30.4-1/src/libbson/src/bson/forwarding/bson.h 2.0.2-1/src/libbson/src/bson/forwarding/bson.h
--- 1.30.4-1/src/libbson/src/bson/forwarding/bson.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/forwarding/bson.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,18 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Including bson.h is superseded. Use bson/bson.h instead. */
-#include <bson/bson.h>
diff -pruN 1.30.4-1/src/libbson/src/bson/modules/module.modulemap.in 2.0.2-1/src/libbson/src/bson/modules/module.modulemap.in
--- 1.30.4-1/src/libbson/src/bson/modules/module.modulemap.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/modules/module.modulemap.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,5 +0,0 @@
-framework module bson [system] {
-    umbrella header "bson.h"
-    
-    export *
-}
\ No newline at end of file
diff -pruN 1.30.4-1/src/libbson/src/bson/validate-private.h 2.0.2-1/src/libbson/src/bson/validate-private.h
--- 1.30.4-1/src/libbson/src/bson/validate-private.h	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/validate-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,37 @@
+#ifndef BSON_VALIDATE_PRIVATE_H_INCLUDED
+#define BSON_VALIDATE_PRIVATE_H_INCLUDED
+
+#include <bson/bson-types.h>
+
+enum {
+   /**
+    * @brief This compile-time constant represents the maximum document nesting
+    * depth permitted by the `bson_validate` family of functions. If the nesting
+    * depth exceeds this limit, the data will be rejected.
+    *
+    * This limit is intentionally larger than the default limit of MongoDB
+    * server, since we cannot anticipate what a libbson user might actually want
+    * to do with BSON, and to prevent accidentally rejecting data that the
+    * server might accept. The main purpose of this limit is to prevent stack
+    * overflow, not to reject invalid data.
+    */
+   BSON_VALIDATION_MAX_NESTING_DEPTH = 500,
+};
+
+/**
+ * @brief Private function backing the implementation of validation.
+ *
+ * Validation was previously defined in the overburdened `bson-iter.c`, but it
+ * is now defined in its own file.
+ *
+ * @param bson The document to validate. Must be non-null.
+ * @param flags Validation control flags
+ * @param offset Receives the offset at which validation failed. Must be non-null.
+ * @param error Receives the error describing why validation failed. Must be non-null.
+ * @return true If the given document has no validation errors
+ * @return false Otherwise
+ */
+bool
+_bson_validate_impl_v2 (const bson_t *bson, bson_validate_flags_t flags, size_t *offset, bson_error_t *error);
+
+#endif // BSON_VALIDATE_PRIVATE_H_INCLUDED
diff -pruN 1.30.4-1/src/libbson/src/bson/validate.c 2.0.2-1/src/libbson/src/bson/validate.c
--- 1.30.4-1/src/libbson/src/bson/validate.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson/validate.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,566 @@
+/**
+ * @file bson/validate.c
+ * @brief Implementation of BSON document validation
+ * @date 2025-05-28
+ *
+ * This file implements the backend for the `bson_validate` family of functions.
+ *
+ * The `_validate_...` functions all accept `validator* self` as their first parameter,
+ * and must `return false` AND set `self->error` if-and-only-if they encounter a validation error.
+ * If a function returns true, it is assumed that validation of that item succeeded.
+ *
+ * For brevity, the `require...` macros are defined, which check conditions, set errors,
+ * and `return false` inline.
+ *
+ * @copyright Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bson/validate-private.h>
+#include <mlib/intencode.h>
+#include <mlib/test.h>
+#include <bson/bson.h>
+
+#include <stdbool.h>
+#include <string.h>
+
+/**
+ * @brief User parameters for validation behavior. These correspond to the various
+ * flags that can be given when the user requests validation
+ */
+typedef struct {
+   /**
+    * @brief Should we allow invalid UTF-8 in string components?
+    *
+    * This affects the behavior of validation of key strings and string-like
+    * elements that require UTF-8 encoding.
+    *
+    * Technically invalid UTF-8 is invalid in BSON, but applications may already
+    * rely on this being accepted.
+    */
+   bool allow_invalid_utf8;
+   /**
+    * @brief Should we allow a zero-valued codepoint in text?
+    *
+    * Unicode U+0000 is a valid codepoint, but a lot of software doesn't like
+    * it and handles it poorly. By default, we reject it, but the user may
+    * want to allow it.
+    *
+    * Note that because element keys rely on null termination, element keys
+    * cannot contain U+0000 by construction.
+    */
+   bool allow_null_in_utf8;
+   /// Should we allow element key strings to be empty strings?
+   bool allow_empty_keys;
+   /// Should we allow ASCII dot "." in element key strings?
+   bool allow_dot_in_keys;
+   /**
+    * @brief Check for special element keys that begin with an ASCII dollar "$"
+    *
+    * By default, we ignore them and treat them as regular elements. If this is
+    * enabled, we reject key strings that start with a dollar, unless it is a
+    * special extended JSON DBRef document.
+    *
+    * This also enables DBRef validation, which checks the structure of a document
+    * whose first key is "$ref".
+    */
+   bool check_special_dollar_keys;
+} validation_params;
+
+/**
+ * @brief State for a validator.
+ */
+typedef struct {
+   /// The parameters that control validation behavior
+   const validation_params *params;
+   /// Error storage that is updated if any validation encounters an error
+   bson_error_t error;
+   /// The zero-based index of the byte where validation stopped in case of an error.
+   size_t error_offset;
+} validator;
+
+// Undef these macros, if they are defined.
+#ifdef require_with_error
+#undef require_with_error
+#endif
+#ifdef require
+#undef require
+#endif
+#ifdef require_advance
+#undef require_advance
+#endif
+
+/**
+ * @brief Check that the given condition is satisfied, or set an error and return `false`
+ *
+ * @param Condition The condition that should evaluate to `true`
+ * @param Offset The byte offset where an error should be indicated.
+ * @param Code The error code that should be set if the condition fails
+ * @param ... The error string and format arguments to be used in the error message
+ *
+ * This macro assumes a `validator* self` is in scope. This macro will evaluate `return false`
+ * if the given condition is not true.
+ */
+#define require_with_error(Condition, Offset, Code, ...)                    \
+   if (!(Condition)) {                                                      \
+      self->error_offset = (Offset);                                        \
+      bson_set_error (&self->error, BSON_ERROR_INVALID, Code, __VA_ARGS__); \
+      return false;                                                         \
+   } else                                                                   \
+      ((void) 0)
+
+/**
+ * @brief Check that the given condition is satisfied, or `return false` immediately.
+ *
+ * This macro does not modify the validator state. It only does an early-return.
+ */
+#define require(Cond) \
+   if (!(Cond)) {     \
+      return false;   \
+   } else             \
+      ((void) 0)
+
+/**
+ * @brief Advance the pointed-to iterator, check for errors, and test whether we are done.
+ *
+ * @param DoneVar An l-value of type `bool` that is set to `true` if the iterator hit the end of
+ * the document, otherwise `false`
+ * @param IteratorPointer An expression of type `bson_iter_t*`, which will be advanced.
+ *
+ * If advancing the iterator results in a decoding error, then this macro sets an error
+ * on the `validator* self` that is in scope and will immediately `return false`.
+ */
+#define require_advance(DoneVar, IteratorPointer)                                                       \
+   if ((DoneVar = !bson_iter_next (IteratorPointer))) {                                                 \
+      /* The iterator indicates that it stopped */                                                      \
+      if ((IteratorPointer)->err_off) {                                                                 \
+         /* The iterator stopped because of a decoding error */                                         \
+         require_with_error (false, (IteratorPointer)->err_off, BSON_VALIDATE_CORRUPT, "corrupt BSON"); \
+      }                                                                                                 \
+   } else                                                                                               \
+      ((void) 0)
+
+// Test if the element's key is equal to the given string
+static bool
+_key_is (bson_iter_t const *iter, const char *const key)
+{
+   BSON_ASSERT_PARAM (iter);
+   BSON_ASSERT_PARAM (key);
+   return !strcmp (bson_iter_key (iter), key);
+}
+
+/**
+ * @brief Validate a document or array object, recursively.
+ *
+ * @param self The validator which will be updated and used to do the validation
+ * @param bson The object to be validated
+ * @param depth The validation depth. We indicate an error if this exceeds a limit.
+ * @return true If the object is valid
+ * @return false Otherwise
+ */
+static bool
+_validate_doc (validator *self, const bson_t *bson, int depth);
+
+/**
+ * @brief Validate a UTF-8 string, if-and-only-if UTF-8 validation is requested
+ *
+ * @param self Pointer to the validator object
+ * @param offset The byte-offset of the string, used to set the error offset
+ * @param u8 Pointer to the first byte in a UTF-8 string
+ * @param u8len The length of the array pointed-to by `u8`
+ * @return true If the UTF-8 string is valid, or if UTF-8 validation is disabled
+ * @return false If UTF-8 validation is requested, AND (the UTF-8 string is invalid OR (UTF-8 strings should not contain
+ * null characters and the UTF-8 string contains a null character))
+ */
+static bool
+_maybe_validate_utf8 (validator *self, size_t offset, const char *u8, size_t u8len)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (u8);
+   if (self->params->allow_invalid_utf8) {
+      // We are not doing UTF-8 checks, so always succeed
+      return true;
+   }
+   // Validate UTF-8
+   const bool u8okay = bson_utf8_validate (u8, u8len, self->params->allow_null_in_utf8);
+   if (u8okay) {
+      // Valid UTF-8, no more checks
+      return true;
+   }
+   // Validation error. It may be invalid UTF-8, or it could be valid UTF-8 with a disallowed null
+   if (!self->params->allow_null_in_utf8) {
+      // We are disallowing null in UTF-8. Check whether it is invalid UTF-8, or is
+      // valid UTF-8 with a null character
+      const bool u8okay_with_null = bson_utf8_validate (u8, u8len, true);
+      if (u8okay_with_null) {
+         // The UTF-8 is valid, but contains a null character.
+         require_with_error (
+            false, offset, BSON_VALIDATE_UTF8_ALLOW_NULL, "UTF-8 string contains a U+0000 (null) character");
+      }
+   }
+   // The UTF-8 is invalid, regardless of whether it contains a null character
+   require_with_error (false, offset, BSON_VALIDATE_UTF8, "Text element is not valid UTF-8");
+}
+
+// Same as `_maybe_validate_u8`, but relies on a null-terminated C string to get the string length
+static bool
+_maybe_validate_utf8_cstring (validator *self, size_t offset, const char *const u8)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (u8);
+   return _maybe_validate_utf8 (self, offset, u8, strlen (u8));
+}
+
+/**
+ * @brief Validate a string-like element (UTF-8, Symbol, or Code)
+ *
+ * This function relies on the representation of the text-like elements within
+ * the iterator struct to reduce code dup around text validation.
+ */
+static bool
+_validate_stringlike_element (validator *self, bson_iter_t const *iter)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   // iter->d1 is the offset to the string header. Subtract 1 to exclude the null terminator
+   const uint32_t u8len = mlib_read_u32le (iter->raw + iter->d1) - 1;
+   // iter->d2 is the offset to the first byte of the string
+   const char *u8 = (const char *) iter->raw + iter->d2;
+   return _maybe_validate_utf8 (self, iter->off, u8, u8len);
+}
+
+static bool
+_validate_regex_elem (validator *self, bson_iter_t const *iter)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   mlib_check (BSON_ITER_HOLDS_REGEX (iter));
+   const char *opts;
+   const char *const rx = bson_iter_regex (iter, &opts);
+   mlib_check (rx);
+   mlib_check (opts);
+   return _maybe_validate_utf8_cstring (self, iter->off, rx) //
+          && _maybe_validate_utf8_cstring (self, iter->off, opts);
+}
+
+static bool
+_validate_codewscope_elem (validator *self, bson_iter_t const *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   mlib_check (BSON_ITER_HOLDS_CODEWSCOPE (iter));
+   // Extract the code and the scope object
+   uint8_t const *doc;
+   uint32_t doc_len;
+   uint32_t u8len;
+   const char *const u8 = bson_iter_codewscope (iter, &u8len, &doc_len, &doc);
+   bson_t scope;
+   require_with_error (
+      bson_init_static (&scope, doc, doc_len), iter->off, BSON_VALIDATE_CORRUPT, "corrupt scope document");
+
+   // Validate the code string
+   require (_maybe_validate_utf8 (self, iter->off, u8, u8len));
+
+   // Now we validate the scope object.
+   // Don't validate the scope document using the parent parameters, because it should
+   // be treated as an opaque closure of JS variables.
+   validation_params const scope_params = {
+      // JS object keys can contain dots
+      .allow_dot_in_keys = true,
+      // JS object keys can be empty
+      .allow_empty_keys = true,
+      // JS strings can contain null bytes
+      .allow_null_in_utf8 = true,
+      // JS strings need to encode properly
+      .allow_invalid_utf8 = false,
+      // JS allows object keys to have dollars
+      .check_special_dollar_keys = false,
+   };
+   validator scope_validator = {.params = &scope_params};
+   // We could do more validation that the scope keys are valid JS identifiers,
+   // but that would require using a full Unicode database.
+   if (_validate_doc (&scope_validator, &scope, depth)) {
+      // No error
+      return true;
+   }
+   // Validation error. Copy the error message, adding the name of the bad element
+   bson_set_error (&self->error,
+                   scope_validator.error.domain,
+                   scope_validator.error.code,
+                   "Error in scope document for element \"%s\": %s",
+                   bson_iter_key (iter),
+                   scope_validator.error.message);
+   // Adjust the error offset by the offset of the iterator
+   self->error_offset = scope_validator.error_offset + iter->off;
+   return false;
+}
+
+// Validate an element's key string according to the validation rules
+static bool
+_validate_element_key (validator *self, bson_iter_t const *iter)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+
+   const char *const key = bson_iter_key (iter);
+   mlib_check (key);
+   const size_t key_len = bson_iter_key_len (iter);
+
+   // Check the UTF-8 of the key
+   require (_maybe_validate_utf8 (self, iter->off, key, key_len));
+
+   // Check for special keys
+   if (self->params->check_special_dollar_keys) {
+      // dollar-keys are checked during the startup of _validate_doc. If we get here, there's a problem.
+      require_with_error (
+         key[0] != '$', iter->off, BSON_VALIDATE_DOLLAR_KEYS, "Disallowed '$' in element key: \"%s\"", key);
+   }
+
+   if (!self->params->allow_empty_keys) {
+      require_with_error (key_len != 0, iter->off, BSON_VALIDATE_EMPTY_KEYS, "Element key cannot be an empty string");
+   }
+
+   if (!self->params->allow_dot_in_keys) {
+      require_with_error (
+         !strstr (key, "."), iter->off, BSON_VALIDATE_DOT_KEYS, "Disallowed '.' in element key: \"%s\"", key);
+   }
+
+   return true;
+}
+
+// Extract a document referred-to by the given iterator. It must point to a
+// document or array element. Returns `false` if `bson_init_static` returns false
+static bool
+_get_subdocument (bson_t *subdoc, bson_iter_t const *iter)
+{
+   BSON_ASSERT_PARAM (subdoc);
+   BSON_ASSERT_PARAM (iter);
+   uint32_t len = mlib_read_u32le (iter->raw + iter->d1);
+   uint8_t const *data = (uint8_t const *) iter->raw + iter->d1;
+   return bson_init_static (subdoc, data, len);
+}
+
+// Validate the value of an element, without checking its key
+static bool
+_validate_element_value (validator *self, bson_iter_t const *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+
+   const bson_type_t type = bson_iter_type (iter);
+   switch (type) {
+   default:
+   case BSON_TYPE_EOD:
+      BSON_UNREACHABLE ("Validation execution encountered an element of type 0x0, but this should not happen as tag "
+                        "validation is handled before we get to this point.");
+   case BSON_TYPE_DOUBLE:
+   case BSON_TYPE_NULL:
+   case BSON_TYPE_OID:
+   case BSON_TYPE_INT32:
+   case BSON_TYPE_INT64:
+   case BSON_TYPE_MINKEY:
+   case BSON_TYPE_MAXKEY:
+   case BSON_TYPE_TIMESTAMP:
+   case BSON_TYPE_UNDEFINED:
+   case BSON_TYPE_DECIMAL128:
+   case BSON_TYPE_DATE_TIME:
+   case BSON_TYPE_BOOL:
+      // No validation on these simple scalar elements. `bson_iter_next` does validation
+      // on these objects for us.
+      return true;
+   case BSON_TYPE_BINARY:
+      // Note: BSON binary validation is handled by bson_iter_next, which checks the
+      // internal structure properly. If we get here, then the binary data is okay.
+      return true;
+   case BSON_TYPE_DBPOINTER:
+      // DBPointer contains more than just a string, but we only need to validate
+      // the string component, which happens to align with the repr of other stringlike
+      // elements. bson_iter_next will do the validation on the element's size.
+      //! fallthrough
+   case BSON_TYPE_SYMBOL:
+   case BSON_TYPE_CODE:
+   case BSON_TYPE_UTF8:
+      return _validate_stringlike_element (self, iter);
+   case BSON_TYPE_DOCUMENT:
+   case BSON_TYPE_ARRAY: {
+      bson_t doc;
+      require_with_error (_get_subdocument (&doc, iter), iter->off, BSON_VALIDATE_CORRUPT, "corrupt BSON");
+      if (_validate_doc (self, &doc, depth)) {
+         // No error
+         return true;
+      }
+      // Error in subdocument. Adjust the error offset for the current iterator position,
+      // plus the key length, plus 2 for the tag and key's null terminator.
+      self->error_offset += iter->off + bson_iter_key_len (iter) + 2;
+      return false;
+   }
+
+   case BSON_TYPE_REGEX:
+      return _validate_regex_elem (self, iter);
+   case BSON_TYPE_CODEWSCOPE:
+      return _validate_codewscope_elem (self, iter, depth);
+   }
+}
+
+// Validate a single BSON element referred-to by the given iterator
+static bool
+_validate_element (validator *self, bson_iter_t *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   return _validate_element_key (self, iter) && _validate_element_value (self, iter, depth);
+}
+
+/**
+ * @brief Validate the elements of a document, beginning with the element pointed-to
+ * by the given iterator.
+ */
+static bool
+_validate_remaining_elements (validator *self, bson_iter_t *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   bool done = false;
+   while (!done) {
+      require (_validate_element (self, iter, depth));
+      require_advance (done, iter);
+   }
+   return true;
+}
+
+// Do validation for a DBRef document, indicated by a leading $ref key
+static bool
+_validate_dbref (validator *self, bson_iter_t *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+
+   // The iterator must be pointing to the initial $ref element
+   mlib_check (_key_is (iter, "$ref"));
+   // Check that $ref is a UTF-8 element
+   require_with_error (
+      BSON_ITER_HOLDS_UTF8 (iter), iter->off, BSON_VALIDATE_DOLLAR_KEYS, "$ref element must be a UTF-8 element");
+   require (_validate_element_value (self, iter, depth));
+
+   // We require an $id as the next element
+   bool done;
+   require_advance (done, iter);
+   require_with_error (
+      !done && _key_is (iter, "$id"), iter->off, BSON_VALIDATE_DOLLAR_KEYS, "Expected an $id element following $ref");
+   // While $id is typically a OID value, it is not constraint to any specific type, so
+   // we just validate it as an arbitrary value.
+   require (_validate_element_value (self, iter, depth));
+
+   // We should stop, or we should have a $db, or we may have other elements
+   require_advance (done, iter);
+   if (done) {
+      // No more elements. Nothing left to check
+      return true;
+   }
+   // If it's a $db, check that it's a UTF-8 string
+   if (_key_is (iter, "$db")) {
+      require_with_error (BSON_ITER_HOLDS_UTF8 (iter),
+                          iter->off,
+                          BSON_VALIDATE_DOLLAR_KEYS,
+                          "$db element in DBRef must be a UTF-8 element");
+      require (_validate_element_value (self, iter, depth));
+      // Advance past the $db
+      require_advance (done, iter);
+      if (done) {
+         // Nothing left to do
+         return true;
+      }
+   }
+   // All subsequent elements should be validated as normal, and we don't expect
+   // any more $-keys
+   return _validate_remaining_elements (self, iter, depth);
+}
+
+// If we are validating special $-keys, validate a document whose first element is a $-key
+static bool
+_validate_dollar_doc (validator *self, bson_iter_t *iter, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (iter);
+   if (_key_is (iter, "$ref")) {
+      return _validate_dbref (self, iter, depth);
+   }
+   // Have the element key validator issue an error message about the bad $-key
+   bool okay = _validate_element_key (self, iter);
+   mlib_check (!okay);
+   return false;
+}
+
+static bool
+_validate_doc (validator *self, const bson_t *bson, int depth)
+{
+   BSON_ASSERT_PARAM (self);
+   BSON_ASSERT_PARAM (bson);
+
+   require_with_error (
+      depth <= BSON_VALIDATION_MAX_NESTING_DEPTH, 0, BSON_VALIDATE_CORRUPT, "BSON document nesting depth is too deep");
+   // We increment the depth here, otherwise we'd have `depth + 1` in several places.
+   ++depth;
+
+   // Initialize an iterator into the document to be validated
+   bson_iter_t iter;
+   require_with_error (
+      bson_iter_init (&iter, bson), 0, BSON_VALIDATE_CORRUPT, "Document header corruption, unable to iterate");
+   bool done;
+   require_advance (done, &iter);
+   if (done) {
+      // Nothing to check (empty doc/array)
+      return true;
+   }
+
+   // Check if the first key starts with a dollar
+   if (self->params->check_special_dollar_keys) {
+      const char *const key = bson_iter_key (&iter);
+      if (key[0] == '$') {
+         return _validate_dollar_doc (self, &iter, depth);
+      }
+   }
+
+   return _validate_remaining_elements (self, &iter, depth);
+}
+
+// This private function is called by `bson_validate_with_error_and_offset`
+bool
+_bson_validate_impl_v2 (const bson_t *bson, bson_validate_flags_t flags, size_t *offset, bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (offset);
+   BSON_ASSERT_PARAM (error);
+
+   // Clear the error
+   *error = (bson_error_t){0};
+
+   // Initialize validation parameters
+   validation_params const params = {
+      .allow_invalid_utf8 = !(flags & BSON_VALIDATE_UTF8),
+      .allow_null_in_utf8 = flags & BSON_VALIDATE_UTF8_ALLOW_NULL,
+      .check_special_dollar_keys = (flags & BSON_VALIDATE_DOLLAR_KEYS),
+      .allow_dot_in_keys = !(flags & BSON_VALIDATE_DOT_KEYS),
+      .allow_empty_keys = !(flags & BSON_VALIDATE_EMPTY_KEYS),
+   };
+
+   // Start the validator on the root document
+   validator v = {.params = &params};
+   bool okay = _validate_doc (&v, bson, 0);
+   *offset = v.error_offset;
+   *error = v.error;
+   mlib_check (okay == (v.error.code == 0) &&
+               "Validation routine should return `false` if-and-only-if it sets an error code");
+   return okay;
+}
diff -pruN 1.30.4-1/src/libbson/src/bson-config.cmake 2.0.2-1/src/libbson/src/bson-config.cmake
--- 1.30.4-1/src/libbson/src/bson-config.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/bson-config.cmake	1970-01-01 00:00:00.000000000 +0000
@@ -1,13 +0,0 @@
-include(CMakeFindDependencyMacro)
-find_dependency(Threads)  # Required for Threads::Threads
-
-# Import common targets first:
-include("${CMAKE_CURRENT_LIST_DIR}/bson-targets.cmake")
-
-# Now import the targets of each link-kind that's available. Only the targets of
-# libbson libraries that were actually installed alongside this file will be
-# imported.
-file(GLOB target_files "${CMAKE_CURRENT_LIST_DIR}/bson_*-targets.cmake")
-foreach(inc IN LISTS target_files)
-    include("${inc}")
-endforeach()
diff -pruN 1.30.4-1/src/libbson/src/jsonsl/jsonsl.c 2.0.2-1/src/libbson/src/jsonsl/jsonsl.c
--- 1.30.4-1/src/libbson/src/jsonsl/jsonsl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/jsonsl/jsonsl.c	2025-06-19 15:42:22.000000000 +0000
@@ -9,77 +9,6 @@
 #include <limits.h>
 #include <ctype.h>
 
-#ifdef JSONSL_USE_METRICS
-#define XMETRICS \
-    X(STRINGY_INSIGNIFICANT) \
-    X(STRINGY_SLOWPATH) \
-    X(ALLOWED_WHITESPACE) \
-    X(QUOTE_FASTPATH) \
-    X(SPECIAL_FASTPATH) \
-    X(SPECIAL_WSPOP) \
-    X(SPECIAL_SLOWPATH) \
-    X(GENERIC) \
-    X(STRUCTURAL_TOKEN) \
-    X(SPECIAL_SWITCHFIRST) \
-    X(STRINGY_CATCH) \
-    X(NUMBER_FASTPATH) \
-    X(ESCAPES) \
-    X(TOTAL) \
-
-struct jsonsl_metrics_st {
-#define X(m) \
-    unsigned long metric_##m;
-    XMETRICS
-#undef X
-};
-
-static struct jsonsl_metrics_st GlobalMetrics = { 0 };
-static unsigned long GenericCounter[0x100] = { 0 };
-static unsigned long StringyCatchCounter[0x100] = { 0 };
-
-#define INCR_METRIC(m) \
-    GlobalMetrics.metric_##m++;
-
-#define INCR_GENERIC(c) \
-        INCR_METRIC(GENERIC); \
-        GenericCounter[c]++; \
-
-#define INCR_STRINGY_CATCH(c) \
-    INCR_METRIC(STRINGY_CATCH); \
-    StringyCatchCounter[c]++;
-
-JSONSL_API
-void jsonsl_dump_global_metrics(void)
-{
-    int ii;
-    printf("JSONSL Metrics:\n");
-#define X(m) \
-    printf("\t%-30s %20lu (%0.2f%%)\n", #m, GlobalMetrics.metric_##m, \
-           (float)((float)(GlobalMetrics.metric_##m/(float)GlobalMetrics.metric_TOTAL)) * 100);
-    XMETRICS
-#undef X
-    printf("Generic Characters:\n");
-    for (ii = 0; ii < 0xff; ii++) {
-        if (GenericCounter[ii]) {
-            printf("\t[ %c ] %lu\n", ii, GenericCounter[ii]);
-        }
-    }
-    printf("Weird string loop\n");
-    for (ii = 0; ii < 0xff; ii++) {
-        if (StringyCatchCounter[ii]) {
-            printf("\t[ %c ] %lu\n", ii, StringyCatchCounter[ii]);
-        }
-    }
-}
-
-#else
-#define INCR_METRIC(m)
-#define INCR_GENERIC(c)
-#define INCR_STRINGY_CATCH(c)
-JSONSL_API
-void jsonsl_dump_global_metrics(void) { }
-#endif /* JSONSL_USE_METRICS */
-
 #define CASE_DIGITS \
 case '1': \
 case '2': \
@@ -99,7 +28,6 @@ static int is_allowed_escape(unsigned);
 static int is_simple_char(unsigned);
 static char get_escape_equiv(unsigned);
 
-JSONSL_API
 jsonsl_t jsonsl_new(int nlevels)
 {
     unsigned int ii;
@@ -123,7 +51,6 @@ jsonsl_t jsonsl_new(int nlevels)
     return jsn;
 }
 
-JSONSL_API
 void jsonsl_reset(jsonsl_t jsn)
 {
     jsn->tok_last = 0;
@@ -135,7 +62,6 @@ void jsonsl_reset(jsonsl_t jsn)
     jsn->expecting = 0;
 }
 
-JSONSL_API
 void jsonsl_destroy(jsonsl_t jsn)
 {
     if (jsn) {
@@ -170,8 +96,6 @@ jsonsl__str_fastparse(jsonsl_t jsn,
                 *bytes >= 0x100 ||
 #endif /* JSONSL_USE_WCHAR */
                 (is_simple_char(*bytes))) {
-            INCR_METRIC(TOTAL);
-            INCR_METRIC(STRINGY_INSIGNIFICANT);
         } else {
             /* Once we're done here, re-calculate the position variables */
             jsn->pos += (bytes - *bytes_p);
@@ -200,8 +124,6 @@ jsonsl__num_fastparse(jsonsl_t jsn,
     for (; nbytes; nbytes--, bytes++) {
         jsonsl_uchar_t c = *bytes;
         if (isdigit(c)) {
-            INCR_METRIC(TOTAL);
-            INCR_METRIC(NUMBER_FASTPATH);
             state->nelem = (state->nelem * 10) + (c - 0x30);
         } else {
             exhausted = 0;
@@ -217,7 +139,6 @@ jsonsl__num_fastparse(jsonsl_t jsn,
     return FASTPARSE_BREAK;
 }
 
-JSONSL_API
 void
 jsonsl_feed(jsonsl_t jsn, const jsonsl_char_t *bytes, size_t nbytes)
 {
@@ -237,15 +158,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
     state->ignore_callback = jsn->stack[jsn->level-1].ignore_callback; \
     state->pos_begin = jsn->pos;
 
-#define STACK_POP_NOPOS \
-    state->pos_cur = jsn->pos; \
-    state = jsn->stack + (--jsn->level);
-
-
-#define STACK_POP \
-    STACK_POP_NOPOS; \
-    state->pos_cur = jsn->pos;
-
 #define CALLBACK_AND_POP_NOPOS(T) \
         state->pos_cur = jsn->pos; \
         DO_CALLBACK(T, POP); \
@@ -314,7 +226,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
 
     for (; nbytes; nbytes--, jsn->pos++, c++) {
         unsigned state_type;
-        INCR_METRIC(TOTAL);
 
         GT_AGAIN:
         state_type = state->type;
@@ -347,7 +258,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
                     INVOKE_ERROR(WEIRD_WHITESPACE);
                 }
             }
-            INCR_METRIC(STRINGY_SLOWPATH);
 
         } else if (state_type == JSONSL_T_SPECIAL) {
             /* Fast track for signed/unsigned */
@@ -476,7 +386,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
                    }
 #endif
                 }
-                INCR_METRIC(SPECIAL_FASTPATH);
                 CONTINUE_NEXT_CHAR();
             }
 
@@ -529,7 +438,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
              */
             goto GT_STRUCTURAL_TOKEN;
         } else if (is_allowed_whitespace(CUR_CHAR)) {
-            INCR_METRIC(ALLOWED_WHITESPACE);
             /* So we're not special. Harmless insignificant whitespace
              * passthrough
              */
@@ -539,8 +447,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
             goto GT_SPECIAL_BEGIN;
         }
 
-        INCR_GENERIC(CUR_CHAR);
-
         if (CUR_CHAR == '"') {
             GT_QUOTE:
             jsn->can_insert = 0;
@@ -601,7 +507,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
             } /* switch(state->type) */
         } else if (CUR_CHAR == '\\') {
             GT_ESCAPE:
-            INCR_METRIC(ESCAPES);
         /* Escape */
             if ( (state->type & JSONSL_Tf_STRINGY) == 0 ) {
                 INVOKE_ERROR(ESCAPE_OUTSIDE_STRING);
@@ -614,7 +519,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
         GT_STRUCTURAL_TOKEN:
         switch (CUR_CHAR) {
         case ':':
-            INCR_METRIC(STRUCTURAL_TOKEN);
             if (jsn->expecting != CUR_CHAR) {
                 INVOKE_ERROR(STRAY_TOKEN);
             }
@@ -624,7 +528,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
             CONTINUE_NEXT_CHAR();
 
         case ',':
-            INCR_METRIC(STRUCTURAL_TOKEN);
             /**
              * The comma is one of the more generic tokens.
              * In the context of an OBJECT, the can_insert flag
@@ -653,7 +556,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
             /* hashes are more common */
         case '{':
         case '[':
-            INCR_METRIC(STRUCTURAL_TOKEN);
             if (!jsn->can_insert) {
                 INVOKE_ERROR(CANT_INSERT);
             }
@@ -681,7 +583,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
             /* closing of list or object */
         case '}':
         case ']':
-            INCR_METRIC(STRUCTURAL_TOKEN);
             if (jsn->tok_last == ',' && jsn->options.allow_trailing_comma == 0) {
                 INVOKE_ERROR(TRAILING_COMMA);
             }
@@ -754,7 +655,6 @@ jsonsl_feed(jsonsl_t jsn, const jsonsl_c
     }
 }
 
-JSONSL_API
 const char* jsonsl_strerror(jsonsl_error_t err)
 {
     if (err == JSONSL_ERROR_SUCCESS) {
@@ -768,7 +668,6 @@ const char* jsonsl_strerror(jsonsl_error
     return "<UNKNOWN_ERROR>";
 }
 
-JSONSL_API
 const char *jsonsl_strtype(jsonsl_type_t type)
 {
 #define X(o,c) \
@@ -786,7 +685,6 @@ const char *jsonsl_strtype(jsonsl_type_t
  *
  *
  */
-#ifndef JSONSL_NO_JPR
 static
 jsonsl_jpr_type_t
 populate_component(char *in,
@@ -879,7 +777,6 @@ populate_component(char *in,
     return ret;
 }
 
-JSONSL_API
 jsonsl_jpr_t
 jsonsl_jpr_new(const char *path, jsonsl_error_t *errp)
 {
@@ -1030,7 +927,6 @@ jsonsl__match_continue(jsonsl_jpr_t jpr,
     }
 }
 
-JSONSL_API
 jsonsl_jpr_match_t
 jsonsl_path_match(jsonsl_jpr_t jpr,
                   const struct jsonsl_state_st *parent,
@@ -1061,7 +957,6 @@ jsonsl_path_match(jsonsl_jpr_t jpr,
     return jsonsl__match_continue(jpr, comp, parent->level, child->type);
 }
 
-JSONSL_API
 jsonsl_jpr_match_t
 jsonsl_jpr_match(jsonsl_jpr_t jpr,
                    unsigned int parent_type,
@@ -1139,7 +1034,6 @@ jsonsl_jpr_match(jsonsl_jpr_t jpr,
     return JSONSL_MATCH_NOMATCH;
 }
 
-JSONSL_API
 void jsonsl_jpr_match_state_init(jsonsl_t jsn,
                                  jsonsl_jpr_t *jprs,
                                  size_t njprs)
@@ -1160,7 +1054,6 @@ void jsonsl_jpr_match_state_init(jsonsl_
     }
 }
 
-JSONSL_API
 void jsonsl_jpr_match_state_cleanup(jsonsl_t jsn)
 {
     if (jsn->jpr_count == 0) {
@@ -1187,7 +1080,6 @@ void jsonsl_jpr_match_state_cleanup(json
  * main lexer itself.
  *
  */
-JSONSL_API
 jsonsl_jpr_t jsonsl_jpr_match_state(jsonsl_t jsn,
                                     struct jsonsl_state_st *state,
                                     const char *key,
@@ -1252,7 +1144,6 @@ jsonsl_jpr_t jsonsl_jpr_match_state(json
     return NULL;
 }
 
-JSONSL_API
 const char *jsonsl_strmatchtype(jsonsl_jpr_match_t match)
 {
 #define X(T,v) \
@@ -1263,8 +1154,6 @@ const char *jsonsl_strmatchtype(jsonsl_j
     return "<UNKNOWN>";
 }
 
-#endif /* JSONSL_WITH_JPR */
-
 static char *
 jsonsl__writeutf8(uint32_t pt, char *out)
 {
@@ -1330,7 +1219,6 @@ jsonsl__get_uescape_16(const char *s)
 /**
  * Utility function to convert escape sequences
  */
-JSONSL_API
 size_t jsonsl_util_unescape_ex(const char *in,
                                char *out,
                                size_t len,
@@ -1658,14 +1546,9 @@ static int is_simple_char(unsigned c) {
 }
 
 /* Clean up all our macros! */
-#undef INCR_METRIC
-#undef INCR_GENERIC
-#undef INCR_STRINGY_CATCH
 #undef CASE_DIGITS
 #undef INVOKE_ERROR
 #undef STACK_PUSH
-#undef STACK_POP_NOPOS
-#undef STACK_POP
 #undef CALLBACK_AND_POP_NOPOS
 #undef CALLBACK_AND_POP
 #undef SPECIAL_POP
diff -pruN 1.30.4-1/src/libbson/src/jsonsl/jsonsl.h 2.0.2-1/src/libbson/src/jsonsl/jsonsl.h
--- 1.30.4-1/src/libbson/src/jsonsl/jsonsl.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/src/jsonsl/jsonsl.h	2025-06-19 15:42:22.000000000 +0000
@@ -73,19 +73,6 @@ typedef int ssize_t;
 #define JSONSL_JPR_COMPONENT_USER_FIELDS
 #endif
 
-#ifndef JSONSL_API
-/**
- * We require a /DJSONSL_DLL so that users already using this as a static
- * or embedded library don't get confused
- */
-#if defined(_WIN32) && defined(JSONSL_DLL)
-#define JSONSL_API __declspec(dllexport)
-#else
-#define JSONSL_API
-#endif /* _WIN32 */
-
-#endif /* !JSONSL_API */
-
 #ifndef JSONSL_INLINE
 #if defined(_MSC_VER)
   #define JSONSL_INLINE __inline
@@ -554,13 +541,11 @@ struct jsonsl_st {
     int can_insert;
     unsigned int levels_max;
 
-#ifndef JSONSL_NO_JPR
     size_t jpr_count;
     jsonsl_jpr_t *jprs;
 
     /* Root pointer for JPR matching information */
     size_t *jpr_root;
-#endif /* JSONSL_NO_JPR */
     /*@}*/
 
     /**
@@ -577,7 +562,6 @@ struct jsonsl_st {
  *
  * @param nlevels maximum recursion depth
  */
-JSONSL_API
 jsonsl_t jsonsl_new(int nlevels);
 
 /**
@@ -587,7 +571,6 @@ jsonsl_t jsonsl_new(int nlevels);
  * @param bytes new data to be fed
  * @param nbytes size of new data
  */
-JSONSL_API
 void jsonsl_feed(jsonsl_t jsn, const jsonsl_char_t *bytes, size_t nbytes);
 
 /**
@@ -597,7 +580,6 @@ void jsonsl_feed(jsonsl_t jsn, const jso
  *
  * @param jsn the lexer
  */
-JSONSL_API
 void jsonsl_reset(jsonsl_t jsn);
 
 /**
@@ -605,7 +587,6 @@ void jsonsl_reset(jsonsl_t jsn);
  *
  * @param jsn the lexer
  */
-JSONSL_API
 void jsonsl_destroy(jsonsl_t jsn);
 
 /**
@@ -675,22 +656,10 @@ void jsonsl_enable_all_callbacks(jsonsl_
  * of the error or type, respectively. They will never
  * return NULL
  */
-JSONSL_API
 const char* jsonsl_strerror(jsonsl_error_t err);
-JSONSL_API
 const char* jsonsl_strtype(jsonsl_type_t jt);
 
 /**
- * Dumps global metrics to the screen. This is a noop unless
- * jsonsl was compiled with JSONSL_USE_METRICS
- */
-JSONSL_API
-void jsonsl_dump_global_metrics(void);
-
-/* This macro just here for editors to do code folding */
-#ifndef JSONSL_NO_JPR
-
-/**
  * @name JSON Pointer API
  *
  * JSONPointer API. This isn't really related to the lexer (at least not yet)
@@ -803,13 +772,11 @@ struct jsonsl_jpr_st {
  *
  * @return a new jsonsl_jpr_t object, or NULL on error.
  */
-JSONSL_API
 jsonsl_jpr_t jsonsl_jpr_new(const char *path, jsonsl_error_t *errp);
 
 /**
  * Destroy a JPR object
  */
-JSONSL_API
 void jsonsl_jpr_destroy(jsonsl_jpr_t jpr);
 
 /**
@@ -830,7 +797,6 @@ void jsonsl_jpr_destroy(jsonsl_jpr_t jpr
  * @return a status constant. This indicates whether a match was excluded, possible,
  * or successful.
  */
-JSONSL_API
 jsonsl_jpr_match_t jsonsl_jpr_match(jsonsl_jpr_t jpr,
                                     unsigned int parent_type,
                                     unsigned int parent_level,
@@ -861,7 +827,6 @@ jsonsl_jpr_match_t jsonsl_jpr_match(json
  * Since this function also checks the state of the child, it should only
  * be called on PUSH callbacks, and not POP callbacks
  */
-JSONSL_API
 jsonsl_jpr_match_t
 jsonsl_path_match(jsonsl_jpr_t jpr,
                   const struct jsonsl_state_st *parent,
@@ -885,7 +850,6 @@ jsonsl_path_match(jsonsl_jpr_t jpr,
  * @param jprs An array of jsonsl_jpr_t objects
  * @param njprs How many elements in the jprs array.
  */
-JSONSL_API
 void jsonsl_jpr_match_state_init(jsonsl_t jsn,
                                  jsonsl_jpr_t *jprs,
                                  size_t njprs);
@@ -910,7 +874,6 @@ void jsonsl_jpr_match_state_init(jsonsl_
  * does not mean matching has failed, it can still be part of the match: check
  * the out parameter).
  */
-JSONSL_API
 jsonsl_jpr_t jsonsl_jpr_match_state(jsonsl_t jsn,
                                     struct jsonsl_state_st *state,
                                     const char *key,
@@ -923,13 +886,11 @@ jsonsl_jpr_t jsonsl_jpr_match_state(json
  * match_state_init() and match_state()
  * @param jsn The lexer
  */
-JSONSL_API
 void jsonsl_jpr_match_state_cleanup(jsonsl_t jsn);
 
 /**
  * Return a string representation of the match result returned by match()
  */
-JSONSL_API
 const char *jsonsl_strmatchtype(jsonsl_jpr_match_t match);
 
 /* @}*/
@@ -982,7 +943,6 @@ const char *jsonsl_strmatchtype(jsonsl_j
  * (i.e. \uXXXX) will occupy six bytes in the source, but at the most
  * two bytes when escaped.
  */
-JSONSL_API
 size_t jsonsl_util_unescape_ex(const char *in,
                                char *out,
                                size_t len,
@@ -997,8 +957,6 @@ size_t jsonsl_util_unescape_ex(const cha
 #define jsonsl_util_unescape(in, out, len, toEscape, err) \
     jsonsl_util_unescape_ex(in, out, len, toEscape, NULL, err, NULL)
 
-#endif /* JSONSL_NO_JPR */
-
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
diff -pruN 1.30.4-1/src/libbson/tests/json/bson_binary_vector/float32.json 2.0.2-1/src/libbson/tests/json/bson_binary_vector/float32.json
--- 1.30.4-1/src/libbson/tests/json/bson_binary_vector/float32.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/json/bson_binary_vector/float32.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,65 @@
+{
+  "description": "Tests of Binary subtype 9, Vectors, with dtype FLOAT32",
+  "test_key": "vector",
+  "tests": [
+    {
+      "description": "Simple Vector FLOAT32",
+      "valid": true,
+      "vector": [127.0, 7.0],
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "padding": 0,
+      "canonical_bson": "1C00000005766563746F72000A0000000927000000FE420000E04000"
+    },
+    {
+      "description": "Vector with decimals and negative value FLOAT32",
+      "valid": true,
+      "vector": [127.7, -7.7],
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "padding": 0,
+      "canonical_bson": "1C00000005766563746F72000A0000000927006666FF426666F6C000"
+    },
+    {
+      "description": "Empty Vector FLOAT32",
+      "valid": true,
+      "vector": [],
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "padding": 0,
+      "canonical_bson": "1400000005766563746F72000200000009270000"
+    },
+    {
+      "description": "Infinity Vector FLOAT32",
+      "valid": true,
+      "vector": [{"$numberDouble": "-Infinity"}, 0.0, {"$numberDouble": "Infinity"} ],
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "padding": 0,
+      "canonical_bson": "2000000005766563746F72000E000000092700000080FF000000000000807F00"
+    },
+    {
+      "description": "FLOAT32 with padding",
+      "valid": false,
+      "vector": [127.0, 7.0],
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "padding": 3,
+      "canonical_bson": "1C00000005766563746F72000A0000000927030000FE420000E04000"
+    },
+    {
+      "description": "Insufficient vector data with 3 bytes FLOAT32",
+      "valid": false,
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "canonical_bson": "1700000005766563746F7200050000000927002A2A2A00"
+    },
+    {
+      "description": "Insufficient vector data with 5 bytes FLOAT32",
+      "valid": false,
+      "dtype_hex": "0x27",
+      "dtype_alias": "FLOAT32",
+      "canonical_bson": "1900000005766563746F7200070000000927002A2A2A2A2A00"
+    }
+  ]
+}
diff -pruN 1.30.4-1/src/libbson/tests/json/bson_binary_vector/int8.json 2.0.2-1/src/libbson/tests/json/bson_binary_vector/int8.json
--- 1.30.4-1/src/libbson/tests/json/bson_binary_vector/int8.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/json/bson_binary_vector/int8.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,57 @@
+{
+  "description": "Tests of Binary subtype 9, Vectors, with dtype INT8",
+  "test_key": "vector",
+  "tests": [
+    {
+      "description": "Simple Vector INT8",
+      "valid": true,
+      "vector": [127, 7],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 0,
+      "canonical_bson": "1600000005766563746F7200040000000903007F0700"
+    },
+    {
+      "description": "Empty Vector INT8",
+      "valid": true,
+      "vector": [],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 0,
+      "canonical_bson": "1400000005766563746F72000200000009030000"
+    },
+    {
+      "description": "Overflow Vector INT8",
+      "valid": false,
+      "vector": [128],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 0
+    },
+    {
+      "description": "Underflow Vector INT8",
+      "valid": false,
+      "vector": [-129],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 0
+    },
+    {
+      "description": "INT8 with padding",
+      "valid": false,
+      "vector": [127, 7],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 3,
+      "canonical_bson": "1600000005766563746F7200040000000903037F0700"
+    },
+    {
+      "description": "INT8 with float inputs",
+      "valid": false,
+      "vector": [127.77, 7.77],
+      "dtype_hex": "0x03",
+      "dtype_alias": "INT8",
+      "padding": 0
+    }
+  ]
+}
diff -pruN 1.30.4-1/src/libbson/tests/json/bson_binary_vector/packed_bit.json 2.0.2-1/src/libbson/tests/json/bson_binary_vector/packed_bit.json
--- 1.30.4-1/src/libbson/tests/json/bson_binary_vector/packed_bit.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/json/bson_binary_vector/packed_bit.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,83 @@
+{
+  "description": "Tests of Binary subtype 9, Vectors, with dtype PACKED_BIT",
+  "test_key": "vector",
+  "tests": [
+    {
+      "description": "Padding specified with no vector data PACKED_BIT",
+      "valid": false,
+      "vector": [],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 1,
+      "canonical_bson": "1400000005766563746F72000200000009100100"
+    },
+    {
+      "description": "Simple Vector PACKED_BIT",
+      "valid": true,
+      "vector": [127, 7],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 0,
+      "canonical_bson": "1600000005766563746F7200040000000910007F0700"
+    },
+    {
+      "description": "Empty Vector PACKED_BIT",
+      "valid": true,
+      "vector": [],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 0,
+      "canonical_bson": "1400000005766563746F72000200000009100000"
+    },
+    {
+      "description": "PACKED_BIT with padding",
+      "valid": true,
+      "vector": [127, 7],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 3,
+      "canonical_bson": "1600000005766563746F7200040000000910037F0700"
+    },
+    {
+      "description": "Overflow Vector PACKED_BIT",
+      "valid": false,
+      "vector": [256],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 0
+    },
+    {
+      "description": "Underflow Vector PACKED_BIT",
+      "valid": false,
+      "vector": [-1],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 0
+    },
+    {
+      "description": "Vector with float values PACKED_BIT",
+      "valid": false,
+      "vector": [127.5],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 0
+    },
+    {
+      "description": "Exceeding maximum padding PACKED_BIT",
+      "valid": false,
+      "vector": [1],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": 8,
+      "canonical_bson": "1500000005766563746F7200030000000910080100"
+    },
+    {
+      "description": "Negative padding PACKED_BIT",
+      "valid": false,
+      "vector": [1],
+      "dtype_hex": "0x10",
+      "dtype_alias": "PACKED_BIT",
+      "padding": -1
+    }
+  ]
+}
diff -pruN 1.30.4-1/src/libbson/tests/json/bson_corpus/binary.json 2.0.2-1/src/libbson/tests/json/bson_corpus/binary.json
--- 1.30.4-1/src/libbson/tests/json/bson_corpus/binary.json	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/json/bson_corpus/binary.json	2025-06-19 15:42:22.000000000 +0000
@@ -74,6 +74,36 @@
             "description": "$type query operator (conflicts with legacy $binary form with $type field)",
             "canonical_bson": "180000000378001000000010247479706500020000000000",
             "canonical_extjson": "{\"x\" : { \"$type\" : {\"$numberInt\": \"2\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector FLOAT32",
+            "canonical_bson": "170000000578000A0000000927000000FE420000E04000",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"JwAAAP5CAADgQA==\", \"subType\": \"09\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector INT8",
+            "canonical_bson": "11000000057800040000000903007F0700",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"AwB/Bw==\", \"subType\": \"09\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector PACKED_BIT",
+            "canonical_bson": "11000000057800040000000910007F0700",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"EAB/Bw==\", \"subType\": \"09\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector (Zero-length) FLOAT32",
+            "canonical_bson": "0F0000000578000200000009270000",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"JwA=\", \"subType\": \"09\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector (Zero-length) INT8",
+            "canonical_bson": "0F0000000578000200000009030000",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"AwA=\", \"subType\": \"09\"}}}"
+        },
+        {
+            "description": "subtype 0x09 Vector (Zero-length) PACKED_BIT",
+            "canonical_bson": "0F0000000578000200000009100000",
+            "canonical_extjson": "{\"x\": {\"$binary\": {\"base64\": \"EAA=\", \"subType\": \"09\"}}}"
         }
     ],
     "decodeErrors": [
diff -pruN 1.30.4-1/src/libbson/tests/json/bson_corpus/top.json 2.0.2-1/src/libbson/tests/json/bson_corpus/top.json
--- 1.30.4-1/src/libbson/tests/json/bson_corpus/top.json	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/json/bson_corpus/top.json	2025-06-19 15:42:22.000000000 +0000
@@ -96,11 +96,11 @@
         },
         {
             "description": "Bad $regularExpression (pattern is number, not string)",
-            "string": "{\"x\" : {\"$regularExpression\" : { \"pattern\": 42, \"$options\" : \"\"}}}"
+            "string": "{\"x\" : {\"$regularExpression\" : { \"pattern\": 42, \"options\" : \"\"}}}"
         },
         {
             "description": "Bad $regularExpression (options are number, not string)",
-            "string": "{\"x\" : {\"$regularExpression\" : { \"pattern\": \"a\", \"$options\" : 0}}}"
+            "string": "{\"x\" : {\"$regularExpression\" : { \"pattern\": \"a\", \"options\" : 0}}}"
         },
         {
             "description" : "Bad $regularExpression (missing pattern field)",
diff -pruN 1.30.4-1/src/libbson/tests/test-atomic.c 2.0.2-1/src/libbson/tests/test-atomic.c
--- 1.30.4-1/src/libbson/tests/test-atomic.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-atomic.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,127 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <bson/bson.h>
-
-#include "TestSuite.h"
-
-#define ATOMIC(Kind, Operation) BSON_CONCAT4 (bson_atomic_, Kind, _, Operation)
-
-
-#define TEST_KIND_WITH_MEMORDER(Kind, TypeName, MemOrder, Assert)              \
-   do {                                                                        \
-      int i;                                                                   \
-      TypeName got;                                                            \
-      TypeName value = 0;                                                      \
-      got = ATOMIC (Kind, fetch) (&value, MemOrder);                           \
-      Assert (got, ==, 0);                                                     \
-      got = ATOMIC (Kind, fetch_add) (&value, 42, MemOrder);                   \
-      Assert (got, ==, 0);                                                     \
-      Assert (value, ==, 42);                                                  \
-      got = ATOMIC (Kind, fetch_sub) (&value, 7, MemOrder);                    \
-      Assert (got, ==, 42);                                                    \
-      Assert (value, ==, 35);                                                  \
-      got = ATOMIC (Kind, exchange) (&value, 77, MemOrder);                    \
-      Assert (got, ==, 35);                                                    \
-      Assert (value, ==, 77);                                                  \
-      /* Compare-exchange fail: */                                             \
-      got = ATOMIC (Kind, compare_exchange_strong) (&value, 4, 9, MemOrder);   \
-      Assert (got, ==, 77);                                                    \
-      Assert (value, ==, 77);                                                  \
-      /* Compare-exchange succeed: */                                          \
-      got = ATOMIC (Kind, compare_exchange_strong) (&value, 77, 9, MemOrder);  \
-      Assert (got, ==, 77);                                                    \
-      Assert (value, ==, 9);                                                   \
-      /* Compare-exchange fail: */                                             \
-      got = ATOMIC (Kind, compare_exchange_weak) (&value, 8, 12, MemOrder);    \
-      Assert (got, ==, 9);                                                     \
-      Assert (value, ==, 9);                                                   \
-      /* Compare-exchange-weak succeed: */                                     \
-      /* 'weak' may fail spuriously, so it must *eventually* succeed */        \
-      for (i = 0; i < 10000 && value != 53; ++i) {                             \
-         got = ATOMIC (Kind, compare_exchange_weak) (&value, 9, 53, MemOrder); \
-         Assert (got, ==, 9);                                                  \
-      }                                                                        \
-      /* Check that it evenutally succeeded */                                 \
-      Assert (value, ==, 53);                                                  \
-   } while (0)
-
-#define TEST_INTEGER_KIND(Kind, TypeName, Assert)                                  \
-   do {                                                                            \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_relaxed, Assert); \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_acq_rel, Assert); \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_acquire, Assert); \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_release, Assert); \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_consume, Assert); \
-      TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_seq_cst, Assert); \
-   } while (0)
-
-
-static void
-test_integers (void)
-{
-   TEST_INTEGER_KIND (int64, int64_t, ASSERT_CMPINT64);
-   TEST_INTEGER_KIND (int32, int32_t, ASSERT_CMPINT32);
-   TEST_INTEGER_KIND (int16, int16_t, ASSERT_CMPINT);
-   TEST_INTEGER_KIND (int8, int8_t, ASSERT_CMPINT);
-   TEST_INTEGER_KIND (int, int, ASSERT_CMPINT);
-}
-
-
-static void
-test_pointers (void)
-{
-   int u = 12;
-   int v = 9;
-   int w = 91;
-   int *ptr = &v;
-   int *other;
-   int *prev;
-   other = bson_atomic_ptr_fetch ((void *) &ptr, bson_memory_order_relaxed);
-   ASSERT_CMPVOID (other, ==, ptr);
-   prev = bson_atomic_ptr_exchange ((void *) &other, &u, bson_memory_order_relaxed);
-   ASSERT_CMPVOID (prev, ==, &v);
-   ASSERT_CMPVOID (other, ==, &u);
-   prev = bson_atomic_ptr_compare_exchange_strong ((void *) &other, &v, &w, bson_memory_order_relaxed);
-   ASSERT_CMPVOID (prev, ==, &u);
-   ASSERT_CMPVOID (other, ==, &u);
-   prev = bson_atomic_ptr_compare_exchange_strong ((void *) &other, &u, &w, bson_memory_order_relaxed);
-   ASSERT_CMPVOID (prev, ==, &u);
-   ASSERT_CMPVOID (other, ==, &w);
-}
-
-
-static void
-test_thread_fence (void)
-{
-   bson_atomic_thread_fence ();
-}
-
-static void
-test_thrd_yield (void)
-{
-   bson_thrd_yield ();
-}
-
-void
-test_atomic_install (TestSuite *suite)
-{
-   TestSuite_Add (suite, "/atomic/integers", test_integers);
-   TestSuite_Add (suite, "/atomic/pointers", test_pointers);
-   TestSuite_Add (suite, "/atomic/thread_fence", test_thread_fence);
-   TestSuite_Add (suite, "/atomic/thread_yield", test_thrd_yield);
-}
diff -pruN 1.30.4-1/src/libbson/tests/test-b64.c 2.0.2-1/src/libbson/tests/test-b64.c
--- 1.30.4-1/src/libbson/tests/test-b64.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-b64.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,7 +18,7 @@
 
 #include "TestSuite.h"
 #include <common-b64-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 static void
 _test_encode_helper (char *input, size_t input_len, char *expected_output, int expected_output_len)
@@ -34,7 +34,7 @@ _test_encode_helper (char *input, size_t
    ASSERT_CMPSIZE_T (target_size, ==, (size_t) expected_output_len + 1);
    /* returned value does not count trailing NULL. */
    ret = mcommon_b64_ntop ((uint8_t *) input, input_len, output, target_size);
-   ASSERT (mcommon_cmp_equal_us (target_size - 1u, ret));
+   ASSERT (mlib_cmp (target_size - 1u, ==, ret));
    ASSERT_CMPSTR (output, expected_output);
    bson_free (output);
 }
diff -pruN 1.30.4-1/src/libbson/tests/test-bson-cmp.c 2.0.2-1/src/libbson/tests/test-bson-cmp.c
--- 1.30.4-1/src/libbson/tests/test-bson-cmp.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-bson-cmp.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,308 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "TestSuite.h"
-
-#include <bson/bson.h>
-
-static void
-test_bson_cmp_equal (void)
-{
-   BSON_ASSERT (bson_cmp_equal_ss (0, 0));
-   BSON_ASSERT (!bson_cmp_equal_ss (0, -1));
-   BSON_ASSERT (!bson_cmp_equal_ss (0, 1));
-   BSON_ASSERT (!bson_cmp_equal_ss (-1, 0));
-   BSON_ASSERT (bson_cmp_equal_ss (-1, -1));
-   BSON_ASSERT (!bson_cmp_equal_ss (-1, 1));
-   BSON_ASSERT (!bson_cmp_equal_ss (1, 0));
-   BSON_ASSERT (!bson_cmp_equal_ss (1, -1));
-   BSON_ASSERT (bson_cmp_equal_ss (1, 1));
-
-   BSON_ASSERT (bson_cmp_equal_uu (0u, 0u));
-   BSON_ASSERT (!bson_cmp_equal_uu (0u, 1u));
-   BSON_ASSERT (!bson_cmp_equal_uu (1u, 0u));
-   BSON_ASSERT (bson_cmp_equal_uu (1u, 1u));
-
-   BSON_ASSERT (bson_cmp_equal_su (0, 0u));
-   BSON_ASSERT (!bson_cmp_equal_su (0, 1u));
-   BSON_ASSERT (!bson_cmp_equal_su (-1, 0u));
-   BSON_ASSERT (!bson_cmp_equal_su (-1, 1u));
-   BSON_ASSERT (!bson_cmp_equal_su (1, 0u));
-   BSON_ASSERT (bson_cmp_equal_su (1, 1u));
-
-   BSON_ASSERT (bson_cmp_equal_us (0u, 0));
-   BSON_ASSERT (!bson_cmp_equal_us (0u, -1));
-   BSON_ASSERT (!bson_cmp_equal_us (0u, 1));
-   BSON_ASSERT (!bson_cmp_equal_us (1u, 0));
-   BSON_ASSERT (!bson_cmp_equal_us (1u, -1));
-   BSON_ASSERT (bson_cmp_equal_us (1u, 1));
-}
-
-static void
-test_bson_cmp_not_equal (void)
-{
-   BSON_ASSERT (!bson_cmp_not_equal_ss (0, 0));
-   BSON_ASSERT (bson_cmp_not_equal_ss (0, -1));
-   BSON_ASSERT (bson_cmp_not_equal_ss (0, 1));
-   BSON_ASSERT (bson_cmp_not_equal_ss (-1, 0));
-   BSON_ASSERT (!bson_cmp_not_equal_ss (-1, -1));
-   BSON_ASSERT (bson_cmp_not_equal_ss (-1, 1));
-   BSON_ASSERT (bson_cmp_not_equal_ss (1, 0));
-   BSON_ASSERT (bson_cmp_not_equal_ss (1, -1));
-   BSON_ASSERT (!bson_cmp_not_equal_ss (1, 1));
-
-   BSON_ASSERT (!bson_cmp_not_equal_uu (0u, 0u));
-   BSON_ASSERT (bson_cmp_not_equal_uu (0u, 1u));
-   BSON_ASSERT (bson_cmp_not_equal_uu (1u, 0u));
-   BSON_ASSERT (!bson_cmp_not_equal_uu (1u, 1u));
-
-   BSON_ASSERT (!bson_cmp_not_equal_su (0, 0u));
-   BSON_ASSERT (bson_cmp_not_equal_su (0, 1u));
-   BSON_ASSERT (bson_cmp_not_equal_su (-1, 0u));
-   BSON_ASSERT (bson_cmp_not_equal_su (-1, 1u));
-   BSON_ASSERT (bson_cmp_not_equal_su (1, 0u));
-   BSON_ASSERT (!bson_cmp_not_equal_su (1, 1u));
-
-   BSON_ASSERT (!bson_cmp_not_equal_us (0u, 0));
-   BSON_ASSERT (bson_cmp_not_equal_us (0u, -1));
-   BSON_ASSERT (bson_cmp_not_equal_us (0u, 1));
-   BSON_ASSERT (bson_cmp_not_equal_us (1u, 0));
-   BSON_ASSERT (bson_cmp_not_equal_us (1u, -1));
-   BSON_ASSERT (!bson_cmp_not_equal_us (1u, 1));
-}
-
-static void
-test_bson_cmp_less (void)
-{
-   BSON_ASSERT (!bson_cmp_less_ss (0, 0));
-   BSON_ASSERT (!bson_cmp_less_ss (0, -1));
-   BSON_ASSERT (bson_cmp_less_ss (0, 1));
-   BSON_ASSERT (bson_cmp_less_ss (-1, 0));
-   BSON_ASSERT (!bson_cmp_less_ss (-1, -1));
-   BSON_ASSERT (bson_cmp_less_ss (-1, 1));
-   BSON_ASSERT (!bson_cmp_less_ss (1, 0));
-   BSON_ASSERT (!bson_cmp_less_ss (1, -1));
-   BSON_ASSERT (!bson_cmp_less_ss (1, 1));
-
-   BSON_ASSERT (!bson_cmp_less_uu (0u, 0u));
-   BSON_ASSERT (bson_cmp_less_uu (0u, 1u));
-   BSON_ASSERT (!bson_cmp_less_uu (1u, 0u));
-   BSON_ASSERT (!bson_cmp_less_uu (1u, 1u));
-
-   BSON_ASSERT (!bson_cmp_less_su (0, 0u));
-   BSON_ASSERT (bson_cmp_less_su (0, 1u));
-   BSON_ASSERT (bson_cmp_less_su (-1, 0u));
-   BSON_ASSERT (bson_cmp_less_su (-1, 1u));
-   BSON_ASSERT (!bson_cmp_less_su (1, 0u));
-   BSON_ASSERT (!bson_cmp_less_su (1, 1u));
-
-   BSON_ASSERT (!bson_cmp_less_us (0u, 0));
-   BSON_ASSERT (!bson_cmp_less_us (0u, -1));
-   BSON_ASSERT (bson_cmp_less_us (0u, 1));
-   BSON_ASSERT (!bson_cmp_less_us (1u, 0));
-   BSON_ASSERT (!bson_cmp_less_us (1u, -1));
-   BSON_ASSERT (!bson_cmp_less_us (1u, 1));
-}
-
-static void
-test_bson_cmp_greater (void)
-{
-   BSON_ASSERT (!bson_cmp_greater_ss (0, 0));
-   BSON_ASSERT (bson_cmp_greater_ss (0, -1));
-   BSON_ASSERT (!bson_cmp_greater_ss (0, 1));
-   BSON_ASSERT (!bson_cmp_greater_ss (-1, 0));
-   BSON_ASSERT (!bson_cmp_greater_ss (-1, -1));
-   BSON_ASSERT (!bson_cmp_greater_ss (-1, 1));
-   BSON_ASSERT (bson_cmp_greater_ss (1, 0));
-   BSON_ASSERT (bson_cmp_greater_ss (1, -1));
-   BSON_ASSERT (!bson_cmp_greater_ss (1, 1));
-
-   BSON_ASSERT (!bson_cmp_greater_uu (0u, 0u));
-   BSON_ASSERT (!bson_cmp_greater_uu (0u, 1u));
-   BSON_ASSERT (bson_cmp_greater_uu (1u, 0u));
-   BSON_ASSERT (!bson_cmp_greater_uu (1u, 1u));
-
-   BSON_ASSERT (!bson_cmp_greater_su (0, 0u));
-   BSON_ASSERT (!bson_cmp_greater_su (0, 1u));
-   BSON_ASSERT (!bson_cmp_greater_su (-1, 0u));
-   BSON_ASSERT (!bson_cmp_greater_su (-1, 1u));
-   BSON_ASSERT (bson_cmp_greater_su (1, 0u));
-   BSON_ASSERT (!bson_cmp_greater_su (1, 1u));
-
-   BSON_ASSERT (!bson_cmp_greater_us (0u, 0));
-   BSON_ASSERT (bson_cmp_greater_us (0u, -1));
-   BSON_ASSERT (!bson_cmp_greater_us (0u, 1));
-   BSON_ASSERT (bson_cmp_greater_us (1u, 0));
-   BSON_ASSERT (bson_cmp_greater_us (1u, -1));
-   BSON_ASSERT (!bson_cmp_greater_us (1u, 1));
-}
-
-static void
-test_bson_cmp_less_equal (void)
-{
-   BSON_ASSERT (bson_cmp_less_equal_ss (0, 0));
-   BSON_ASSERT (!bson_cmp_less_equal_ss (0, -1));
-   BSON_ASSERT (bson_cmp_less_equal_ss (0, 1));
-   BSON_ASSERT (bson_cmp_less_equal_ss (-1, 0));
-   BSON_ASSERT (bson_cmp_less_equal_ss (-1, -1));
-   BSON_ASSERT (bson_cmp_less_equal_ss (-1, 1));
-   BSON_ASSERT (!bson_cmp_less_equal_ss (1, 0));
-   BSON_ASSERT (!bson_cmp_less_equal_ss (1, -1));
-   BSON_ASSERT (bson_cmp_less_equal_ss (1, 1));
-
-   BSON_ASSERT (bson_cmp_less_equal_uu (0u, 0u));
-   BSON_ASSERT (bson_cmp_less_equal_uu (0u, 1u));
-   BSON_ASSERT (!bson_cmp_less_equal_uu (1u, 0u));
-   BSON_ASSERT (bson_cmp_less_equal_uu (1u, 1u));
-
-   BSON_ASSERT (bson_cmp_less_equal_su (0, 0u));
-   BSON_ASSERT (bson_cmp_less_equal_su (0, 1u));
-   BSON_ASSERT (bson_cmp_less_equal_su (-1, 0u));
-   BSON_ASSERT (bson_cmp_less_equal_su (-1, 1u));
-   BSON_ASSERT (!bson_cmp_less_equal_su (1, 0u));
-   BSON_ASSERT (bson_cmp_less_equal_su (1, 1u));
-
-   BSON_ASSERT (bson_cmp_less_equal_us (0u, 0));
-   BSON_ASSERT (!bson_cmp_less_equal_us (0u, -1));
-   BSON_ASSERT (bson_cmp_less_equal_us (0u, 1));
-   BSON_ASSERT (!bson_cmp_less_equal_us (1u, 0));
-   BSON_ASSERT (!bson_cmp_less_equal_us (1u, -1));
-   BSON_ASSERT (bson_cmp_less_equal_us (1u, 1));
-}
-
-static void
-test_bson_cmp_greater_equal (void)
-{
-   BSON_ASSERT (bson_cmp_greater_equal_ss (0, 0));
-   BSON_ASSERT (bson_cmp_greater_equal_ss (0, -1));
-   BSON_ASSERT (!bson_cmp_greater_equal_ss (0, 1));
-   BSON_ASSERT (!bson_cmp_greater_equal_ss (-1, 0));
-   BSON_ASSERT (bson_cmp_greater_equal_ss (-1, -1));
-   BSON_ASSERT (!bson_cmp_greater_equal_ss (-1, 1));
-   BSON_ASSERT (bson_cmp_greater_equal_ss (1, 0));
-   BSON_ASSERT (bson_cmp_greater_equal_ss (1, -1));
-   BSON_ASSERT (bson_cmp_greater_equal_ss (1, 1));
-
-   BSON_ASSERT (bson_cmp_greater_equal_uu (0u, 0u));
-   BSON_ASSERT (!bson_cmp_greater_equal_uu (0u, 1u));
-   BSON_ASSERT (bson_cmp_greater_equal_uu (1u, 0u));
-   BSON_ASSERT (bson_cmp_greater_equal_uu (1u, 1u));
-
-   BSON_ASSERT (bson_cmp_greater_equal_su (0, 0u));
-   BSON_ASSERT (!bson_cmp_greater_equal_su (0, 1u));
-   BSON_ASSERT (!bson_cmp_greater_equal_su (-1, 0u));
-   BSON_ASSERT (!bson_cmp_greater_equal_su (-1, 1u));
-   BSON_ASSERT (bson_cmp_greater_equal_su (1, 0u));
-   BSON_ASSERT (bson_cmp_greater_equal_su (1, 1u));
-
-   BSON_ASSERT (bson_cmp_greater_equal_us (0u, 0));
-   BSON_ASSERT (bson_cmp_greater_equal_us (0u, -1));
-   BSON_ASSERT (!bson_cmp_greater_equal_us (0u, 1));
-   BSON_ASSERT (bson_cmp_greater_equal_us (1u, 0));
-   BSON_ASSERT (bson_cmp_greater_equal_us (1u, -1));
-   BSON_ASSERT (bson_cmp_greater_equal_us (1u, 1));
-}
-
-/* Sanity check: ensure ssize_t limits are as expected relative to size_t. */
-BSON_STATIC_ASSERT2 (ssize_t_size_min_check, SSIZE_MIN + 1 == -SSIZE_MAX);
-BSON_STATIC_ASSERT2 (ssize_t_size_max_check, (size_t) SSIZE_MAX <= SIZE_MAX);
-
-static void
-test_bson_in_range (void)
-{
-   const int64_t int8_min = INT8_MIN;
-   const int64_t int8_max = INT8_MAX;
-   const int64_t int32_min = INT32_MIN;
-   const int64_t int32_max = INT32_MAX;
-
-   const uint64_t uint8_max = UINT8_MAX;
-   const uint64_t uint32_max = UINT32_MAX;
-
-   const ssize_t ssize_min = SSIZE_MIN;
-   const ssize_t ssize_max = SSIZE_MAX;
-
-   BSON_ASSERT (!bson_in_range_signed (int8_t, int8_min - 1));
-   BSON_ASSERT (bson_in_range_signed (int8_t, int8_min));
-   BSON_ASSERT (bson_in_range_signed (int8_t, 0));
-   BSON_ASSERT (bson_in_range_signed (int8_t, int8_max));
-   BSON_ASSERT (!bson_in_range_signed (int8_t, int8_max + 1));
-
-   BSON_ASSERT (bson_in_range_unsigned (int8_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (int8_t, (uint64_t) int8_max));
-   BSON_ASSERT (!bson_in_range_unsigned (int8_t, (uint64_t) (int8_max + 1)));
-
-   BSON_ASSERT (!bson_in_range_signed (uint8_t, int8_min - 1));
-   BSON_ASSERT (!bson_in_range_signed (uint8_t, int8_min));
-   BSON_ASSERT (bson_in_range_signed (uint8_t, 0));
-   BSON_ASSERT (bson_in_range_signed (uint8_t, int8_max));
-   BSON_ASSERT (bson_in_range_signed (uint8_t, int8_max + 1));
-   BSON_ASSERT (bson_in_range_signed (uint8_t, (int64_t) uint8_max));
-   BSON_ASSERT (!bson_in_range_signed (uint8_t, (int64_t) uint8_max + 1));
-
-   BSON_ASSERT (bson_in_range_unsigned (uint8_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (uint8_t, uint8_max));
-   BSON_ASSERT (!bson_in_range_unsigned (uint8_t, uint8_max + 1u));
-
-   BSON_ASSERT (!bson_in_range_signed (int32_t, int32_min - 1));
-   BSON_ASSERT (bson_in_range_signed (int32_t, int32_min));
-   BSON_ASSERT (bson_in_range_signed (int32_t, 0));
-   BSON_ASSERT (bson_in_range_signed (int32_t, int32_max));
-   BSON_ASSERT (!bson_in_range_signed (int32_t, int32_max + 1));
-
-   BSON_ASSERT (bson_in_range_unsigned (int32_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (int32_t, (uint64_t) int32_max));
-   BSON_ASSERT (!bson_in_range_unsigned (int32_t, (uint64_t) (int32_max + 1)));
-
-   BSON_ASSERT (!bson_in_range_signed (uint32_t, int32_min - 1));
-   BSON_ASSERT (!bson_in_range_signed (uint32_t, int32_min));
-   BSON_ASSERT (bson_in_range_signed (uint32_t, 0));
-   BSON_ASSERT (bson_in_range_signed (uint32_t, int32_max));
-   BSON_ASSERT (bson_in_range_signed (uint32_t, int32_max + 1));
-   BSON_ASSERT (bson_in_range_signed (uint32_t, (int64_t) uint32_max));
-   BSON_ASSERT (!bson_in_range_signed (uint32_t, (int64_t) uint32_max + 1));
-
-   BSON_ASSERT (bson_in_range_unsigned (uint32_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (uint32_t, uint32_max));
-   BSON_ASSERT (!bson_in_range_unsigned (uint32_t, uint32_max + 1u));
-
-   BSON_ASSERT (bson_in_range_signed (ssize_t, ssize_min));
-   BSON_ASSERT (bson_in_range_signed (ssize_t, 0));
-   BSON_ASSERT (bson_in_range_signed (ssize_t, ssize_max));
-
-   BSON_ASSERT (bson_in_range_unsigned (ssize_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (ssize_t, (size_t) ssize_max));
-   BSON_ASSERT (!bson_in_range_unsigned (ssize_t, (size_t) ssize_max + 1u));
-
-   BSON_ASSERT (!bson_in_range_signed (size_t, ssize_min));
-   BSON_ASSERT (bson_in_range_signed (size_t, 0));
-   BSON_ASSERT (bson_in_range_signed (size_t, ssize_max));
-
-   BSON_ASSERT (bson_in_range_unsigned (size_t, 0u));
-   BSON_ASSERT (bson_in_range_unsigned (size_t, (size_t) ssize_max));
-   BSON_ASSERT (bson_in_range_unsigned (size_t, (size_t) ssize_max + 1u));
-}
-
-void
-test_bson_cmp_install (TestSuite *suite)
-{
-   TestSuite_Add (suite, "/bson/cmp/equal", test_bson_cmp_equal);
-   TestSuite_Add (suite, "/bson/cmp/not_equal", test_bson_cmp_not_equal);
-   TestSuite_Add (suite, "/bson/cmp/less", test_bson_cmp_less);
-   TestSuite_Add (suite, "/bson/cmp/greater", test_bson_cmp_greater);
-   TestSuite_Add (suite, "/bson/cmp/less_equal", test_bson_cmp_less_equal);
-   TestSuite_Add (suite, "/bson/cmp/greater_equal", test_bson_cmp_greater_equal);
-   TestSuite_Add (suite, "/bson/cmp/in_range", test_bson_in_range);
-}
diff -pruN 1.30.4-1/src/libbson/tests/test-bson-error.c 2.0.2-1/src/libbson/tests/test-bson-error.c
--- 1.30.4-1/src/libbson/tests/test-bson-error.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-bson-error.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,10 +24,11 @@ test_bson_error_basic (void)
 {
    bson_error_t error;
 
-   bson_set_error (&error, 123, 456, "%s %d", "localhost", 27017);
-   BSON_ASSERT (!strcmp (error.message, "localhost 27017"));
+   bson_set_error (&error, 123, 456, "%s:%d", "localhost", 27017);
+   ASSERT_CMPSTR (error.message, "localhost:27017");
    ASSERT_CMPUINT32 (error.domain, ==, 123u);
    ASSERT_CMPUINT32 (error.code, ==, 456u);
+   ASSERT_CMPUINT (error.reserved, ==, 1u); // BSON_ERROR_CATEGORY
 }
 
 static void
@@ -39,6 +40,10 @@ test_bson_strerror_r (void)
    char *errmsg = bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf);
    // Check a message is returned. Do not check platform-dependent contents:
    ASSERT (errmsg);
+   const char *unknown_msg = "Unknown error";
+   if (strstr (errmsg, unknown_msg)) {
+      test_error ("Expected error message to contain platform-dependent content, not: '%s'", errmsg);
+   }
 }
 
 void
diff -pruN 1.30.4-1/src/libbson/tests/test-bson-sync.c 2.0.2-1/src/libbson/tests/test-bson-sync.c
--- 1.30.4-1/src/libbson/tests/test-bson-sync.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-bson-sync.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <bson/bson.h>
-#include <common-macros-private.h> // BEGIN_IGNORE_DEPRECATIONS
-
-#include "TestSuite.h"
-
-static void
-test_bson_sync_synchronize (void)
-{
-   BEGIN_IGNORE_DEPRECATIONS
-
-   // This doesn't test for correct functionality, only that it exists and can be called
-   bson_sync_synchronize ();
-
-   END_IGNORE_DEPRECATIONS
-}
-
-void
-test_bson_sync_install (TestSuite *suite)
-{
-   TestSuite_Add (suite, "/bson/sync/synchronize", test_bson_sync_synchronize);
-}
diff -pruN 1.30.4-1/src/libbson/tests/test-bson-vector.c 2.0.2-1/src/libbson/tests/test-bson-vector.c
--- 1.30.4-1/src/libbson/tests/test-bson-vector.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-bson-vector.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,1572 @@
+/*
+ * Copyright 2009-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <bson/bson.h>
+
+#include "bsonutil/bson-parser.h"
+#include "TestSuite.h"
+#include "test-conveniences.h"
+#include "json-test.h"
+
+#ifdef _MSC_VER
+#define SSCANF sscanf_s
+#else
+#define SSCANF sscanf
+#endif
+
+struct view_abi_reference_type {
+   void *data;
+   uint32_t data_len;
+   uint8_t header_0;
+   uint8_t header_1;
+};
+
+/* ABI: Make sure vector views have the expected size. */
+#define EXPECTED_VECTOR_VIEW_SIZE (sizeof (struct view_abi_reference_type))
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_int8_const_view_t,
+                     sizeof (bson_vector_int8_const_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_int8_view_t, sizeof (bson_vector_int8_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_float32_const_view_t,
+                     sizeof (bson_vector_float32_const_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_float32_view_t,
+                     sizeof (bson_vector_float32_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_packed_bit_const_view_t,
+                     sizeof (bson_vector_packed_bit_const_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+BSON_STATIC_ASSERT2 (sizeof_bson_vector_packed_bit_view_t,
+                     sizeof (bson_vector_packed_bit_view_t) == EXPECTED_VECTOR_VIEW_SIZE);
+#undef EXPECTED_VECTOR_VIEW_SIZE
+
+typedef struct vector_json_test_case_t {
+   char *scenario_description, *scenario_test_key;
+   char *test_description, *test_dtype_hex_str, *test_dtype_alias_str, *test_canonical_bson_str;
+   bson_t *test_vector_array;
+   int64_t *test_padding;
+   bool *test_valid;
+} vector_json_test_case_t;
+
+static bool
+append_vector_packed_bit_from_packed_array (
+   bson_t *bson, const char *key, int key_length, const bson_iter_t *iter, int64_t padding, bson_error_t *error)
+{
+   // (Spec test improvement TODO) This implements something the test covers that our API doesn't. If the test
+   // were modified to cover element-by-element conversion, this can be replaced with
+   // bson_append_vector_packed_bit_from_array.
+
+   BSON_ASSERT_PARAM (bson);
+   BSON_ASSERT_PARAM (key);
+   BSON_ASSERT_PARAM (iter);
+
+   size_t byte_count = 0;
+   {
+      bson_iter_t validation_iter = *iter;
+      while (bson_iter_next (&validation_iter)) {
+         if (!BSON_ITER_HOLDS_INT (&validation_iter)) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_TYPE,
+                            "expected int32 or int64 in BSON array key '%s', found item type 0x%02X",
+                            bson_iter_key (&validation_iter),
+                            (unsigned) bson_iter_type (&validation_iter));
+            return false;
+         }
+         int64_t byte_as_int64 = bson_iter_as_int64 (&validation_iter);
+         if (byte_as_int64 < 0 || byte_as_int64 > UINT8_MAX) {
+            bson_set_error (error,
+                            BSON_ERROR_VECTOR,
+                            BSON_VECTOR_ERROR_ARRAY_ELEMENT_VALUE,
+                            "BSON array key '%s' value %" PRId64 " is out of range for packed byte",
+                            bson_iter_key (&validation_iter),
+                            byte_as_int64);
+            return false;
+         }
+         byte_count++;
+      }
+   }
+
+   if (padding < 0 || padding > 7) {
+      bson_set_error (error,
+                      TEST_ERROR_DOMAIN,
+                      TEST_ERROR_CODE,
+                      "'padding' parameter (%" PRId64
+                      ") for append_vector_packed_bit_from_packed_array is out of range",
+                      padding);
+      return false;
+   }
+   if (byte_count < 1 && padding > 0) {
+      bson_set_error (error,
+                      TEST_ERROR_DOMAIN,
+                      TEST_ERROR_CODE,
+                      "nonzero 'padding' parameter (%" PRId64
+                      ") for zero-length append_vector_packed_bit_from_packed_array",
+                      padding);
+      return false;
+   }
+
+   bson_vector_packed_bit_view_t view;
+   if (bson_append_vector_packed_bit_uninit (bson, key, key_length, byte_count * 8u - (size_t) padding, &view)) {
+      bson_iter_t copy_iter = *iter;
+      for (size_t i = 0; i < byte_count; i++) {
+         ASSERT (bson_iter_next (&copy_iter));
+         uint8_t packed_byte = (uint8_t) bson_iter_as_int64 (&copy_iter);
+         ASSERT (bson_vector_packed_bit_view_write_packed (view, &packed_byte, 1, i));
+      }
+      return true;
+   } else {
+      return false;
+   }
+}
+
+static void
+hex_str_to_bson (bson_t *bson_out, const char *hex_str)
+{
+   uint32_t size = (uint32_t) strlen (hex_str) / 2u;
+   uint8_t *buffer = bson_reserve_buffer (bson_out, size);
+   for (uint32_t i = 0; i < size; i++) {
+      unsigned int byte;
+      ASSERT (SSCANF (&hex_str[i * 2], "%2x", &byte) == 1);
+      buffer[i] = (uint8_t) byte;
+   }
+}
+
+// Implement spec tests, given parsed arguments
+static void
+test_bson_vector_json_case (vector_json_test_case_t *test_case)
+{
+   bson_t expected_bson = BSON_INITIALIZER;
+   if (test_case->test_canonical_bson_str) {
+      hex_str_to_bson (&expected_bson, test_case->test_canonical_bson_str);
+   }
+
+   ASSERT (test_case->test_valid);
+   ASSERT (test_case->test_dtype_hex_str);
+   ASSERT (test_case->scenario_test_key);
+
+   bson_t vector_from_array = BSON_INITIALIZER;
+   bson_error_t vector_from_array_error;
+   bool vector_from_array_ok;
+
+   // (Spec test improvement TODO) Patch test cases that have unused bits set to '1' when '0' is required.
+   if (0 == strcmp ("PACKED_BIT with padding", test_case->test_description)) {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &expected_bson, test_case->scenario_test_key));
+      uint32_t binary_len;
+      uint8_t *binary;
+      bson_iter_overwrite_binary (&iter, BSON_SUBTYPE_VECTOR, &binary_len, &binary);
+      ASSERT (binary_len > BSON_VECTOR_HEADER_LEN);
+      binary[binary_len - 1] &= (uint8_t) 0xFF << bson_vector_padding_from_header_byte_1 (binary[1]);
+   }
+
+   // Try a format conversion from array to the indicated vector format.
+   // The spec calls the first header byte "dtype" (combining the element type and element size fields)
+   if (0 == strcmp ("0x03", test_case->test_dtype_hex_str)) {
+      // int8 vector from int32/int64 array
+      bson_iter_t iter;
+      bool padding_ok = !test_case->test_padding || *test_case->test_padding == 0;
+      vector_from_array_ok = test_case->test_vector_array && padding_ok &&
+                             bson_iter_init (&iter, test_case->test_vector_array) &&
+                             BSON_APPEND_VECTOR_INT8_FROM_ARRAY (
+                                &vector_from_array, test_case->scenario_test_key, &iter, &vector_from_array_error);
+   } else if (0 == strcmp ("0x27", test_case->test_dtype_hex_str)) {
+      // float32 vector from float64 array
+      bson_iter_t iter;
+      bool padding_ok = !test_case->test_padding || *test_case->test_padding == 0;
+      vector_from_array_ok = test_case->test_vector_array && padding_ok &&
+                             bson_iter_init (&iter, test_case->test_vector_array) &&
+                             BSON_APPEND_VECTOR_FLOAT32_FROM_ARRAY (
+                                &vector_from_array, test_case->scenario_test_key, &iter, &vector_from_array_error);
+   } else if (0 == strcmp ("0x10", test_case->test_dtype_hex_str)) {
+      // packed_bit from packed bytes in an int array, with "padding" parameter supplied separately.
+      // Suggested changes to reduce the special cases here:
+      //  - Array-to-Vector should be defined as an element-by-element conversion. This test shouldn't operate on packed
+      //  representations.
+      //  - Include additional JSON tests for packed access, distinct from Array conversion.
+      //  - Tests should keep the unused bits zeroed as required.
+      // (Spec test improvement TODO)
+      bson_iter_t iter;
+      if (!test_case->test_padding) {
+         test_error ("test '%s' is missing required 'padding' field", test_case->test_description);
+      }
+      vector_from_array_ok = test_case->test_vector_array && bson_iter_init (&iter, test_case->test_vector_array) &&
+                             append_vector_packed_bit_from_packed_array (&vector_from_array,
+                                                                         test_case->scenario_test_key,
+                                                                         -1,
+                                                                         &iter,
+                                                                         *test_case->test_padding,
+                                                                         &vector_from_array_error);
+   } else {
+      test_error (
+         "test '%s' has unsupported dtype_hex format '%s'", test_case->test_description, test_case->test_dtype_hex_str);
+   }
+
+   if (*test_case->test_valid) {
+      /*
+       * "To prove correct in a valid case (valid: true), one MUST
+       * - encode a document from the numeric values, dtype, and padding, along with the "test_key", and assert this
+       * matches the canonical_bson string.
+       * - decode the canonical_bson into its binary form, and then assert that the numeric values, dtype, and padding
+       * all match those provided in the JSON."
+       */
+
+      // Check the vector-from-array performed above ("encode")
+
+      if (!test_case->test_vector_array) {
+         test_error ("test '%s' should be valid, but missing 'vector' field", test_case->test_description);
+      }
+
+      if (!vector_from_array_ok) {
+         test_error ("test '%s' should be valid, but vector-from-array failed: %s",
+                     test_case->test_description,
+                     vector_from_array_error.message);
+      }
+
+      if (0 != bson_compare (&vector_from_array, &expected_bson)) {
+         test_error ("test '%s' did not exactly match the reference document.\n "
+                     "Actual: %s\n Expected: %s",
+                     test_case->test_description,
+                     tmp_json (&vector_from_array),
+                     tmp_json (&expected_bson));
+      }
+
+      // Perform an array-from-vector and check it ("decode")
+
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &expected_bson, test_case->scenario_test_key));
+
+      bson_t array_from_vector = BSON_INITIALIZER;
+      {
+         bson_array_builder_t *array_builder = bson_array_builder_new ();
+         if (!bson_array_builder_append_vector_elements (array_builder, &iter)) {
+            test_error ("test '%s' should be valid but failed array-from-vector conversion",
+                        test_case->test_description);
+         }
+         ASSERT (bson_array_builder_build (array_builder, &array_from_vector));
+         bson_array_builder_destroy (array_builder);
+      }
+
+      if (BSON_ITER_HOLDS_VECTOR_FLOAT32 (&iter)) {
+         // float32 special case: Due to underspecified rounding and conversion rules we compare value inexactly.
+         // (Spec test improvement TODO)
+
+         bson_iter_t actual_iter, expected_iter;
+         ASSERT (bson_iter_init (&actual_iter, &array_from_vector));
+         ASSERT (bson_iter_init (&expected_iter, test_case->test_vector_array));
+
+         for (size_t i = 0;; i++) {
+            bool actual_next = bson_iter_next (&actual_iter);
+            bool expected_next = bson_iter_next (&expected_iter);
+            if (!actual_next && !expected_next) {
+               break;
+            } else if (!actual_next) {
+               test_error ("converted array is shorter than expected");
+            } else if (!expected_next) {
+               test_error ("converted array is longer than expected");
+            }
+
+            if (!BSON_ITER_HOLDS_DOUBLE (&actual_iter)) {
+               test_error ("converted array element %d has unexpected type, should be double", (int) i);
+            }
+            double actual_double = bson_iter_double (&actual_iter);
+
+            double expected_double;
+            if (BSON_ITER_HOLDS_DOUBLE (&expected_iter)) {
+               expected_double = bson_iter_double (&expected_iter);
+            } else {
+               test_error ("test-vector array element %d has unexpected type, should be double, 'inf', or '-inf'.",
+                           (int) i);
+            }
+
+            bool is_sorta_equal = false;
+            if (expected_double != expected_double) {
+               // Expect NaN, any type is fine.
+               if (actual_double != actual_double) {
+                  is_sorta_equal = true;
+               }
+            } else if (expected_double == 0.0 || expected_double * 0.0 != 0.0) {
+               // Infinity or zero, equality comparison is fine.
+               is_sorta_equal = expected_double == actual_double;
+            } else {
+               // Finite number, allow +/- error relative to the scale of the expected value.
+               // Note that ASSERT_EQUAL_DOUBLE() in TestSuite exists but its fixed error threshold of 20% seems too
+               // loose for this application.
+               static const double allowed_relative_error = 1e-7;
+               double allowed_absolute_error = fabs (allowed_relative_error * expected_double);
+               is_sorta_equal = actual_double >= expected_double - allowed_absolute_error &&
+                                actual_double <= expected_double + allowed_absolute_error;
+            }
+            if (!is_sorta_equal) {
+               test_error ("test-vector array element %d failed inexact float32 match. Actual: %f Expected: %f",
+                           (int) i,
+                           actual_double,
+                           expected_double);
+            }
+         }
+
+      } else if (BSON_ITER_HOLDS_VECTOR_PACKED_BIT (&iter)) {
+         // packed_bit special case: The tests for packed_bit aren't actually testing vector-to-array conversion as we
+         // understand it, they're operating on bytes rather than elements. This is the inverse of
+         // append_vector_packed_bit_from_packed_array() above, and it bypasses the vector-to-array conversion.
+         // 'array_from_vector' is ignored on this path.
+         // (Spec test improvement TODO)
+
+         bson_iter_t expected_iter;
+         ASSERT (bson_iter_init (&expected_iter, test_case->test_vector_array));
+         bson_vector_packed_bit_const_view_t actual_view;
+         ASSERT (bson_vector_packed_bit_const_view_from_iter (&actual_view, &iter));
+
+         size_t byte_count = 0;
+         while (bson_iter_next (&expected_iter)) {
+            int64_t expected_byte;
+            if (BSON_ITER_HOLDS_INT (&expected_iter)) {
+               expected_byte = bson_iter_as_int64 (&expected_iter);
+            } else {
+               test_error ("test-vector array element %d has unexpected type, should be int.", (int) byte_count);
+            }
+
+            // (Spec test improvement TODO) Packed writes can't set unused bits to '1' in libbson, but the spec
+            // tests allow padding bits to take on undefined values. Modify the expected values to keep padding bits
+            // zeroed.
+            if (0 == strcmp ("PACKED_BIT with padding", test_case->test_description) &&
+                byte_count == bson_vector_packed_bit_const_view_length_bytes (actual_view) - 1u) {
+               expected_byte &= ((int64_t) 0xFF << *test_case->test_padding) & 0xFF;
+            }
+
+            // Note, the zero initializer is only needed due to a false positive -Wmaybe-uninitialized warning in
+            // uncommon configurations where the compiler does not have visibility into memcpy().
+            uint8_t actual_byte = 0;
+            ASSERT (bson_vector_packed_bit_const_view_read_packed (actual_view, &actual_byte, 1, byte_count));
+
+            if (expected_byte != (int64_t) actual_byte) {
+               test_error ("failed to match packed byte %d of packed_bit test-vector. Actual: 0x%02x Expected: 0x%02x",
+                           (int) byte_count,
+                           (unsigned) actual_byte,
+                           (unsigned) expected_byte);
+            }
+            byte_count++;
+         }
+         ASSERT_CMPSIZE_T (byte_count, ==, bson_vector_packed_bit_const_view_length_bytes (actual_view));
+
+      } else {
+         // No special case, expect an exact match. (Used for int8 vectors)
+         if (0 != bson_compare (&array_from_vector, test_case->test_vector_array)) {
+            test_error ("bson_binary_vector JSON scenario '%s' test '%s' did not exactly match the reference array "
+                        "after array-from-vector.\n "
+                        "Actual: %s\n Expected: %s",
+                        test_case->scenario_description,
+                        test_case->test_description,
+                        tmp_json (&array_from_vector),
+                        tmp_json (test_case->test_vector_array));
+         }
+      }
+
+      bson_destroy (&array_from_vector);
+   } else {
+      /*
+       * "To prove correct in an invalid case (valid:false), one MUST
+       * - if the vector field is present, raise an exception when attempting to encode a document from the numeric
+       * values, dtype, and padding.
+       * - if the canonical_bson field is present, raise an exception when attempting to deserialize it into the
+       * corresponding numeric values, as the field contains corrupted data."
+       */
+
+      if (vector_from_array_ok) {
+         test_error ("bson_binary_vector JSON scenario '%s' test '%s' should be invalid but vector-from-array "
+                     "succeeded with result: %s",
+                     test_case->scenario_description,
+                     test_case->test_description,
+                     tmp_json (&vector_from_array));
+      }
+
+      if (test_case->test_canonical_bson_str) {
+         bson_t array_from_vector = BSON_INITIALIZER;
+         bson_iter_t iter;
+         ASSERT (bson_iter_init_find (&iter, &expected_bson, test_case->scenario_test_key));
+         if (BSON_APPEND_ARRAY_FROM_VECTOR (&array_from_vector, "should_fail", &iter)) {
+            test_error ("bson_binary_vector JSON scenario '%s' test '%s' should be invalid but array-from-vector "
+                        "succeeded with result: %s",
+                        test_case->scenario_description,
+                        test_case->test_description,
+                        tmp_json (&array_from_vector));
+         }
+         bson_destroy (&array_from_vector);
+      }
+   }
+
+   bson_destroy (&expected_bson);
+}
+
+// callback for install_json_test_suite_with_check, implements JSON spec tests
+static void
+test_bson_vector_json_cb (void *test_arg)
+{
+   BSON_ASSERT_PARAM (test_arg);
+   bson_t *scenario = (bson_t *) test_arg;
+   bson_error_t error;
+   vector_json_test_case_t test_case;
+
+   bson_parser_t *scenario_opts = bson_parser_new ();
+   bson_t *tests;
+   bson_parser_utf8 (scenario_opts, "description", &test_case.scenario_description);
+   bson_parser_utf8 (scenario_opts, "test_key", &test_case.scenario_test_key);
+   bson_parser_array (scenario_opts, "tests", &tests);
+   if (!bson_parser_parse (scenario_opts, scenario, &error)) {
+      test_error ("format error in bson_binary_vector JSON scenario: %s", error.message);
+   }
+
+   bson_iter_t tests_iter;
+   ASSERT (bson_iter_init (&tests_iter, tests));
+   while (bson_iter_next (&tests_iter)) {
+      bson_t test_subdoc;
+      bson_iter_bson (&tests_iter, &test_subdoc);
+
+      bson_parser_t *test_opts = bson_parser_new ();
+      bson_parser_utf8 (test_opts, "description", &test_case.test_description);
+      bson_parser_bool (test_opts, "valid", &test_case.test_valid);
+      bson_parser_array_optional (test_opts, "vector", &test_case.test_vector_array);
+      bson_parser_utf8 (test_opts, "dtype_hex", &test_case.test_dtype_hex_str);
+      bson_parser_utf8 (test_opts, "dtype_alias", &test_case.test_dtype_alias_str);
+      bson_parser_int_optional (test_opts, "padding", &test_case.test_padding);
+      bson_parser_utf8_optional (test_opts, "canonical_bson", &test_case.test_canonical_bson_str);
+      if (!bson_parser_parse (test_opts, &test_subdoc, &error)) {
+         test_error (
+            "format error in bson_binary_vector JSON test for '%s': %s", test_case.scenario_description, error.message);
+      }
+
+      if (test_suite_debug_output ()) {
+         printf ("bson_binary_vector JSON scenario '%s' test '%s'\n",
+                 test_case.scenario_description,
+                 test_case.test_description);
+      }
+
+      test_bson_vector_json_case (&test_case);
+      bson_parser_destroy_with_parsed_fields (test_opts);
+   }
+   bson_parser_destroy_with_parsed_fields (scenario_opts);
+}
+
+static void
+test_bson_vector_view_api_usage_int8 (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // Construct a small vector by writing individual elements
+   {
+      bson_vector_int8_view_t view;
+      const size_t length = 25;
+      ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "vector", length, &view));
+      for (size_t i = 0; i < length; i++) {
+         int8_t v = (int8_t) i - 9;
+         bson_vector_int8_view_write (view, &v, 1, i);
+      }
+   }
+
+   ASSERT_CMPJSON (
+      bson_as_canonical_extended_json (&doc, NULL),
+      BSON_STR ({"vector" : {"$binary" : {"base64" : "AwD3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4P", "subType" : "09"}}}));
+
+   // Construct a longer vector by writing individual elements
+   {
+      bson_vector_int8_view_t view;
+      const size_t length = 50000;
+      ASSERT (bson_append_vector_int8_uninit (&doc, "longer_vector", -1, length, &view));
+      for (size_t i = 0; i < length; i++) {
+         int8_t v = (int8_t) (uint8_t) i;
+         bson_vector_int8_view_write (view, &v, 1, i);
+      }
+   }
+
+   // Fail appending a vector that would be too large to represent
+   {
+      bson_vector_int8_view_t view;
+      const size_t length = UINT32_MAX - 1;
+      ASSERT (!bson_append_vector_int8_uninit (&doc, "overlong_vector", -1, length, &view));
+   }
+
+   // Use a mutable view to partially overwrite "vector"
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      bson_vector_int8_view_t view;
+      ASSERT (bson_vector_int8_view_from_iter (&view, &iter));
+      ASSERT (bson_vector_int8_view_length (view) == 25);
+      int8_t values[5] = {12, 34, 56, 78, 90};
+      ASSERT (bson_vector_int8_view_write (view, values, sizeof values / sizeof values[0], 3));
+   }
+
+   // Read the modified small vector into an int8_t array
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_ITER_HOLDS_BINARY (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR_INT8 (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_FLOAT32 (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_PACKED_BIT (&iter));
+      bson_vector_int8_const_view_t view;
+      ASSERT (bson_vector_int8_const_view_from_iter (&view, &iter));
+      ASSERT (bson_vector_int8_const_view_length (view) == 25);
+      int8_t values[25];
+      static const int8_t expected_values[25] = {-9, -8, -7, 12, 34, 56, 78, 90, -1, 0,  1,  2, 3,
+                                                 4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15};
+      ASSERT (bson_vector_int8_const_view_read (view, values, sizeof values / sizeof values[0], 0));
+      ASSERT_MEMCMP (values, expected_values, (int) sizeof expected_values);
+   }
+
+   // Convert the small vector to a BSON Array, and check the resulting canonical extended JSON.
+   // Each element will be losslessly converted to int32.
+   // Convert the output back, and add a "round_trip" key to the original document.
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT_CMPJSON (bson_as_canonical_extended_json (&converted, NULL), BSON_STR ({
+                         "array" : [
+                            {"$numberInt" : "-9"}, {"$numberInt" : "-8"}, {"$numberInt" : "-7"}, {"$numberInt" : "12"},
+                            {"$numberInt" : "34"}, {"$numberInt" : "56"}, {"$numberInt" : "78"}, {"$numberInt" : "90"},
+                            {"$numberInt" : "-1"}, {"$numberInt" : "0"},  {"$numberInt" : "1"},  {"$numberInt" : "2"},
+                            {"$numberInt" : "3"},  {"$numberInt" : "4"},  {"$numberInt" : "5"},  {"$numberInt" : "6"},
+                            {"$numberInt" : "7"},  {"$numberInt" : "8"},  {"$numberInt" : "9"},  {"$numberInt" : "10"},
+                            {"$numberInt" : "11"}, {"$numberInt" : "12"}, {"$numberInt" : "13"}, {"$numberInt" : "14"},
+                            {"$numberInt" : "15"}
+                         ]
+                      }));
+
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_INT8_FROM_ARRAY (&doc, "round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+
+   // The original small vector and round_trip small vector must be identical
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   // Try the same round trip conversion with our longer vector
+   // (Note that BSON arrays special-case keys below "1000")
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "longer_vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_INT8_FROM_ARRAY (&doc, "longer_round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "longer_vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "longer_round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_view_api_usage_float32 (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // Construct a small vector by writing individual elements
+   {
+      bson_vector_float32_view_t view;
+      const size_t length = 5;
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "vector", length, &view));
+      for (size_t i = 0; i < length; i++) {
+         float v = 1.0f + 0.25f * (float) i;
+         bson_vector_float32_view_write (view, &v, 1, i);
+      }
+   }
+
+   ASSERT_CMPJSON (
+      bson_as_canonical_extended_json (&doc, NULL),
+      BSON_STR ({"vector" : {"$binary" : {"base64" : "JwAAAIA/AACgPwAAwD8AAOA/AAAAQA==", "subType" : "09"}}}));
+
+   // Construct a longer vector by writing individual elements
+   {
+      bson_vector_float32_view_t view;
+      const size_t length = 10000;
+      ASSERT (bson_append_vector_float32_uninit (&doc, "longer_vector", -1, length, &view));
+      for (size_t i = 0; i < length; i++) {
+         float v = (float) i;
+         bson_vector_float32_view_write (view, &v, 1, i);
+      }
+   }
+
+   // Fail appending a vector that would be too large to represent
+   {
+      bson_vector_float32_view_t view;
+      const size_t length = (UINT32_MAX - 1) / 4;
+      ASSERT (!bson_append_vector_float32_uninit (&doc, "overlong_vector", -1, length, &view));
+   }
+
+   // Read the small vector into a float array
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_ITER_HOLDS_BINARY (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_INT8 (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR_FLOAT32 (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_PACKED_BIT (&iter));
+      bson_vector_float32_const_view_t view;
+      ASSERT (bson_vector_float32_const_view_from_iter (&view, &iter));
+      ASSERT (bson_vector_float32_const_view_length (view) == 5);
+      float values[5];
+      static const float expected_values[5] = {1.0f, 1.25f, 1.5f, 1.75f, 2.0f};
+      ASSERT (bson_vector_float32_const_view_read (view, values, sizeof values / sizeof values[0], 0));
+      ASSERT_MEMCMP (values, expected_values, (int) sizeof expected_values);
+   }
+
+   // Convert the small vector to a BSON Array, and check the resulting canonical extended JSON.
+   // Each element will be converted from 32-bit to 64-bit float.
+   // Convert the output back, and add a "round_trip" key to the original document.
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT_CMPJSON (bson_as_canonical_extended_json (&converted, NULL), BSON_STR ({
+                         "array" : [
+                            {"$numberDouble" : "1.0"},
+                            {"$numberDouble" : "1.25"},
+                            {"$numberDouble" : "1.5"},
+                            {"$numberDouble" : "1.75"},
+                            {"$numberDouble" : "2.0"}
+                         ]
+                      }));
+
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_FROM_ARRAY (&doc, "round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+
+   // The original small vector and round_trip small vector must be identical
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   // Try the same round trip conversion with our longer vector
+   // (Note that BSON arrays special-case keys below "1000")
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "longer_vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_FROM_ARRAY (&doc, "longer_round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "longer_vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "longer_round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_view_api_usage_packed_bit (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // Construct a small vector by packing individual elements from a 'bool' source
+   {
+      bson_vector_packed_bit_view_t view;
+      const size_t length = 123;
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "vector", length, &view));
+      for (size_t i = 0; i < length; i++) {
+         bool v = (i & 1) != 0;
+         bson_vector_packed_bit_view_pack_bool (view, &v, 1, i);
+      }
+   }
+
+   ASSERT_CMPJSON (bson_as_canonical_extended_json (&doc, NULL),
+                   BSON_STR ({"vector" : {"$binary" : {"base64" : "EAVVVVVVVVVVVVVVVVVVVVVA", "subType" : "09"}}}));
+
+   // Construct a longer vector by packing individual elements from a 'bool' source
+   {
+      bson_vector_packed_bit_view_t view;
+      const size_t length = 100002;
+      ASSERT (bson_append_vector_packed_bit_uninit (&doc, "longer_vector", -1, length, &view));
+      for (size_t i = 0; i < length; i++) {
+         bool v = (i & 3) != 0;
+         bson_vector_packed_bit_view_pack_bool (view, &v, 1, i);
+      }
+   }
+
+   // Fail appending a vector that would be too large to represent
+   {
+      bson_vector_int8_view_t view;
+      const size_t length = (UINT32_MAX - 1) * (size_t) 8;
+      ASSERT (!bson_append_vector_int8_uninit (&doc, "overlong_vector", -1, length, &view));
+   }
+
+   // Unpack the small vector into a bool array
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_ITER_HOLDS_BINARY (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_INT8 (&iter));
+      ASSERT (!BSON_ITER_HOLDS_VECTOR_FLOAT32 (&iter));
+      ASSERT (BSON_ITER_HOLDS_VECTOR_PACKED_BIT (&iter));
+      bson_vector_packed_bit_const_view_t view;
+      ASSERT (bson_vector_packed_bit_const_view_from_iter (&view, &iter));
+      ASSERT (bson_vector_packed_bit_const_view_length (view) == 123);
+      bool values[123];
+      bool expected_values[123];
+      for (size_t i = 0; i < sizeof expected_values / sizeof expected_values[0]; i++) {
+         expected_values[i] = (i & 1) != 0;
+      }
+      ASSERT (bson_vector_packed_bit_const_view_unpack_bool (view, values, sizeof values / sizeof values[0], 0));
+      ASSERT_MEMCMP (values, expected_values, (int) sizeof expected_values);
+   }
+
+   // Read the packed representation without unpacking
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      bson_vector_packed_bit_const_view_t view;
+      ASSERT (bson_vector_packed_bit_const_view_from_iter (&view, &iter));
+      ASSERT (bson_vector_packed_bit_const_view_length (view) == 123);
+      uint8_t packed[16];
+      static const uint8_t expected_packed[16] = {
+         0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x40};
+      ASSERT (bson_vector_packed_bit_const_view_read_packed (view, packed, sizeof packed, 0));
+      ASSERT_MEMCMP (packed, expected_packed, (int) sizeof expected_packed);
+   }
+
+   // Partial overwrite of the packed representation
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      bson_vector_packed_bit_view_t view;
+      ASSERT (bson_vector_packed_bit_view_from_iter (&view, &iter));
+      uint8_t packed[2] = {0x12, 0x34};
+      ASSERT (bson_vector_packed_bit_view_write_packed (view, packed, sizeof packed, 12));
+   }
+
+   // Partial read of the packed representation
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      bson_vector_packed_bit_const_view_t view;
+      ASSERT (bson_vector_packed_bit_const_view_from_iter (&view, &iter));
+      uint8_t packed[5];
+      static const uint8_t expected_packed[5] = {0x55, 0x12, 0x34, 0x55, 0x40};
+      ASSERT (bson_vector_packed_bit_const_view_read_packed (view, packed, sizeof packed, 11));
+      ASSERT_MEMCMP (packed, expected_packed, (int) sizeof expected_packed);
+   }
+
+   // Partial write from a bool array, spanning complete and partial packed bytes
+   {
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      bson_vector_packed_bit_view_t view;
+      ASSERT (bson_vector_packed_bit_view_from_iter (&view, &iter));
+      bool values[24] = {
+         false, false, false, true,  false, false, false, true,  true,  true,  false, true,
+         true,  false, false, false, false, true,  false, false, false, false, false, true,
+      };
+      ASSERT (bson_vector_packed_bit_view_pack_bool (view, values, sizeof values / sizeof values[0], 3));
+   }
+
+   // Convert the small vector to a BSON Array, and check the resulting canonical extended JSON.
+   // Each element will be losslessly converted to int32.
+   // Convert the output back, and add a "round_trip" key to the original document.
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT_CMPJSON (bson_as_canonical_extended_json (&converted, NULL), BSON_STR ({
+                         "array" : [
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "0"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}, {"$numberInt" : "1"},
+                            {"$numberInt" : "0"}, {"$numberInt" : "1"}, {"$numberInt" : "0"}
+                         ]
+                      }));
+
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_FROM_ARRAY (&doc, "round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+
+   // The original small vector and round_trip small vector must be identical
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   // Try the same round trip conversion with our longer vector
+   // (Note that BSON arrays special-case keys below "1000")
+   {
+      bson_t converted = BSON_INITIALIZER;
+      bson_iter_t iter;
+      ASSERT (bson_iter_init_find (&iter, &doc, "longer_vector"));
+      ASSERT (BSON_APPEND_ARRAY_FROM_VECTOR (&converted, "array", &iter));
+      ASSERT (bson_iter_init_find (&iter, &converted, "array"));
+      ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+      ASSERT (bson_iter_recurse (&iter, &iter));
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_FROM_ARRAY (&doc, "longer_round_trip", &iter, NULL));
+      bson_destroy (&converted);
+   }
+   {
+      bson_iter_t a, b;
+      ASSERT (bson_iter_init_find (&a, &doc, "longer_vector"));
+      ASSERT (bson_iter_init_find (&b, &doc, "longer_round_trip"));
+      ASSERT (bson_iter_binary_equal (&a, &b));
+   }
+
+   // Padding bits will be initialized to zero when a packed_bit vector is first allocated by
+   // bson_append_vector_packed_bit_uninit
+   {
+      // Set the uninitialized part of 'doc' to a known value
+      static const uint32_t reserve_len = 512;
+      memset (bson_reserve_buffer (&doc, doc.len + reserve_len) + doc.len, 0xdd, reserve_len);
+
+      bson_vector_packed_bit_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "padding_init_test", 12, &view));
+      ASSERT (bson_vector_packed_bit_view_length_bytes (view) == 2);
+      ASSERT (bson_vector_packed_bit_view_padding (view) == 4);
+
+      // BSON validity only requires the low 4 bits to be zero, but the entire last
+      // byte will be zeroed by our implementation.
+      uint8_t bytes[2];
+      ASSERT (bson_vector_packed_bit_view_read_packed (view, bytes, sizeof bytes, 0));
+      ASSERT_CMPUINT ((unsigned) bytes[0], ==, 0xdd);
+      ASSERT_CMPUINT ((unsigned) bytes[1], ==, 0x00);
+   }
+
+   // Padding bits can't be forcibly given nonzero values using bson_vector_packed_bit_view_write_packed
+   {
+      bson_vector_packed_bit_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "padding_mask_test", 13, &view));
+      ASSERT (bson_vector_packed_bit_view_length_bytes (view) == 2);
+      ASSERT (bson_vector_packed_bit_view_padding (view) == 3);
+
+      uint8_t bytes[2] = {0xff, 0xff};
+      ASSERT (bson_vector_packed_bit_view_write_packed (view, bytes, sizeof bytes, 0));
+      ASSERT (bson_vector_packed_bit_view_read_packed (view, bytes, sizeof bytes, 0));
+      ASSERT_CMPUINT ((unsigned) bytes[0], ==, 0xff);
+      ASSERT_CMPUINT ((unsigned) bytes[1], ==, 0xf8);
+   }
+
+   bson_destroy (&doc);
+}
+
+// Note: The effective MAX_TESTED_VECTOR_LENGTH is limited to 2047 on Windows due to RAND_MAX==0x7fff
+#define MAX_TESTED_VECTOR_LENGTH 10000
+#define FUZZ_TEST_ITERS 5000
+
+static void
+test_bson_vector_view_api_fuzz_int8 (void)
+{
+   size_t current_length = 0;
+   bson_t vector_doc = BSON_INITIALIZER;
+   int8_t *expected_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *expected_elements);
+   int8_t *actual_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *actual_elements);
+   for (int fuzz_iter = 0; fuzz_iter < FUZZ_TEST_ITERS; fuzz_iter++) {
+      unsigned r = (unsigned) rand ();
+      unsigned r_operation = r & 0xFu;
+      size_t r_param = r >> 4;
+
+      if (current_length == 0 || r_operation == 15) {
+         // Resize and fill
+         size_t new_length = (size_t) r_param % MAX_TESTED_VECTOR_LENGTH;
+         bson_reinit (&vector_doc);
+         bson_vector_int8_view_t view;
+         ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&vector_doc, "vector", new_length, &view));
+         for (size_t i = 0; i < new_length; i++) {
+            expected_elements[i] = (int8_t) (uint8_t) rand ();
+         }
+         ASSERT (bson_vector_int8_view_write (view, expected_elements, new_length, 0));
+         current_length = new_length;
+
+      } else if (r_operation < 7) {
+         // Partial write
+         size_t element_count = r_param % current_length;
+         size_t offset = (size_t) rand () % (current_length - element_count);
+         for (size_t i = 0; i < element_count; i++) {
+            expected_elements[offset + i] = (int8_t) (uint8_t) rand ();
+         }
+         bson_vector_int8_view_t view;
+         bson_iter_t iter;
+         ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+         ASSERT (bson_vector_int8_view_from_iter (&view, &iter));
+         ASSERT (bson_vector_int8_view_write (view, expected_elements + offset, element_count, offset));
+
+      } else {
+         // Partial read
+         size_t element_count = r_param % current_length;
+         size_t offset = (size_t) rand () % (current_length - element_count);
+         bson_vector_int8_const_view_t view;
+         bson_iter_t iter;
+         ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+         ASSERT (bson_vector_int8_const_view_from_iter (&view, &iter));
+         ASSERT (bson_vector_int8_const_view_read (view, actual_elements, element_count, offset));
+         ASSERT_MEMCMP (actual_elements, expected_elements + offset, element_count * sizeof *actual_elements);
+      }
+   }
+   bson_destroy (&vector_doc);
+   bson_free (expected_elements);
+   bson_free (actual_elements);
+}
+
+static void
+test_bson_vector_view_api_fuzz_float32 (void)
+{
+   size_t current_length = 0;
+   bson_t vector_doc = BSON_INITIALIZER;
+   float *expected_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *expected_elements);
+   float *actual_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *actual_elements);
+   for (int fuzz_iter = 0; fuzz_iter < FUZZ_TEST_ITERS; fuzz_iter++) {
+      unsigned r = (unsigned) rand ();
+      unsigned r_operation = r & 0xFu;
+      size_t r_param = r >> 4;
+
+      if (current_length == 0 || r_operation == 15) {
+         // Resize and fill
+         size_t new_length = (size_t) r_param % MAX_TESTED_VECTOR_LENGTH;
+         bson_reinit (&vector_doc);
+         bson_vector_float32_view_t view;
+         ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&vector_doc, "vector", new_length, &view));
+         for (size_t i = 0; i < new_length; i++) {
+            expected_elements[i] = (float) rand ();
+         }
+         ASSERT (bson_vector_float32_view_write (view, expected_elements, new_length, 0));
+         current_length = new_length;
+
+      } else if (r_operation < 7) {
+         // Partial write
+         size_t element_count = r_param % current_length;
+         size_t offset = (size_t) rand () % (current_length - element_count);
+         for (size_t i = 0; i < element_count; i++) {
+            expected_elements[offset + i] = (float) rand ();
+         }
+         bson_vector_float32_view_t view;
+         bson_iter_t iter;
+         ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+         ASSERT (bson_vector_float32_view_from_iter (&view, &iter));
+         ASSERT (bson_vector_float32_view_write (view, expected_elements + offset, element_count, offset));
+
+      } else {
+         // Partial read
+         size_t element_count = r_param % current_length;
+         size_t offset = (size_t) rand () % (current_length - element_count);
+         bson_vector_float32_const_view_t view;
+         bson_iter_t iter;
+         ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+         ASSERT (bson_vector_float32_const_view_from_iter (&view, &iter));
+         ASSERT (bson_vector_float32_const_view_read (view, actual_elements, element_count, offset));
+         ASSERT_MEMCMP (actual_elements, expected_elements + offset, element_count * sizeof *actual_elements);
+      }
+   }
+   bson_destroy (&vector_doc);
+   bson_free (expected_elements);
+   bson_free (actual_elements);
+}
+
+static void
+test_bson_vector_view_api_fuzz_packed_bit (void)
+{
+   size_t current_length = 0;
+   bson_t vector_doc = BSON_INITIALIZER;
+   bool *expected_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *expected_elements);
+   bool *actual_elements = bson_malloc (MAX_TESTED_VECTOR_LENGTH * sizeof *actual_elements);
+   uint8_t *packed_buffer = bson_malloc ((MAX_TESTED_VECTOR_LENGTH + 7) / 8);
+   for (int fuzz_iter = 0; fuzz_iter < FUZZ_TEST_ITERS; fuzz_iter++) {
+      unsigned r = (unsigned) rand ();
+      unsigned r_operation = r & 0xFu;
+      size_t r_param = r >> 4;
+
+      if (current_length == 0 || r_operation == 15) {
+         // Resize and fill from unpacked bool source
+         size_t new_length = (size_t) r_param % MAX_TESTED_VECTOR_LENGTH;
+         bson_reinit (&vector_doc);
+         bson_vector_packed_bit_view_t view;
+         ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&vector_doc, "vector", new_length, &view));
+         for (size_t i = 0; i < new_length; i++) {
+            expected_elements[i] = ((unsigned) rand () & 1u) != 0u;
+         }
+         ASSERT (bson_vector_packed_bit_view_pack_bool (view, expected_elements, new_length, 0));
+         current_length = new_length;
+
+      } else if (r_operation < 7) {
+         // Partial write
+         if (r_operation & 1) {
+            // Partial write from unpacked bool source
+            size_t element_count = r_param % current_length;
+            size_t offset = (size_t) rand () % (current_length - element_count);
+            for (size_t i = 0; i < element_count; i++) {
+               expected_elements[offset + i] = ((unsigned) rand () & 1u) != 0u;
+            }
+            bson_vector_packed_bit_view_t view;
+            bson_iter_t iter;
+            ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+            ASSERT (bson_vector_packed_bit_view_from_iter (&view, &iter));
+            ASSERT (bson_vector_packed_bit_view_length (view) == current_length);
+            ASSERT (bson_vector_packed_bit_view_pack_bool (view, expected_elements + offset, element_count, offset));
+         } else {
+            // Partial write of packed bytes
+            size_t current_length_bytes = (current_length + 7) / 8;
+            size_t byte_count = r_param % current_length_bytes;
+            size_t byte_offset = (size_t) rand () % (current_length_bytes - byte_count);
+            for (size_t i = 0; i < byte_count; i++) {
+               uint8_t packed_byte = (uint8_t) rand ();
+               packed_buffer[i] = packed_byte;
+               for (unsigned bit = 0; bit < 8; bit++) {
+                  expected_elements[(byte_offset + i) * 8 + bit] = (packed_byte & (0x80 >> bit)) != 0;
+               }
+            }
+            bson_vector_packed_bit_view_t view;
+            bson_iter_t iter;
+            ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+            ASSERT (bson_vector_packed_bit_view_from_iter (&view, &iter));
+            ASSERT (bson_vector_packed_bit_view_length (view) == current_length);
+            ASSERT (bson_vector_packed_bit_view_length_bytes (view) == current_length_bytes);
+            ASSERT (bson_vector_packed_bit_view_write_packed (view, packed_buffer, byte_count, byte_offset));
+         }
+      } else {
+         // Partial read
+         if (r_operation & 1) {
+            // Partial read to unpacked bool destination
+            size_t element_count = r_param % current_length;
+            size_t offset = (size_t) rand () % (current_length - element_count);
+            bson_vector_packed_bit_const_view_t view;
+            bson_iter_t iter;
+            ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+            ASSERT (bson_vector_packed_bit_const_view_from_iter (&view, &iter));
+            ASSERT (bson_vector_packed_bit_const_view_length (view) == current_length);
+            ASSERT (bson_vector_packed_bit_const_view_unpack_bool (view, actual_elements, element_count, offset));
+            ASSERT_MEMCMP (actual_elements, expected_elements + offset, element_count * sizeof *actual_elements);
+         } else {
+            // Partial read of packed bytes
+            size_t current_length_bytes = (current_length + 7) / 8;
+            size_t byte_count = r_param % current_length_bytes;
+            size_t byte_offset = (size_t) rand () % (current_length_bytes - byte_count);
+            bson_vector_packed_bit_const_view_t view;
+            bson_iter_t iter;
+            ASSERT (bson_iter_init_find (&iter, &vector_doc, "vector"));
+            ASSERT (bson_vector_packed_bit_const_view_from_iter (&view, &iter));
+            ASSERT (bson_vector_packed_bit_const_view_length (view) == current_length);
+            ASSERT (bson_vector_packed_bit_const_view_length_bytes (view) == current_length_bytes);
+            ASSERT (bson_vector_packed_bit_const_view_read_packed (view, packed_buffer, byte_count, byte_offset));
+            for (size_t i = 0; i < byte_count; i++) {
+               uint8_t packed_byte = packed_buffer[i];
+               for (unsigned bit = 0; bit < 8; bit++) {
+                  ASSERT (expected_elements[(byte_offset + i) * 8 + bit] == ((packed_byte & (0x80 >> bit)) != 0));
+               }
+            }
+         }
+      }
+   }
+   bson_destroy (&vector_doc);
+   bson_free (expected_elements);
+   bson_free (actual_elements);
+   bson_free (packed_buffer);
+}
+
+static void
+test_bson_vector_example_int8_const_view (void)
+{
+   // setup: construct a sample document
+   bson_t doc = BSON_INITIALIZER;
+   {
+      static const int8_t values[] = {12, 34, -56};
+      bson_vector_int8_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "vector", sizeof values / sizeof values[0], &view));
+      ASSERT (bson_vector_int8_view_write (view, values, sizeof values / sizeof values[0], 0));
+   }
+
+   // bson_vector_int8_const_view_t.rst
+   // Edits:
+   //  - Added test_suite_debug_output() test.
+   //  - Added unnecessary zero initializer to work around false positive compiler warning.
+   //    (same as in bson_array_builder_append_vector_int8_elements)
+   {
+      bson_iter_t iter;
+      bson_vector_int8_const_view_t view;
+
+      if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_int8_const_view_from_iter (&view, &iter)) {
+         size_t length = bson_vector_int8_const_view_length (view);
+         if (test_suite_debug_output ()) {
+            printf ("Elements in 'vector':\n");
+         }
+         for (size_t i = 0; i < length; i++) {
+            int8_t element = 0; // Workaround
+            ASSERT (bson_vector_int8_const_view_read (view, &element, 1, i));
+            if (test_suite_debug_output ()) {
+               printf (" [%d] = %d\n", (int) i, (int) element);
+            }
+         }
+      }
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_example_int8_view (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // bson_vector_int8_view_t.rst
+   {
+      static const int8_t values[] = {1, 2, 3};
+      const size_t values_count = sizeof values / sizeof values[0];
+
+      bson_vector_int8_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "vector", values_count, &view));
+      ASSERT (bson_vector_int8_view_write (view, values, values_count, 0));
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_example_float32_const_view (void)
+{
+   // setup: construct a sample document
+   bson_t doc = BSON_INITIALIZER;
+   {
+      static const float values[] = {5.0f, -1e10f, INFINITY, NAN, -1.0f};
+      bson_vector_float32_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "vector", sizeof values / sizeof values[0], &view));
+      ASSERT (bson_vector_float32_view_write (view, values, sizeof values / sizeof values[0], 0));
+   }
+
+   // bson_vector_float32_const_view_t.rst
+   // Edits:
+   //  - Added test_suite_debug_output() test.
+   {
+      bson_iter_t iter;
+      bson_vector_float32_const_view_t view;
+
+      if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_float32_const_view_from_iter (&view, &iter)) {
+         size_t length = bson_vector_float32_const_view_length (view);
+         if (test_suite_debug_output ()) {
+            printf ("Elements in 'vector':\n");
+         }
+         for (size_t i = 0; i < length; i++) {
+            float element;
+            ASSERT (bson_vector_float32_const_view_read (view, &element, 1, i));
+            if (test_suite_debug_output ()) {
+               printf (" [%d] = %f\n", (int) i, element);
+            }
+         }
+      }
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_example_float32_view (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // bson_vector_float32_view_t.rst
+   {
+      static const float values[] = {1.0f, 2.0f, 3.0f};
+      const size_t values_count = sizeof values / sizeof values[0];
+
+      bson_vector_float32_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "vector", values_count, &view));
+      ASSERT (bson_vector_float32_view_write (view, values, values_count, 0));
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_example_packed_bit_const_view (void)
+{
+   // setup: construct a sample document
+   bson_t doc = BSON_INITIALIZER;
+   {
+      static const bool values[] = {true, false, true, true, false, true, false, true, true, false};
+      bson_vector_packed_bit_view_t view;
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "vector", sizeof values / sizeof values[0], &view));
+      ASSERT (bson_vector_packed_bit_view_pack_bool (view, values, sizeof values / sizeof values[0], 0));
+   }
+
+   // bson_vector_packed_bit_const_view_t.rst
+   // Edits:
+   //  - Added test_suite_debug_output() test.
+   //  - Added unnecessary zero initializer to work around false positive compiler warning.
+   //    (same as in bson_array_builder_append_vector_int8_elements)
+   {
+      bson_iter_t iter;
+      bson_vector_packed_bit_const_view_t view;
+
+      if (bson_iter_init_find (&iter, &doc, "vector") && bson_vector_packed_bit_const_view_from_iter (&view, &iter)) {
+         size_t length = bson_vector_packed_bit_const_view_length (view);
+         size_t length_bytes = bson_vector_packed_bit_const_view_length_bytes (view);
+         size_t padding = bson_vector_packed_bit_const_view_padding (view);
+
+         if (test_suite_debug_output ()) {
+            printf ("Elements in 'vector':\n");
+         }
+         for (size_t i = 0; i < length; i++) {
+            bool element;
+            ASSERT (bson_vector_packed_bit_const_view_unpack_bool (view, &element, 1, i));
+            if (test_suite_debug_output ()) {
+               printf (" elements[%d] = %d\n", (int) i, (int) element);
+            }
+         }
+
+         if (test_suite_debug_output ()) {
+            printf ("Bytes in 'vector': (%d bits unused)\n", (int) padding);
+         }
+         for (size_t i = 0; i < length_bytes; i++) {
+            uint8_t packed_byte = 0; // Workaround
+            ASSERT (bson_vector_packed_bit_const_view_read_packed (view, &packed_byte, 1, i));
+            if (test_suite_debug_output ()) {
+               printf (" bytes[%d] = 0x%02x\n", (int) i, (unsigned) packed_byte);
+            }
+         }
+      }
+   }
+
+   bson_destroy (&doc);
+}
+
+static void
+test_bson_vector_example_packed_bit_view (void)
+{
+   bson_t doc = BSON_INITIALIZER;
+
+   // bson_vector_packed_bit_view_t.rst
+   {
+      // Fill a new vector with individual boolean elements
+      {
+         static const bool bool_values[] = {true, false, true, true, false};
+         const size_t bool_values_count = sizeof bool_values / sizeof bool_values[0];
+
+         bson_vector_packed_bit_view_t view;
+         ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "from_bool", bool_values_count, &view));
+         ASSERT (bson_vector_packed_bit_view_pack_bool (view, bool_values, bool_values_count, 0));
+      }
+
+      // Fill another new vector with packed bytes
+      {
+         static const uint8_t packed_bytes[] = {0xb0};
+         const size_t unused_bits_count = 3;
+         const size_t packed_values_count = sizeof packed_bytes * 8 - unused_bits_count;
+
+         bson_vector_packed_bit_view_t view;
+         ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "from_packed", packed_values_count, &view));
+         ASSERT (bson_vector_packed_bit_view_write_packed (view, packed_bytes, sizeof packed_bytes, 0));
+      }
+
+      // Compare both vectors. They match exactly.
+      {
+         bson_iter_t from_bool_iter, from_packed_iter;
+         ASSERT (bson_iter_init_find (&from_bool_iter, &doc, "from_bool"));
+         ASSERT (bson_iter_init_find (&from_packed_iter, &doc, "from_packed"));
+         ASSERT (bson_iter_binary_equal (&from_bool_iter, &from_packed_iter));
+      }
+   }
+
+   bson_destroy (&doc);
+}
+
+// Shared edge case tests that apply to all reader/writer functions.
+#define TEST_BSON_VECTOR_RW(_expected, _view, _v, _count, _offset, _read, _write) \
+   if (true) {                                                                    \
+      ASSERT ((_expected) == (_write) ((_view), (_v), (_count), (_offset)));      \
+      ASSERT ((_expected) == (_read) ((_view), (_v), (_count), (_offset)));       \
+   } else                                                                         \
+      ((void) 0)
+
+#if defined(__USE_FORTIFY_LEVEL) && __USE_FORTIFY_LEVEL > 0
+// Prevent memcpy size overflows even in dead code
+#define MAX_TESTABLE_COPY_COUNT (SIZE_MAX / 2u / sizeof (float))
+#else
+// Allow dead code to contain an oversized or overflowing memcpy
+#define MAX_TESTABLE_COPY_COUNT SIZE_MAX
+#endif
+
+#define TEST_BSON_VECTOR_EDGE_CASES_RW_COMMON(_view, _alloc_size, _v, _v_size, _read, _write)                   \
+   if (true) {                                                                                                  \
+      TEST_BSON_VECTOR_RW (false, (_view), (_v), (_alloc_size) + 1u, 0, (_read), (_write));                     \
+      TEST_BSON_VECTOR_RW (true, (_view), (_v), (_v_size), (_alloc_size) - (_v_size), (_read), (_write));       \
+      TEST_BSON_VECTOR_RW (false, (_view), (_v), (_v_size), (_alloc_size) - (_v_size) + 1u, (_read), (_write)); \
+      TEST_BSON_VECTOR_RW (false, (_view), (_v), (_v_size) + 1u, (_alloc_size) - (_v_size), (_read), (_write)); \
+      TEST_BSON_VECTOR_RW (                                                                                     \
+         false, (_view), (_v), MAX_TESTABLE_COPY_COUNT, (_alloc_size) - (_v_size), (_read), (_write));          \
+      TEST_BSON_VECTOR_RW (                                                                                     \
+         false, (_view), (_v), MAX_TESTABLE_COPY_COUNT, (_alloc_size) - (_v_size) + 1u, (_read), (_write));     \
+      TEST_BSON_VECTOR_RW (true, (_view), (_v), (_v_size), 0, (_read), (_write));                               \
+   } else                                                                                                       \
+      ((void) 0)
+
+static void
+test_bson_vector_edge_cases_int8 (void)
+{
+   size_t max_representable_elements = (size_t) UINT32_MAX - BSON_VECTOR_HEADER_LEN;
+
+   // Test binary_data_length (uint32_t) edge cases, without any allocation.
+   {
+      ASSERT_CMPUINT32 (bson_vector_int8_binary_data_length (max_representable_elements - 1u), ==, UINT32_MAX - 1u);
+      ASSERT_CMPUINT32 (bson_vector_int8_binary_data_length (max_representable_elements), ==, UINT32_MAX);
+      ASSERT_CMPUINT32 (bson_vector_int8_binary_data_length (max_representable_elements + 1u), ==, 0);
+   }
+
+   // Needs little real memory because most bytes are never accessed,
+   // but we should require a virtual address space larger than 32 bits.
+#if BSON_WORD_SIZE > 32
+
+   size_t expected_bson_overhead =
+      5 /* empty bson document */ + 3 /* "v" element header */ + 5 /* binary item header */;
+   size_t max_alloc_elements = (size_t) BSON_MAX_SIZE - expected_bson_overhead - BSON_VECTOR_HEADER_LEN;
+
+   bson_t doc = BSON_INITIALIZER;
+   bson_vector_int8_view_t view;
+
+   // Test allocation (BSON_MAX_SIZE + uint32_t) edge cases.
+   {
+      ASSERT (!BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "v", max_representable_elements, &view));
+      ASSERT (!BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "v", max_representable_elements + 1u, &view));
+      ASSERT (!BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "v", max_alloc_elements + 1u, &view));
+      ASSERT (BSON_APPEND_VECTOR_INT8_UNINIT (&doc, "v", max_alloc_elements, &view));
+   }
+
+   // Test some read and write boundaries.
+   {
+      size_t values_size = 100;
+      int8_t *values = bson_malloc0 (values_size * sizeof *values);
+      TEST_BSON_VECTOR_EDGE_CASES_RW_COMMON (
+         view, max_alloc_elements, values, values_size, bson_vector_int8_view_read, bson_vector_int8_view_write);
+      bson_free (values);
+   }
+
+   bson_destroy (&doc);
+#endif // BSON_WORD_SIZE > 32
+}
+
+static void
+test_bson_vector_edge_cases_float32 (void)
+{
+   size_t max_representable_elements = ((size_t) UINT32_MAX - BSON_VECTOR_HEADER_LEN) / sizeof (float);
+
+   // Test binary_data_length (uint32_t) edge cases, without any allocation.
+   // Note that the longest possible multiple of a complete element is 1 byte short of UINT32_MAX.
+   {
+      ASSERT_CMPUINT32 (
+         bson_vector_float32_binary_data_length (max_representable_elements - 1u), ==, UINT32_MAX - 1u - 4u);
+      ASSERT_CMPUINT32 (bson_vector_float32_binary_data_length (max_representable_elements), ==, UINT32_MAX - 1u);
+      ASSERT_CMPUINT32 (bson_vector_float32_binary_data_length (max_representable_elements + 1u), ==, 0);
+   }
+
+   // Needs little real memory because most bytes are never accessed,
+   // but we should require a virtual address space larger than 32 bits.
+#if BSON_WORD_SIZE > 32
+
+   size_t expected_bson_overhead =
+      5 /* empty bson document */ + 3 /* "v" element header */ + 5 /* binary item header */;
+   size_t max_alloc_elements =
+      ((size_t) BSON_MAX_SIZE - expected_bson_overhead - BSON_VECTOR_HEADER_LEN) / sizeof (float);
+
+   bson_t doc = BSON_INITIALIZER;
+   bson_vector_float32_view_t view;
+
+   // Test allocation (BSON_MAX_SIZE + uint32_t) edge cases.
+   {
+      ASSERT (!BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "v", max_representable_elements, &view));
+      ASSERT (!BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "v", max_representable_elements + 1u, &view));
+      ASSERT (!BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "v", max_alloc_elements + 1u, &view));
+      ASSERT (BSON_APPEND_VECTOR_FLOAT32_UNINIT (&doc, "v", max_alloc_elements, &view));
+   }
+
+   // Test some read and write boundaries.
+   {
+      size_t values_size = 100;
+      float *values = bson_malloc0 (values_size * sizeof *values);
+      TEST_BSON_VECTOR_EDGE_CASES_RW_COMMON (
+         view, max_alloc_elements, values, values_size, bson_vector_float32_view_read, bson_vector_float32_view_write);
+      bson_free (values);
+   }
+
+   bson_destroy (&doc);
+#endif // BSON_WORD_SIZE > 32
+}
+
+static void
+test_bson_vector_edge_cases_packed_bit (void)
+{
+   // Test UINT32_MAX as an element count. This is the largest representable on systems with a 32-bit size_t.
+   uint32_t len_for_max_count = (uint32_t) (((uint64_t) UINT32_MAX + 7u) / 8u + BSON_VECTOR_HEADER_LEN);
+   {
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX), ==, len_for_max_count);
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX - 1u), ==, len_for_max_count);
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX - 6u), ==, len_for_max_count);
+      ASSERT_CMPUINT32 (
+         bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX - 7u), ==, len_for_max_count - 1u);
+      ASSERT_CMPUINT32 (
+         bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX - 8u), ==, len_for_max_count - 1u);
+   }
+
+   // Test the real max_representable_elements only if size_t is large enough.
+#if SIZE_MAX > UINT32_MAX
+   size_t max_representable_elements = ((size_t) UINT32_MAX - BSON_VECTOR_HEADER_LEN) * 8u;
+
+   // Test binary_data_length (uint32_t) edge cases, without any allocation.
+   {
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX + 1u), ==, len_for_max_count);
+      ASSERT_CMPUINT32 (
+         bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX + 2u), ==, len_for_max_count + 1u);
+      ASSERT_CMPUINT32 (
+         bson_vector_packed_bit_binary_data_length ((size_t) UINT32_MAX + 9u), ==, len_for_max_count + 1u);
+      ASSERT_CMPUINT32 (
+         bson_vector_packed_bit_binary_data_length (max_representable_elements - 8u), ==, UINT32_MAX - 1u);
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length (max_representable_elements - 7u), ==, UINT32_MAX);
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length (max_representable_elements), ==, UINT32_MAX);
+      ASSERT_CMPUINT32 (bson_vector_packed_bit_binary_data_length (max_representable_elements + 1u), ==, 0);
+   }
+#endif // SIZE_MAX > UINT32_MAX
+
+   // If we additionally have a 64-bit address space, allocate this max-sized vector and run tests.
+   // Needs little real memory because most bytes are never accessed.
+#if BSON_WORD_SIZE > 32
+
+#if !(SIZE_MAX > UINT32_MAX)
+#error 64-bit platforms should have a 64-bit size_t
+#endif
+
+   size_t expected_bson_overhead =
+      5 /* empty bson document */ + 3 /* "v" element header */ + 5 /* binary item header */;
+   size_t max_alloc_bytes = (size_t) BSON_MAX_SIZE - expected_bson_overhead - BSON_VECTOR_HEADER_LEN;
+   size_t max_alloc_elements = max_alloc_bytes * 8u;
+
+   bson_t doc = BSON_INITIALIZER;
+   bson_vector_packed_bit_view_t view;
+
+   // Test allocation (BSON_MAX_SIZE + uint32_t) edge cases.
+   {
+      ASSERT (!BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "v", max_representable_elements, &view));
+      ASSERT (!BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "v", max_representable_elements + 1u, &view));
+      ASSERT (!BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "v", max_alloc_elements + 1u, &view));
+      ASSERT (BSON_APPEND_VECTOR_PACKED_BIT_UNINIT (&doc, "v", max_alloc_elements, &view));
+   }
+
+   // Test pack and unpack boundaries with the same tests used for read/write of non-packed element types.
+   // Only tests one length, but it's chosen to be greater than 8 and not a multiple of 8.
+   {
+      size_t values_size = 190;
+      bool *values = bson_malloc0 (values_size * sizeof *values);
+      TEST_BSON_VECTOR_EDGE_CASES_RW_COMMON (view,
+                                             max_alloc_elements,
+                                             values,
+                                             values_size,
+                                             bson_vector_packed_bit_view_unpack_bool,
+                                             bson_vector_packed_bit_view_pack_bool);
+      bson_free (values);
+   }
+
+   // Test read and write boundaries on packed bytes.
+   {
+      size_t packed_size = 50;
+      uint8_t *packed = bson_malloc0 (packed_size);
+      TEST_BSON_VECTOR_EDGE_CASES_RW_COMMON (view,
+                                             max_alloc_bytes,
+                                             packed,
+                                             packed_size,
+                                             bson_vector_packed_bit_view_read_packed,
+                                             bson_vector_packed_bit_view_write_packed);
+      bson_free (packed);
+   }
+
+   bson_destroy (&doc);
+#endif // BSON_WORD_SIZE > 32
+}
+
+void
+test_bson_vector_install (TestSuite *suite)
+{
+   install_json_test_suite_with_check (suite, BSON_JSON_DIR, "bson_binary_vector", test_bson_vector_json_cb);
+
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/usage/int8", test_bson_vector_view_api_usage_int8);
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/usage/float32", test_bson_vector_view_api_usage_float32);
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/usage/packed_bit", test_bson_vector_view_api_usage_packed_bit);
+
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/fuzz/int8", test_bson_vector_view_api_fuzz_int8);
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/fuzz/float32", test_bson_vector_view_api_fuzz_float32);
+   TestSuite_Add (suite, "/bson_binary_vector/view_api/fuzz/packed_bit", test_bson_vector_view_api_fuzz_packed_bit);
+
+   TestSuite_Add (suite, "/bson_binary_vector/example/int8_const_view", test_bson_vector_example_int8_const_view);
+   TestSuite_Add (suite, "/bson_binary_vector/example/int8_view", test_bson_vector_example_int8_view);
+   TestSuite_Add (suite, "/bson_binary_vector/example/float32_const_view", test_bson_vector_example_float32_const_view);
+   TestSuite_Add (suite, "/bson_binary_vector/example/float32_view", test_bson_vector_example_float32_view);
+   TestSuite_Add (
+      suite, "/bson_binary_vector/example/packed_bit_const_view", test_bson_vector_example_packed_bit_const_view);
+   TestSuite_Add (suite, "/bson_binary_vector/example/packed_bit_view", test_bson_vector_example_packed_bit_view);
+
+   TestSuite_Add (suite, "/bson_binary_vector/edge_cases/int8", test_bson_vector_edge_cases_int8);
+   TestSuite_Add (suite, "/bson_binary_vector/edge_cases/float32", test_bson_vector_edge_cases_float32);
+   TestSuite_Add (suite, "/bson_binary_vector/edge_cases/packed_bit", test_bson_vector_edge_cases_packed_bit);
+}
diff -pruN 1.30.4-1/src/libbson/tests/test-bson.c 2.0.2-1/src/libbson/tests/test-bson.c
--- 1.30.4-1/src/libbson/tests/test-bson.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-bson.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <bson/bson.h>
 #include <bson/bcon.h>
 #include <bson/bson-private.h>
+#include <bson/validate-private.h>
 #include <fcntl.h>
 #include <time.h>
 
@@ -26,6 +27,10 @@
 #include "TestSuite.h"
 #include "test-conveniences.h"
 
+#include <mlib/ckdint.h>
+#include <mlib/test.h>
+#include <mlib/intencode.h>
+
 /* CDRIVER-2460 ensure the unused old BSON_ASSERT_STATIC macro still compiles */
 BSON_STATIC_ASSERT (1 == 1);
 
@@ -853,272 +858,61 @@ test_bson_append_deep (void)
 
 
 static void
-test_bson_validate_dbref (void)
-{
-   size_t offset;
-   bson_t dbref, child, child2;
-
-   /* should fail, $ref without an $id */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with non id field */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "extra", "field");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $id at the top */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_UTF8 (&dbref, "$ref", "foo");
-      BSON_APPEND_UTF8 (&dbref, "$id", "bar");
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $id not first keys */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "extra", "field");
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $db */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$db", "bar");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, non-string $ref with $id */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_INT32 (&child, "$ref", 1);
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, non-string $ref with nothing */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_INT32 (&child, "$ref", 1);
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $id with non-string $db */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      BSON_APPEND_INT32 (&child, "$db", 1);
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $id with non-string $db with stuff after */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      BSON_APPEND_INT32 (&child, "$db", 1);
-      BSON_APPEND_UTF8 (&child, "extra", "field");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should fail, $ref with $id with stuff, then $db */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      BSON_APPEND_UTF8 (&child, "extra", "field");
-      BSON_APPEND_UTF8 (&child, "$db", "baz");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should succeed, $ref with $id */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should succeed, $ref with nested dbref $id */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_DOCUMENT_BEGIN (&child, "$id", &child2);
-      BSON_APPEND_UTF8 (&child2, "$ref", "foo2");
-      BSON_APPEND_UTF8 (&child2, "$id", "bar2");
-      BSON_APPEND_UTF8 (&child2, "$db", "baz2");
-      bson_append_document_end (&child, &child2);
-      BSON_APPEND_UTF8 (&child, "$db", "baz");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should succeed, $ref with $id and $db */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      BSON_APPEND_UTF8 (&child, "$db", "baz");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-
-   /* should succeed, $ref with $id and $db and trailing */
-   {
-      bson_init (&dbref);
-      BSON_APPEND_DOCUMENT_BEGIN (&dbref, "dbref", &child);
-      BSON_APPEND_UTF8 (&child, "$ref", "foo");
-      BSON_APPEND_UTF8 (&child, "$id", "bar");
-      BSON_APPEND_UTF8 (&child, "$db", "baz");
-      BSON_APPEND_UTF8 (&child, "extra", "field");
-      bson_append_document_end (&dbref, &child);
-
-      BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset));
-
-      bson_destroy (&dbref);
-   }
-}
-
-
-/* BSON spec requires bool value to be exactly 0 or 1 */
-static void
-test_bson_validate_bool (void)
+_make_deep_bson (bson_t *const dst, const size_t depth)
 {
-   /* {"b": true}, with implicit NULL at end */
-   uint8_t data[] = "\x09\x00\x00\x00\x08\x62\x00\x01";
-   bson_t bson;
-   bson_iter_t iter;
-   size_t err_offset = 0;
-
-   ASSERT (bson_init_static (&bson, data, sizeof data));
-   ASSERT (bson_validate (&bson, BSON_VALIDATE_NONE, &err_offset));
-   ASSERT (bson_iter_init (&iter, &bson));
-   ASSERT (bson_iter_next (&iter));
-   ASSERT (BSON_ITER_HOLDS_BOOL (&iter));
-   ASSERT (bson_iter_bool (&iter));
-
-   /* replace boolean value 1 with 255 */
-   ASSERT (data[7] == '\x01');
-   data[7] = (uint8_t) '\xff';
-
-   ASSERT (bson_init_static (&bson, data, 9));
-   ASSERT (!bson_validate (&bson, BSON_VALIDATE_NONE, &err_offset));
-   ASSERT_CMPSIZE_T (err_offset, ==, (size_t) 7);
-
-   ASSERT (bson_iter_init (&iter, &bson));
-   ASSERT (!bson_iter_next (&iter));
+   const size_t n_docs = depth + 1;
+   // Needed size: 5 bytes for doc header/trailer, 2 bytes for each tag and empty
+   // key, minus 2 because the outer document has no tag and key
+   const size_t buffer_size = (n_docs * (5 + 2)) - 2;
+   uint8_t *const buffer = calloc (buffer_size, 1);
+   mlib_check (buffer);
+   uint8_t *out = buffer;
+   mlib_foreach_urange (i, n_docs) {
+      // Bytes we have already written:
+      const size_t begin_offset = (size_t) (out - buffer);
+      // The number of bytes for this inner doc:
+      size_t inner_size = buffer_size;
+      mlib_check (!mlib_sub (&inner_size, begin_offset));
+      mlib_check (!mlib_sub (&inner_size, i));
+      // Write a header:
+      out = (uint8_t *) mlib_write_i32le (out, mlib_assert_narrow (int32_t, inner_size));
+      // Add a new element header if we're not at the innermost doc
+      if (!loop.last) {
+         *out++ = 0x3; // Document tag
+         ++out;        // Leave a null terminator to make a "" key string
+      }
+   }
+   bson_t big;
+   mlib_check (bson_init_static (&big, buffer, buffer_size));
+   bson_copy_to (&big, dst);
+   free (buffer);
 }
 
-
-/* BSON spec requires the deprecated DBPointer's value to be NULL-termed */
+/**
+ * @brief Test case: Check that we stop validating if we go too deep.
+ *
+ * The current validation is implemented as a simple recursive algorithm. This
+ * is fast since it doesn't allocate, but we risk blowing out the stack if the
+ * data is too deep. We don't want to crash user applications because of untrusted
+ * input, so assert that we stop when we hit a reasonably high depth.
+ */
 static void
-test_bson_validate_dbpointer (void)
+test_bson_validate_deep (void)
 {
-   /* { "a": DBPointer(ObjectId(...), Collection="b") }, implicit NULL at end */
-   uint8_t data[] = "\x1A\x00\x00\x00\x0C\x61\x00\x02\x00\x00\x00\x62\x00"
-                    "\x56\xE1\xFC\x72\xE0\xC9\x17\xE9\xC4\x71\x41\x61";
-
-   bson_t bson;
-   bson_iter_t iter;
-   size_t err_offset = 0;
-   uint32_t collection_len;
-   const char *collection;
-   const bson_oid_t *oid;
-
-   ASSERT (bson_init_static (&bson, data, sizeof data));
-   ASSERT (bson_validate (&bson, BSON_VALIDATE_NONE, &err_offset));
-   ASSERT (bson_iter_init (&iter, &bson));
-   ASSERT (bson_iter_next (&iter));
-   ASSERT (BSON_ITER_HOLDS_DBPOINTER (&iter));
-   bson_iter_dbpointer (&iter, &collection_len, &collection, &oid);
-   ASSERT_CMPSTR (collection, "b");
-   ASSERT_CMPINT (collection_len, ==, 1);
-
-   /* replace the NULL terminator of "b" with 255 */
-   ASSERT (data[12] == '\0');
-   data[12] = (uint8_t) '\xff';
-
-   ASSERT (bson_init_static (&bson, data, sizeof data));
-   ASSERT (!bson_validate (&bson, BSON_VALIDATE_NONE, &err_offset));
-   ASSERT_CMPSIZE_T (err_offset, ==, (size_t) 12);
-
-   ASSERT (bson_iter_init (&iter, &bson));
-   ASSERT (!bson_iter_next (&iter));
+   bson_t deep;
+   // Just barely too deep
+   _make_deep_bson (&deep, BSON_VALIDATION_MAX_NESTING_DEPTH + 1);
+   bson_error_t err;
+   mlib_check (!bson_validate_with_error (&deep, 0, &err));
+   mlib_check (err.code, eq, BSON_VALIDATE_CORRUPT);
+   mlib_check (err.message, str_eq, "BSON document nesting depth is too deep");
+   bson_destroy (&deep);
+   // At the limit
+   _make_deep_bson (&deep, BSON_VALIDATION_MAX_NESTING_DEPTH);
+   mlib_check (bson_validate (&deep, 0, NULL));
+   bson_destroy (&deep);
 }
 
-
 static void
 test_bson_validate_with_error_and_offset (void)
 {
@@ -1132,108 +926,6 @@ test_bson_validate_with_error_and_offset
 
 
 static void
-test_bson_validate (void)
-{
-   char filename[64];
-   size_t offset;
-   bson_t *b;
-   int i;
-   bson_error_t error;
-
-   for (i = 1; i <= 38; i++) {
-      bson_snprintf (filename, sizeof filename, "test%d.bson", i);
-      b = get_bson (filename);
-      BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
-      bson_destroy (b);
-   }
-
-   b = get_bson ("codewscope.bson");
-   BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
-   bson_destroy (b);
-
-   b = get_bson ("empty_key.bson");
-   BSON_ASSERT (bson_validate (
-      b, BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 | BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, &offset));
-   bson_destroy (b);
-
-#define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg)                      \
-   b = get_bson (_filename);                                                        \
-   BSON_ASSERT (!bson_validate_with_error_and_offset (b, _flags, &offset, &error)); \
-   ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset);                                 \
-   ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg);                  \
-   bson_destroy (b)
-
-   VALIDATE_TEST ("overflow2.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("trailingnull.bson", BSON_VALIDATE_NONE, 14, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("dollarquery.bson",
-                  BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
-                  4,
-                  BSON_VALIDATE_DOLLAR_KEYS,
-                  "keys cannot begin with \"$\": \"$query\"");
-   VALIDATE_TEST ("dotquery.bson",
-                  BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
-                  4,
-                  BSON_VALIDATE_DOT_KEYS,
-                  "keys cannot contain \".\": \"abc.def\"");
-   VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   /* same outcome as above, despite different flags */
-   VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_UTF8, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("overflow4.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("empty_key.bson", BSON_VALIDATE_EMPTY_KEYS, 4, BSON_VALIDATE_EMPTY_KEYS, "empty key");
-   VALIDATE_TEST ("test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test50.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope");
-   VALIDATE_TEST ("test51.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope");
-   VALIDATE_TEST ("test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test54.bson", BSON_VALIDATE_NONE, 12, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test59.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
-   VALIDATE_TEST ("test60.bson", BSON_VALIDATE_NONE, 4, BSON_VALIDATE_NONE, "corrupt BSON");
-
-   /* DBRef validation */
-   b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "}");
-   BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
-   BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
-   bson_destroy (b);
-
-   /* needs "$ref" before "$id" */
-   b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}");
-   BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
-   BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
-   ASSERT_ERROR_CONTAINS (
-      error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$id\"");
-   bson_destroy (b);
-
-   /* two $refs */
-   b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$ref", BCON_UTF8 ("collection"), "}");
-   BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
-   BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
-   ASSERT_ERROR_CONTAINS (
-      error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$ref\"");
-   bson_destroy (b);
-
-   /* must not contain invalid key like "extra" */
-   b =
-      BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "extra", BCON_INT32 (2), "$id", BCON_INT32 (1), "}");
-   BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
-   BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
-   ASSERT_ERROR_CONTAINS (
-      error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "invalid key within DBRef subdocument: \"extra\"");
-   bson_destroy (b);
-
-#undef VALIDATE_TEST
-}
-
-
-static void
 test_bson_init (void)
 {
    bson_t b;
@@ -1279,11 +971,9 @@ test_bson_new_from_buffer (void)
 {
    // Buffer size matches document size
    {
-      uint8_t *buf = bson_malloc0 (5);
       size_t len = 5;
-      uint32_t len_le = BSON_UINT32_TO_LE (5);
-
-      memcpy (buf, &len_le, sizeof (len_le));
+      uint8_t *buf = bson_malloc0 (5);
+      mlib_write_i32le (buf, 5);
 
       bson_t *b = bson_new_from_buffer (&buf, &len, bson_realloc_ctx, NULL);
 
@@ -1815,7 +1505,6 @@ test_bson_steal (void)
    uint8_t *alloc;
    uint8_t *buf;
    size_t len;
-   uint32_t len_le;
 
    /* inline, stack-allocated */
    bson_init (&stack_alloced);
@@ -1861,8 +1550,7 @@ test_bson_steal (void)
    /* test stealing from a bson created with bson_new_from_buffer */
    buf = bson_malloc0 (5);
    len = 5;
-   len_le = BSON_UINT32_TO_LE (5);
-   memcpy (buf, &len_le, sizeof (len_le));
+   mlib_write_u32le (buf, 5);
    heap_alloced = bson_new_from_buffer (&buf, &len, bson_realloc_ctx, NULL);
    ASSERT (bson_steal (&dst, heap_alloced));
    ASSERT (dst.flags & BSON_FLAG_NO_FREE);
@@ -1947,7 +1635,6 @@ test_bson_reserve_buffer_errors (void)
    bson_t bson = BSON_INITIALIZER;
    bson_t child;
    uint8_t data[5] = {0};
-   uint32_t len_le;
 
    /* too big */
    ASSERT (!bson_reserve_buffer (&bson, (uint32_t) (BSON_MAX_SIZE + 1u)));
@@ -1959,8 +1646,7 @@ test_bson_reserve_buffer_errors (void)
    bson_destroy (&bson);
 
    /* make a static bson, it refuses bson_reserve_buffer since it's read-only */
-   len_le = BSON_UINT32_TO_LE (5);
-   memcpy (data, &len_le, sizeof (len_le));
+   mlib_write_u32le (data, 5);
    ASSERT (bson_init_static (&bson, data, sizeof data));
    ASSERT (!bson_reserve_buffer (&bson, 10));
 
@@ -2721,7 +2407,7 @@ test_bson_dsl_build (void)
    // Insert a subdoc
    bson_t *subdoc = TMP_BSON_FROM_JSON ({"child" : [ 1, 2, 3 ], "other" : null});
 
-   bsonBuild (doc, kv ("subdoc", doc (insert (*subdoc, true))));
+   bsonBuild (doc, kv ("subdoc", doc (insert (*subdoc, always))));
    ASSERT_BSON_EQUAL (doc, {"subdoc" : {"child" : [ 1, 2, 3 ], "other" : null}});
    bson_destroy (&doc);
 
@@ -2736,7 +2422,7 @@ test_bson_dsl_build (void)
                   doc (kv ("inner1", array ()),
                        kv ("inner2", null),
                        kv ("inner3", array (int32 (1), int32 (2), int32 (3))),
-                       insert (*subdoc, true),
+                       insert (*subdoc, always),
                        kv ("inner4", doc (kv ("innermost", int32 (42)))))));
    ASSERT_BSON_EQUAL (doc, {
       "top" : {
@@ -3314,10 +3000,7 @@ test_bson_install (TestSuite *suite)
    TestSuite_Add (suite, "/bson/append_general", test_bson_append_general);
    TestSuite_Add (suite, "/bson/append_deep", test_bson_append_deep);
    TestSuite_Add (suite, "/bson/utf8_key", test_bson_utf8_key);
-   TestSuite_Add (suite, "/bson/validate", test_bson_validate);
-   TestSuite_Add (suite, "/bson/validate/dbref", test_bson_validate_dbref);
-   TestSuite_Add (suite, "/bson/validate/bool", test_bson_validate_bool);
-   TestSuite_Add (suite, "/bson/validate/dbpointer", test_bson_validate_dbpointer);
+   TestSuite_Add (suite, "/bson/validate/deep", test_bson_validate_deep);
    TestSuite_Add (suite, "/bson/validate/with_error_and_offset", test_bson_validate_with_error_and_offset);
    TestSuite_Add (suite, "/bson/new_1mm", test_bson_new_1mm);
    TestSuite_Add (suite, "/bson/init_1mm", test_bson_init_1mm);
diff -pruN 1.30.4-1/src/libbson/tests/test-iso8601.c 2.0.2-1/src/libbson/tests/test-iso8601.c
--- 1.30.4-1/src/libbson/tests/test-iso8601.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-iso8601.c	2025-06-19 15:42:22.000000000 +0000
@@ -2,7 +2,7 @@
 
 #include <bson/bson-iso8601-private.h>
 #include "TestSuite.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-string-private.h>
 #include <common-json-private.h>
 
@@ -16,7 +16,7 @@ test_date (const char *str, int64_t mill
 
    const size_t len = strlen (str);
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, len));
+   BSON_ASSERT (mlib_in_range (int32_t, len));
 
    if (!_bson_iso8601_date_parse (str, (int32_t) len, &v, &error)) {
       fprintf (stderr, "could not parse (%s)\n", str);
@@ -61,7 +61,7 @@ test_date_should_fail (const char *str)
 
    const size_t len = strlen (str);
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, len));
+   BSON_ASSERT (mlib_in_range (int32_t, len));
 
    if (_bson_iso8601_date_parse (str, (int32_t) len, &v, &error)) {
       fprintf (stderr, "should not be able to parse (%s)\n", str);
diff -pruN 1.30.4-1/src/libbson/tests/test-iter.c 2.0.2-1/src/libbson/tests/test-iter.c
--- 1.30.4-1/src/libbson/tests/test-iter.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-iter.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <bson/bson.h>
 
 #include "TestSuite.h"
+#include <mlib/intencode.h>
 
 #define FUZZ_N_PASSES 100000
 
@@ -205,18 +206,15 @@ test_bson_iter_fuzz (void)
 {
    uint8_t *data;
    uint32_t len = 512;
-   uint32_t len_le;
    uint32_t r;
    bson_iter_t iter;
    bson_t *b;
    uint32_t i;
    int pass;
 
-   len_le = BSON_UINT32_TO_LE (len);
-
    for (pass = 0; pass < FUZZ_N_PASSES; pass++) {
       data = bson_malloc0 (len);
-      memcpy (data, &len_le, sizeof (len_le));
+      mlib_write_u32le (data, len);
 
       for (i = 4; i < len; i += 4) {
          r = rand ();
@@ -253,8 +251,7 @@ test_bson_iter_fuzz (void)
                BSON_ASSERT (child_len >= 5);
                BSON_ASSERT ((iter.off + child_len) < b->len);
                BSON_ASSERT (child_len < (uint32_t) -1);
-               memcpy (&child_len, child, sizeof (child_len));
-               child_len = BSON_UINT32_FROM_LE (child_len);
+               child_len = mlib_read_u32le (child);
                BSON_ASSERT (child_len >= 5);
             }
          } break;
diff -pruN 1.30.4-1/src/libbson/tests/test-json.c 2.0.2-1/src/libbson/tests/test-json.c
--- 1.30.4-1/src/libbson/tests/test-json.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-json.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,7 @@
 /* required on old Windows for rand_s to be defined */
+#ifdef _WIN32
 #define _CRT_RAND_S
+#endif
 
 #include <bson/bson.h>
 #include <math.h>
@@ -7,7 +9,7 @@
 #include "TestSuite.h"
 #include "test-conveniences.h"
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-json-private.h>
 #include <bson/bson-iso8601-private.h>
 #include <bson/bson-json-private.h>
@@ -1191,7 +1193,7 @@ test_bson_json_error (const char *json,
    bson = bson_new_from_json ((const uint8_t *) json, strlen (json), &error);
 
    BSON_ASSERT (!bson);
-   BSON_ASSERT (error.domain == domain);
+   BSON_ASSERT (mlib_cmp (error.domain, ==, domain));
    BSON_ASSERT (error.code == code);
 }
 
@@ -2718,7 +2720,7 @@ test_bson_as_json_with_opts (bson_t *bso
    ASSERT_CMPSIZE_T (json_len, ==, strlen (expected));
 
    if (max_len != BSON_MAX_LEN_UNLIMITED) {
-      ASSERT (mcommon_in_range_signed (size_t, max_len));
+      ASSERT (mlib_in_range (size_t, max_len));
       ASSERT_CMPSIZE_T (json_len, <=, (size_t) max_len);
    }
 
@@ -2747,7 +2749,7 @@ run_bson_as_json_with_opts_tests (bson_t
    const size_t ulen = strlen (expected);
    char *truncated;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int, ulen));
+   BSON_ASSERT (mlib_in_range (int, ulen));
    const int len = (int) ulen;
 
    /* Test with 0 length (empty string). */
@@ -3213,7 +3215,7 @@ _test_bson_json_utf8_truncation (bson_t
          if (arg < 0) {
             BSON_ASSERT (arg == -1);
             break;
-         } else if (arg == checking_len) {
+         } else if (mlib_cmp (arg, ==, checking_len)) {
             expect_truncation_here = false;
          }
       }
diff -pruN 1.30.4-1/src/libbson/tests/test-oid.c 2.0.2-1/src/libbson/tests/test-oid.c
--- 1.30.4-1/src/libbson/tests/test-oid.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-oid.c	2025-06-19 15:42:22.000000000 +0000
@@ -205,28 +205,6 @@ test_bson_oid_init (void)
 }
 
 
-static void
-test_bson_oid_init_sequence (void)
-{
-   bson_context_t *context;
-   bson_oid_t oid;
-   bson_oid_t oid2;
-   int i;
-
-   BEGIN_IGNORE_DEPRECATIONS
-   context = bson_context_new (BSON_CONTEXT_NONE);
-   bson_oid_init_sequence (&oid, context);
-   for (i = 0; i < 10000; i++) {
-      bson_oid_init_sequence (&oid2, context);
-      BSON_ASSERT (false == bson_oid_equal (&oid, &oid2));
-      BSON_ASSERT (0 > bson_oid_compare (&oid, &oid2));
-      bson_oid_copy (&oid2, &oid);
-   }
-   bson_context_destroy (context);
-   END_IGNORE_DEPRECATIONS
-}
-
-
 static char *
 get_time_as_string (const bson_oid_t *oid)
 {
@@ -476,7 +454,6 @@ test_oid_install (TestSuite *suite)
 {
    TestSuite_Add (suite, "/bson/oid/init", test_bson_oid_init);
    TestSuite_Add (suite, "/bson/oid/init_from_string", test_bson_oid_init_from_string);
-   TestSuite_Add (suite, "/bson/oid/init_sequence", test_bson_oid_init_sequence);
    TestSuite_Add (suite, "/bson/oid/init_with_threads", test_bson_oid_init_with_threads);
    TestSuite_Add (suite, "/bson/oid/hash", test_bson_oid_hash);
    TestSuite_Add (suite, "/bson/oid/compare", test_bson_oid_compare);
diff -pruN 1.30.4-1/src/libbson/tests/test-string.c 2.0.2-1/src/libbson/tests/test-string.c
--- 1.30.4-1/src/libbson/tests/test-string.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-string.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,136 +22,6 @@
 #include "TestSuite.h"
 #include "test-libmongoc.h"
 
-
-static void
-test_bson_string_new (void)
-{
-   bson_string_t *str;
-   char *s;
-
-   str = bson_string_new (NULL);
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, ""));
-   bson_free (s);
-
-   str = bson_string_new ("");
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!*s);
-   BSON_ASSERT (0 == strcmp (s, ""));
-   bson_free (s);
-
-   str = bson_string_new ("abcdef");
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, "abcdef"));
-   bson_free (s);
-
-   str = bson_string_new ("");
-   s = bson_string_free (str, true);
-   BSON_ASSERT (!s);
-}
-
-
-static void
-test_bson_string_append (void)
-{
-   bson_string_t *str;
-   char *s;
-
-   str = bson_string_new (NULL);
-   bson_string_append (str, "christian was here");
-   bson_string_append (str, "\n");
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, "christian was here\n"));
-   bson_free (s);
-
-   str = bson_string_new (">>>");
-   bson_string_append (str, "^^^");
-   bson_string_append (str, "<<<");
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, ">>>^^^<<<"));
-   bson_free (s);
-}
-
-
-static void
-test_bson_string_append_c (void)
-{
-   bson_string_t *str;
-   char *s;
-
-   str = bson_string_new (NULL);
-   bson_string_append_c (str, 'c');
-   bson_string_append_c (str, 'h');
-   bson_string_append_c (str, 'r');
-   bson_string_append_c (str, 'i');
-   bson_string_append_c (str, 's');
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, "chris"));
-   bson_free (s);
-}
-
-
-static void
-test_bson_string_append_printf (void)
-{
-   bson_string_t *str;
-
-   str = bson_string_new ("abcd ");
-   bson_string_append_printf (str, "%d %d %d", 1, 2, 3);
-   BSON_ASSERT (!strcmp (str->str, "abcd 1 2 3"));
-   bson_string_truncate (str, 2);
-   BSON_ASSERT (!strcmp (str->str, "ab"));
-   bson_string_free (str, true);
-}
-
-
-static void
-test_bson_string_append_printf_truncate (void)
-{
-   // mcommon_string_append_printf will always truncate strings between UTF-8 code points.
-   // Also see /bson/as_json_with_opts/utf8_truncation. Both tests exercise functionality implemented by
-   // mcommon_utf8_truncate_len(), but printf() uses a different path through mcommon_string.
-
-   for (uint32_t limit = 0; limit < 13; limit++) {
-      mcommon_string_append_t append;
-      mcommon_string_set_append_with_limit (mcommon_string_new (""), &append, limit);
-      mcommon_string_append_printf (&append, "foo \xf4%s%c%c bar", "\x8f", '\xbf', '\xbf');
-      const char *expected = "foo \xf4\x8f\xbf\xbf bar";
-      const char *str = mcommon_str_from_append (&append);
-      uint32_t len = mcommon_strlen_from_append (&append);
-      if (limit >= 4 && limit < 8) {
-         BSON_ASSERT (len == 4);
-      } else {
-         BSON_ASSERT (len == limit);
-      }
-      BSON_ASSERT (0 == memcmp (str, expected, len));
-      mcommon_string_from_append_destroy (&append);
-   }
-}
-
-
-static void
-test_bson_string_append_unichar (void)
-{
-   static const unsigned char test1[] = {0xe2, 0x82, 0xac, 0};
-   bson_string_t *str;
-   char *s;
-
-   str = bson_string_new (NULL);
-   bson_string_append_unichar (str, 0x20AC);
-   s = bson_string_free (str, false);
-   BSON_ASSERT (s);
-   BSON_ASSERT (!strcmp (s, (const char *) test1));
-   bson_free (s);
-}
-
-
 static void
 test_bson_strdup_printf (void)
 {
@@ -331,150 +201,9 @@ test_bson_strcasecmp (void)
    BSON_ASSERT (bson_strcasecmp ("FoZ", "foo") > 0);
 }
 
-static void
-test_bson_string_truncate (void)
-{
-   // Test truncating.
-   {
-      bson_string_t *str = bson_string_new ("foobar");
-      ASSERT_CMPSIZE_T (str->len, ==, 6u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 8u);
-
-      bson_string_truncate (str, 2);
-      ASSERT_CMPSTR (str->str, "fo");
-      ASSERT_CMPSIZE_T (str->len, ==, 2u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 4u);
-      bson_string_free (str, true);
-   }
-
-   // Test truncating to same length.
-   {
-      bson_string_t *str = bson_string_new ("foobar");
-      ASSERT_CMPSIZE_T (str->len, ==, 6u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 8u);
-
-      bson_string_truncate (str, 6u);
-      ASSERT_CMPSTR (str->str, "foobar");
-      ASSERT_CMPUINT32 (str->len, ==, 6u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 8u);
-      bson_string_free (str, true);
-   }
-
-   // Test truncating to 0.
-   {
-      bson_string_t *str = bson_string_new ("foobar");
-      ASSERT_CMPSIZE_T (str->len, ==, 6u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 8u);
-
-      bson_string_truncate (str, 0u);
-      ASSERT_CMPSTR (str->str, "");
-      ASSERT_CMPUINT32 (str->len, ==, 0u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 1u);
-      bson_string_free (str, true);
-   }
-
-   // Test truncating beyond string length.
-   // The documentation for `bson_string_truncate` says the truncated length "must be smaller or equal to the current
-   // length of the string.". However, `bson_string_truncate` does not reject greater lengths. For backwards
-   // compatibility, this behavior is preserved.
-   {
-      bson_string_t *str = bson_string_new ("a");
-      bson_string_truncate (str, 2u); // Is not rejected.
-      ASSERT_CMPUINT32 (str->len, ==, 2u);
-      ASSERT_CMPUINT32 (str->alloc, ==, 4u);
-      bson_string_free (str, true);
-   }
-
-   // Test truncating in the middle of a UTF-8 sequence, producing invalid UTF-8 as output.
-   // This is not especially desirable, but the behavior is maintained for compatibility.
-   {
-      // From RFC-3629 examples, "A<NOT IDENTICAL TO><ALPHA>."
-      bson_string_t *str = bson_string_new ("\x41\xe2\x89\xa2\xce\x91\x2e");
-      ASSERT_CMPSIZE_T (str->len, ==, 7u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 8u);
-
-      bson_string_truncate (str, 3);
-      ASSERT_CMPSTR (str->str, "\x41\xe2\x89");
-      ASSERT_CMPSIZE_T (str->len, ==, 3u);
-      ASSERT_CMPSIZE_T (str->alloc, ==, 4u);
-      bson_string_free (str, true);
-   }
-}
-
-static void
-test_bson_string_capacity (void *unused)
-{
-   BSON_UNUSED (unused);
-
-   char *large_str = bson_malloc (UINT32_MAX);
-   memset (large_str, 's', UINT32_MAX); // Do not NULL terminate. Each test case sets NULL byte.
-
-   // Test the largest possible string that can be constructed.
-   {
-      large_str[UINT32_MAX - 1u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new (large_str);
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 1u] = 's'; // Restore.
-   }
-
-   // Test appending with `bson_string_append` to get maximum size.
-   {
-      large_str[UINT32_MAX - 1u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new ("");
-      bson_string_append (str, large_str);
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 1u] = 's'; // Restore.
-   }
-
-   // Test appending with `bson_string_append_c` to get maximum size.
-   {
-      large_str[UINT32_MAX - 2u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new (large_str);
-      bson_string_append_c (str, 'c');
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 2u] = 's'; // Restore.
-   }
-
-   // Test appending with `bson_string_append_printf` to get maximum size.
-   {
-      large_str[UINT32_MAX - 2u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new (large_str);
-      bson_string_append_printf (str, "c");
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 2u] = 's'; // Restore.
-   }
-
-   // Test appending with single characters.
-   {
-      large_str[UINT32_MAX - 2u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new (large_str);
-      bson_string_append_unichar (str, (bson_unichar_t) 's');
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 2u] = 's'; // Restore.
-   }
-
-   // Can truncate strings of length close to UINT32_MAX - 1.
-   {
-      large_str[UINT32_MAX - 1u] = '\0'; // Set size.
-      bson_string_t *str = bson_string_new (large_str);
-      bson_string_truncate (str, UINT32_MAX - 2); // Truncate one character.
-      ASSERT_CMPSIZE_T (strlen (str->str), ==, UINT32_MAX - 2u);
-      bson_string_free (str, true);
-      large_str[UINT32_MAX - 1u] = 's'; // Restore.
-   }
-
-   bson_free (large_str);
-}
-
 void
 test_string_install (TestSuite *suite)
 {
-   TestSuite_Add (suite, "/bson/string/new", test_bson_string_new);
-   TestSuite_Add (suite, "/bson/string/append", test_bson_string_append);
-   TestSuite_Add (suite, "/bson/string/append_c", test_bson_string_append_c);
-   TestSuite_Add (suite, "/bson/string/append_printf", test_bson_string_append_printf);
-   TestSuite_Add (suite, "/bson/string/append_printf_truncate", test_bson_string_append_printf_truncate);
-   TestSuite_Add (suite, "/bson/string/append_unichar", test_bson_string_append_unichar);
    TestSuite_Add (suite, "/bson/string/strdup", test_bson_strdup);
    TestSuite_Add (suite, "/bson/string/strdup_printf", test_bson_strdup_printf);
    TestSuite_Add (suite, "/bson/string/strndup", test_bson_strndup);
@@ -483,7 +212,4 @@ test_string_install (TestSuite *suite)
    TestSuite_Add (suite, "/bson/string/snprintf", test_bson_snprintf);
    TestSuite_Add (suite, "/bson/string/strnlen", test_bson_strnlen);
    TestSuite_Add (suite, "/bson/string/strcasecmp", test_bson_strcasecmp);
-   TestSuite_AddFull (
-      suite, "/bson/string/capacity", test_bson_string_capacity, NULL, NULL, skip_if_no_large_allocations);
-   TestSuite_Add (suite, "/bson/string/truncate", test_bson_string_truncate);
 }
diff -pruN 1.30.4-1/src/libbson/tests/test-validate.generated.c 2.0.2-1/src/libbson/tests/test-validate.generated.c
--- 1.30.4-1/src/libbson/tests/test-validate.generated.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/test-validate.generated.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,2513 @@
+// ! This code is GENERATED! Do not edit it directly!
+// clang-format off
+
+#include <bson/bson.h>
+
+#include <mlib/test.h>
+
+#include <TestSuite.h>
+
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: empty
+static inline void _test_case_empty(void) {
+  /**
+   * Test a simple empty document object.
+   */
+  const uint8_t bytes[] = {
+    5, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: bad-element
+static inline void _test_case_bad_element(void) {
+  /**
+   * The element content is not valid
+   */
+  const uint8_t bytes[] = {
+    6, 0, 0, 0, 'f', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 6);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: invalid-type
+static inline void _test_case_invalid_type(void) {
+  /**
+   * The type tag "0x0e" is not a valid type
+   */
+  const uint8_t bytes[] = {
+    0x0d, 0, 0, 0, 0x0e, 'f', 'o', 'o', 0, 'f', 'o', 'o', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/invalid/accept
+static inline void _test_case_key_invalid_accept(void) {
+  /**
+   * The element key contains an invalid UTF-8 byte, but we accept it
+   * because we aren't doing UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x28, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, 'f', 'o', 'o', 0xff, 'b',
+    'a', 'r', 0, 4, 0, 0, 0, 'b', 'a', 'z', 0, 2, 'c', 0, 2, 0, 0, 0, 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/invalid/reject
+static inline void _test_case_key_invalid_reject(void) {
+  /**
+   * The element key is not valid UTF-8 and we reject it when we do UTF-8
+   * validation.
+   */
+  const uint8_t bytes[] = {
+    0x28, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, 'f', 'o', 'o', 0xff, 'b',
+    'a', 'r', 0, 4, 0, 0, 0, 'b', 'a', 'z', 0, 2, 'c', 0, 2, 0, 0, 0, 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/empty/accept
+static inline void _test_case_key_empty_accept(void) {
+  /**
+   * The element has an empty string key, and we accept this.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, 0, 7, 0, 0, 0, 's', 't', 'r', 'i', 'n', 'g', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/empty/reject
+static inline void _test_case_key_empty_reject(void) {
+  /**
+   * The element has an empty key, and we can reject it.
+   */
+  const uint8_t bytes[] = {
+    0x1b, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, 0, 7, 0, 0, 0, 's', 't',
+    'r', 'i', 'n', 'g', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_EMPTY_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_EMPTY_KEYS);
+  mlib_check(error.message, str_eq, "Element key cannot be an empty string");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/empty/accept-if-absent
+static inline void _test_case_key_empty_accept_if_absent(void) {
+  /**
+   * We are checking for empty keys, and accept if they are absent.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, 'f', 'o', 'o', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_EMPTY_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dot/accept
+static inline void _test_case_key_dot_accept(void) {
+  /**
+   * The element key has an ASCII dot, and we accept this since we don't
+   * ask to validate it.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'f', 'o', 'o', '.', 'b', 'a', 'r', 0, 4, 0, 0, 0, 'b',
+    'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_EMPTY_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dot/reject
+static inline void _test_case_key_dot_reject(void) {
+  /**
+   * The element has an ASCII dot, and we reject it when we ask to validate
+   * it.
+   */
+  const uint8_t bytes[] = {
+    0x1f, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, 'f', 'o', 'o', '.', 'b',
+    'a', 'r', 0, 4, 0, 0, 0, 'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOT_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOT_KEYS);
+  mlib_check(error.message, str_eq, "Disallowed '.' in element key: \"foo.bar\"");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dot/accept-if-absent
+static inline void _test_case_key_dot_accept_if_absent(void) {
+  /**
+   * We are checking for keys with dot '.', and accept if they are absent.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, 'f', 'o', 'o', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOT_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dollar/accept
+static inline void _test_case_key_dollar_accept(void) {
+  /**
+   * We can accept an element key that starts with a dollar '$' sign.
+   */
+  const uint8_t bytes[] = {
+    0x1c, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, '$', 'f', 'o', 'o', 0, 4,
+    0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dollar/reject
+static inline void _test_case_key_dollar_reject(void) {
+  /**
+   * We can reject an element key that starts with a dollar '$' sign.
+   */
+  const uint8_t bytes[] = {
+    0x1c, 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 2, '$', 'f', 'o', 'o', 0, 4,
+    0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Disallowed '$' in element key: \"$foo\"");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dollar/accept-in-middle
+static inline void _test_case_key_dollar_accept_in_middle(void) {
+  /**
+   * This contains a element key "foo$bar", but we don't reject this, as we
+   * only care about keys that *start* with dollars.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'f', 'o', 'o', '$', 'b', 'a', 'r', 0, 4, 0, 0, 0, 'b',
+    'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: key/dollar/accept-if-absent
+static inline void _test_case_key_dollar_accept_if_absent(void) {
+  /**
+   * We are validating for dollar-keys, and we accept because this document
+   * doesn't contain any such keys.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, 'f', 'o', 'o', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/simple
+static inline void _test_case_utf8_simple(void) {
+  /**
+   * Simple UTF-8 string element
+   */
+  const uint8_t bytes[] = {
+    0x1d, 0, 0, 0, 2, 's', 't', 'r', 'i', 'n', 'g', 0, 0x0c, 0, 0, 0, 's', 'o',
+    'm', 'e', 0x20, 's', 't', 'r', 'i', 'n', 'g', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/missing-null
+static inline void _test_case_utf8_missing_null(void) {
+  /**
+   * The UTF-8 element "a" contains 4 characters and declares its length of 4,
+   * but the fourth character is supposed to be a null terminator. In this case,
+   * it is the letter 'd'.
+   */
+  const uint8_t bytes[] = {
+    0x10, 0, 0, 0, 2, 'a', 0, 4, 0, 0, 0, 'a', 'b', 'c', 'd', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 14);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/length-zero
+static inline void _test_case_utf8_length_zero(void) {
+  /**
+   * UTF-8 string length must always be at least 1 for the null terminator
+   */
+  const uint8_t bytes[] = {
+    0x0c, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 6);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/length-too-short
+static inline void _test_case_utf8_length_too_short(void) {
+  /**
+   * UTF-8 string is three chars and a null terminator, but the declared length is 3 (should be 4)
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 2, 0, 3, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 12);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/header-too-large
+static inline void _test_case_utf8_header_too_large(void) {
+  /**
+   * Data { "foo": "bar" } but the declared length of "bar" is way too large.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, 'f', 'o', 'o', 0, 0xff, 0xff, 0xff, 0xff, 'b', 'a', 'r',
+    0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/valid
+static inline void _test_case_utf8_valid(void) {
+  /**
+   * Validate a valid UTF-8 string with UTF-8 validation enabled.
+   */
+  const uint8_t bytes[] = {
+    0x13, 0, 0, 0, 2, 'f', 'o', 'o', 0, 5, 0, 0, 0, 'a', 'b', 'c', 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/invalid/accept
+static inline void _test_case_utf8_invalid_accept(void) {
+  /**
+   * Validate an invalid UTF-8 string, but accept invalid UTF-8.
+   */
+  const uint8_t bytes[] = {
+    0x14, 0, 0, 0, 2, 'f', 'o', 'o', 0, 6, 0, 0, 0, 'a', 'b', 'c', 0xff, 'd', 0,
+    0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/invalid/reject
+static inline void _test_case_utf8_invalid_reject(void) {
+  /**
+   * Validate an invalid UTF-8 string, and expect rejection.
+   */
+  const uint8_t bytes[] = {
+    0x14, 0, 0, 0, 2, 'f', 'o', 'o', 0, 6, 0, 0, 0, 'a', 'b', 'c', 0xff, 'd', 0,
+    0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/valid-with-null/accept-1
+static inline void _test_case_utf8_valid_with_null_accept_1(void) {
+  /**
+   * This is a valid UTF-8 string that contains a null character. We accept
+   * it because we don't do UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'f', 'o', 'o', 0, 8, 0, 0, 0, 'a', 'b', 'c', 0, '1', '2',
+    '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/valid-with-null/accept-2
+static inline void _test_case_utf8_valid_with_null_accept_2(void) {
+  /**
+   * This is a valid UTF-8 string that contains a null character. We allow
+   * it explicitly when we request UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'f', 'o', 'o', 0, 8, 0, 0, 0, 'a', 'b', 'c', 0, '1', '2',
+    '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/valid-with-null/reject
+static inline void _test_case_utf8_valid_with_null_reject(void) {
+  /**
+   * This is a valid UTF-8 string that contains a null character. We reject
+   * this because we don't pass BSON_VALIDATE_UTF8_ALLOW_NULL.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'f', 'o', 'o', 0, 8, 0, 0, 0, 'a', 'b', 'c', 0, '1', '2',
+    '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8_ALLOW_NULL);
+  mlib_check(error.message, str_eq, "UTF-8 string contains a U+0000 (null) character");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/overlong-null/accept-1
+static inline void _test_case_utf8_overlong_null_accept_1(void) {
+  /**
+   * This is an *invalid* UTF-8 string, and contains an overlong null. We should
+   * accept it because we aren't doing UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 2, 'f', 'o', 'o', 0, 9, 0, 0, 0, 'a', 'b', 'c', 0xc0, 0x80,
+    '1', '2', '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/overlong-null/accept-2
+static inline void _test_case_utf8_overlong_null_accept_2(void) {
+  /**
+   * ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+   * 
+   * This is an *invalid* UTF-8 string, because it contains an overlong null
+   * "0xc0 0x80". Despite being invalid, we accept it because our current UTF-8
+   * validation considers the overlong null to be a valid encoding for the null
+   * codepoint (it isn't, but changing it would be a breaking change).
+   * 
+   * If/when UTF-8 validation is changed to reject overlong null, then this
+   * test should change to expect rejection the invalid UTF-8.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 2, 'f', 'o', 'o', 0, 9, 0, 0, 0, 'a', 'b', 'c', 0xc0, 0x80,
+    '1', '2', '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8/overlong-null/reject
+static inline void _test_case_utf8_overlong_null_reject(void) {
+  /**
+   * ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+   * 
+   * This is an *invalid* UTF-8 string, because it contains an overlong null
+   * character. Our UTF-8 validator wrongly accepts overlong null as a valid
+   * UTF-8 sequence. This test fails because we disallow null codepoints, not
+   * because the UTF-8 is invalid, and the error message reflects that.
+   * 
+   * If/when UTF-8 validation is changed to reject overlong null, then the
+   * expected error code and error message for this test should change.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 2, 'f', 'o', 'o', 0, 9, 0, 0, 0, 'a', 'b', 'c', 0xc0, 0x80,
+    '1', '2', '3', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8_ALLOW_NULL);
+  mlib_check(error.message, str_eq, "UTF-8 string contains a U+0000 (null) character");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8-key/invalid/accept
+static inline void _test_case_utf8_key_invalid_accept(void) {
+  /**
+   * The element key is not valid UTf-8, but we accept it if we don't do
+   * UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'a', 'b', 'c', 0xff, 'd', 'e', 'f', 0, 4, 0, 0, 0, 'b',
+    'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8-key/invalid/reject
+static inline void _test_case_utf8_key_invalid_reject(void) {
+  /**
+   * The element key is not valid UTF-8, and we reject it when we requested
+   * UTF-8 validation.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 2, 'a', 'b', 'c', 0xff, 'd', 'e', 'f', 0, 4, 0, 0, 0, 'b',
+    'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8-key/overlong-null/reject
+static inline void _test_case_utf8_key_overlong_null_reject(void) {
+  /**
+   * ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+   * 
+   * The element key is invalid UTF-8 because it contains an overlong null. We accept the
+   * overlong null as a valid encoding of U+0000, but we reject the key because
+   * we disallow null in UTF-8 strings.
+   * 
+   * If/when UTF-8 validation is changed to reject overlong null, then the
+   * expected error code and error message for this test should change.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 2, 'a', 'b', 'c', 0xc0, 0x80, 'd', 'e', 'f', 0, 4, 0, 0, 0,
+    'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8_ALLOW_NULL);
+  mlib_check(error.message, str_eq, "UTF-8 string contains a U+0000 (null) character");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: utf8-key/overlong-null/accept
+static inline void _test_case_utf8_key_overlong_null_accept(void) {
+  /**
+   * ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+   * 
+   * The element key is invalid UTF-8 because it contains an overlong null. We accept the
+   * overlong null as a valid encoding of U+0000, and we allow it in an element key because
+   * we pass ALLOW_NULL
+   * 
+   * If/when UTF-8 validation is changed to reject overlong null, then this
+   * test case should instead reject the key string as invalid UTF-8.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 2, 'a', 'b', 'c', 0xc0, 0x80, 'd', 'e', 'f', 0, 4, 0, 0, 0,
+    'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: array/empty
+static inline void _test_case_array_empty(void) {
+  /**
+   * Simple empty array element
+   */
+  const uint8_t bytes[] = {
+    0x11, 0, 0, 0, 4, 'a', 'r', 'r', 'a', 'y', 0, 5, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: array/simple
+static inline void _test_case_array_simple(void) {
+  /**
+   * Simple array element of integers
+   */
+  const uint8_t bytes[] = {
+    0x26, 0, 0, 0, 4, 'a', 'r', 'r', 'a', 'y', 0, 0x1a, 0, 0, 0, 0x10, '0', 0,
+    0x2a, 0, 0, 0, 0x10, '1', 0, 0xc1, 6, 0, 0, 0x10, '2', 0, 0xf8, 0xff, 0xff,
+    0xff, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: array/invalid-element
+static inline void _test_case_array_invalid_element(void) {
+  /**
+   * Simple array element of integers, but one element is truncated
+   */
+  const uint8_t bytes[] = {
+    0x23, 0, 0, 0, 4, 'a', 'r', 'r', 'a', 'y', 0, 0x17, 0, 0, 0, 0x10, '0', 0,
+    0x2a, 0, 0, 0, 0x10, '1', 0, 0, 0x10, '2', 0, 0xf8, 0xff, 0xff, 0xff, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 34);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: array/invalid-element-check-offset
+static inline void _test_case_array_invalid_element_check_offset(void) {
+  /**
+   * This is the same as the array/invalid-element test, but with a longer
+   * key string on the parent array. This is to check that the error offset
+   * is properly adjusted for the additional characters.
+   */
+  const uint8_t bytes[] = {
+    0x2b, 0, 0, 0, 4, 'a', 'r', 'r', 'a', 'y', '-', 's', 'h', 'i', 'f', 't',
+    'e', 'd', 0, 0x17, 0, 0, 0, 0x10, '0', 0, 0x2a, 0, 0, 0, 0x10, '1', 0, 0,
+    0x10, '2', 0, 0xf8, 0xff, 0xff, 0xff, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 42);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: symbol/simple
+static inline void _test_case_symbol_simple(void) {
+  /**
+   * A simple document: { symbol: Symbol("void 0;") }
+   */
+  const uint8_t bytes[] = {
+    0x19, 0, 0, 0, 0x0e, 's', 'y', 'm', 'b', 'o', 'l', 0, 8, 0, 0, 0, 'v', 'o',
+    'i', 'd', 0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: symbol/invalid-utf8/accept
+static inline void _test_case_symbol_invalid_utf8_accept(void) {
+  /**
+   * A simple symbol document, but the string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x1a, 0, 0, 0, 0x0e, 's', 'y', 'm', 'b', 'o', 'l', 0, 9, 0, 0, 0, 'v', 'o',
+    'i', 'd', 0xff, 0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: symbol/invalid-utf8/reject
+static inline void _test_case_symbol_invalid_utf8_reject(void) {
+  /**
+   * A simple symbol document, but the string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x1a, 0, 0, 0, 0x0e, 's', 'y', 'm', 'b', 'o', 'l', 0, 9, 0, 0, 0, 'v', 'o',
+    'i', 'd', 0xff, 0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: symbol/length-zero
+static inline void _test_case_symbol_length_zero(void) {
+  /**
+   * Symbol string length must always be at least 1 for the null terminator
+   */
+  const uint8_t bytes[] = {
+    0x0c, 0, 0, 0, 0x0e, 0, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 6);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: symbol/length-too-short
+static inline void _test_case_symbol_length_too_short(void) {
+  /**
+   * Symbol string is three chars and a null terminator, but the declared
+   * length is 3 (should be 4)
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 0x0e, 0, 3, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 12);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code/simple
+static inline void _test_case_code_simple(void) {
+  /**
+   * A simple document: { code: Code("void 0;") }
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 0x0d, 'c', 'o', 'd', 'e', 0, 8, 0, 0, 0, 'v', 'o', 'i', 'd',
+    0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code/invalid-utf8/accept
+static inline void _test_case_code_invalid_utf8_accept(void) {
+  /**
+   * A simple code document, but the string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x18, 0, 0, 0, 0x0d, 'c', 'o', 'd', 'e', 0, 9, 0, 0, 0, 'v', 'o', 'i', 'd',
+    0xff, 0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code/invalid-utf8/reject
+static inline void _test_case_code_invalid_utf8_reject(void) {
+  /**
+   * A simple code document, but the string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x18, 0, 0, 0, 0x0d, 'c', 'o', 'd', 'e', 0, 9, 0, 0, 0, 'v', 'o', 'i', 'd',
+    0xff, 0x20, '0', 0x3b, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code/length-zero
+static inline void _test_case_code_length_zero(void) {
+  /**
+   * Code string length must always be at least 1 for the null terminator
+   */
+  const uint8_t bytes[] = {
+    0x10, 0, 0, 0, 0x0d, 'c', 'o', 'd', 'e', 0, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 10);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code/length-too-short
+static inline void _test_case_code_length_too_short(void) {
+  /**
+   * Code string is three chars and a null terminator, but the declared length is 3 (should be 4)
+   */
+  const uint8_t bytes[] = {
+    0x13, 0, 0, 0, 0x0d, 'c', 'o', 'd', 'e', 0, 3, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 16);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/simple
+static inline void _test_case_code_with_scope_simple(void) {
+  /**
+   * A simple valid code-with-scope element
+   */
+  const uint8_t bytes[] = {
+    0x1f, 0, 0, 0, 0x0f, 'f', 'o', 'o', 0, 0x15, 0, 0, 0, 8, 0, 0, 0, 'v', 'o',
+    'i', 'd', 0x20, '0', 0x3b, 0, 5, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/invalid-code-length-zero
+static inline void _test_case_code_with_scope_invalid_code_length_zero(void) {
+  /**
+   * Data { "": CodeWithScope("", {}) }, but the code string length is zero, when
+   * it must be at least 1
+   */
+  const uint8_t bytes[] = {
+    0x15, 0, 0, 0, 0x0f, 0, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 6);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/invalid-code-length-too-large
+static inline void _test_case_code_with_scope_invalid_code_length_too_large(void) {
+  /**
+   * Data { "": CodeWithScope("", {}) }, but the code string length is way too large
+   */
+  const uint8_t bytes[] = {
+    0x15, 0, 0, 0, 0x0f, 0, 0x0a, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 5, 0, 0,
+    0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 6);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/invalid-scope
+static inline void _test_case_code_with_scope_invalid_scope(void) {
+  /**
+   * A code-with-scope element, but the scope document is corrupted
+   */
+  const uint8_t bytes[] = {
+    0x1e, 0, 0, 0, 0x0f, 'f', 'o', 'o', 0, 0x14, 0, 0, 0, 8, 0, 0, 0, 'v', 'o',
+    'i', 'd', 0x20, '0', 0x3b, 0, 5, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/empty-key-in-scope
+static inline void _test_case_code_with_scope_empty_key_in_scope(void) {
+  /**
+   * A code-with-scope element. The scope itself contains empty keys within
+   * objects, and we ask to reject empty keys. But the scope document should
+   * be treated as an opaque closure, so our outer validation rules do not
+   * apply.
+   */
+  const uint8_t bytes[] = {
+    '7', 0, 0, 0, 0x0f, 'c', 'o', 'd', 'e', 0, 0x2c, 0, 0, 0, 8, 0, 0, 0, 'v',
+    'o', 'i', 'd', 0x20, '0', 0x3b, 0, 0x1c, 0, 0, 0, 3, 'o', 'b', 'j', 0, 0x12,
+    0, 0, 0, 2, 0, 7, 0, 0, 0, 's', 't', 'r', 'i', 'n', 'g', 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_EMPTY_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/corrupt-scope
+static inline void _test_case_code_with_scope_corrupt_scope(void) {
+  /**
+   * A code-with-scope element, but the scope contains corruption
+   */
+  const uint8_t bytes[] = {
+    0x2a, 0, 0, 0, 0x0f, 'c', 'o', 'd', 'e', 0, 0x1f, 0, 0, 0, 8, 0, 0, 0, 'v',
+    'o', 'i', 'd', 0x20, '0', 0x3b, 0, 0x0f, 0, 0, 0, 2, 'f', 'o', 'o', 0, 0, 0,
+    0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "Error in scope document for element \"code\": corrupt BSON");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: code-with-scope/corrupt-scope-2
+static inline void _test_case_code_with_scope_corrupt_scope_2(void) {
+  /**
+   * A code-with-scope element, but the scope contains corruption
+   */
+  const uint8_t bytes[] = {
+    0x2a, 0, 0, 0, 0x0f, 'c', 'o', 'd', 'e', 0, 0x1f, 0, 0, 0, 8, 0, 0, 0, 'v',
+    'o', 'i', 'd', 0x20, '0', 0x3b, 0, 0x0f, 0, 0, 0, 2, 'f', 'o', 'o', 0, 0xff,
+    0xff, 0xff, 0xff, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "Error in scope document for element \"code\": corrupt BSON");
+  mlib_check(offset, eq, 13);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/simple
+static inline void _test_case_regex_simple(void) {
+  /**
+   * Simple document: { regex: Regex("1234", "gi") }
+   */
+  const uint8_t bytes[] = {
+    0x14, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, '1', '2', '3', '4', 0, 'g',
+    'i', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/invalid-opts
+static inline void _test_case_regex_invalid_opts(void) {
+  /**
+   * A regular expression element with missing null terminator. The main
+   * option string "foo" has a null terminator, but the option component "bar"
+   * does not have a null terminator. A naive parse will see the doc's null
+   * terminator as the null terminator for the options string, but that's
+   * invalid!
+   */
+  const uint8_t bytes[] = {
+    0x13, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, 'f', 'o', 'o', 0, 'b', 'a',
+    'r', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/double-null
+static inline void _test_case_regex_double_null(void) {
+  /**
+   * A regular expression element with an extra null terminator. Since regex
+   * is delimited by its null terminator, the iterator will stop early before
+   * the actual EOD.
+   */
+  const uint8_t bytes[] = {
+    0x15, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, 'f', 'o', 'o', 0, 'b', 'a',
+    'r', 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 21);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/invalid-utf8/accept
+static inline void _test_case_regex_invalid_utf8_accept(void) {
+  /**
+   * A regular expression that contains invalid UTF-8.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, 'f', 'o', 'o', 0xff, 'b',
+    'a', 'r', 0, 'g', 'i', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/invalid-utf8/reject
+static inline void _test_case_regex_invalid_utf8_reject(void) {
+  /**
+   * A regular expression that contains invalid UTF-8.
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, 'f', 'o', 'o', 0xff, 'b',
+    'a', 'r', 0, 'g', 'i', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: regex/invalid-utf8/accept-if-absent
+static inline void _test_case_regex_invalid_utf8_accept_if_absent(void) {
+  /**
+   * A regular valid UTf-8 regex. We check for invalid UTf-8, and accept becaues
+   * the regex is fine.
+   */
+  const uint8_t bytes[] = {
+    0x13, 0, 0, 0, 0x0b, 'r', 'e', 'g', 'e', 'x', 0, 'f', 'o', 'o', 0, 'g', 'i',
+    0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/string-length-zero
+static inline void _test_case_dbpointer_string_length_zero(void) {
+  /**
+   * Document { "foo": DBPointer("", <oid>) }, but the length header on the inner
+   * string is zero, when it must be at least 1.
+   */
+  const uint8_t bytes[] = {
+    0x1b, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 'R', 'Y', 0xb5, 'j',
+    0xfa, 0x5b, 0xd8, 'A', 0xd6, 'X', 0x5d, 0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/string-length-too-big
+static inline void _test_case_dbpointer_string_length_too_big(void) {
+  /**
+   * Document { "foo": DBPointer("foobar", <oid>) }, but the length header on the inner
+   * string is far too large
+   */
+  const uint8_t bytes[] = {
+    0x21, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 0xff, 0xff, 0xff, 0xff, 'f', 'o',
+    'o', 'b', 'a', 'r', 0, 'R', 'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8, 'A', 0xd6,
+    'X', 0x5d, 0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/truncated
+static inline void _test_case_dbpointer_truncated(void) {
+  /**
+   * Document { "foo": DBPointer("foobar", <oid>) }, but the length header on
+   * the string is one byte too large, causing it to use the first byte of the
+   * OID as the null terminator. This should fail when iterating.
+   */
+  const uint8_t bytes[] = {
+    '2', 0, 0, 0, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 0x0c, 'f', 'o', 'o', 0, 7, 0,
+    0, 0, 'f', 'o', 'o', 'b', 'a', 'r', 0, 'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8,
+    'A', 0xd6, 'X', 0x5d, 0x99, 2, 'a', 0, 2, 0, 0, 0, 'b', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 43);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/missing-null
+static inline void _test_case_dbpointer_missing_null(void) {
+  /**
+   * Document { "foo": DBPointer("abcd", <oid>) }, the length header on
+   * the string is 4, but the fourth byte is not a null terminator.
+   */
+  const uint8_t bytes[] = {
+    0x1e, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 4, 0, 0, 0, 'a', 'b', 'c', 'd', 'R',
+    'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8, 'A', 0xd6, 'X', 0x5d, 0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 16);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/invalid-utf8/accept
+static inline void _test_case_dbpointer_invalid_utf8_accept(void) {
+  /**
+   * DBPointer document, but the collection string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x22, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 8, 0, 0, 0, 'a', 'b', 'c', 0xff, 'd',
+    'e', 'f', 0, 'R', 'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8, 'A', 0xd6, 'X', 0x5d,
+    0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/invalid-utf8/reject
+static inline void _test_case_dbpointer_invalid_utf8_reject(void) {
+  /**
+   * DBPointer document, but the collection string contains invalid UTF-8
+   */
+  const uint8_t bytes[] = {
+    0x22, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 8, 0, 0, 0, 'a', 'b', 'c', 0xff, 'd',
+    'e', 'f', 0, 'R', 'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8, 'A', 0xd6, 'X', 0x5d,
+    0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_UTF8);
+  mlib_check(error.message, str_eq, "Text element is not valid UTF-8");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbpointer/invalid-utf8/accept-if-absent
+static inline void _test_case_dbpointer_invalid_utf8_accept_if_absent(void) {
+  /**
+   * DBPointer document, and we validate UTF-8. Accepts because there is no
+   * invalid UTF-8 here.
+   */
+  const uint8_t bytes[] = {
+    0x21, 0, 0, 0, 0x0c, 'f', 'o', 'o', 0, 7, 0, 0, 0, 'a', 'b', 'c', 'd', 'e',
+    'f', 0, 'R', 'Y', 0xb5, 'j', 0xfa, 0x5b, 0xd8, 'A', 0xd6, 'X', 0x5d, 0x99, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_UTF8, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/simple
+static inline void _test_case_subdoc_simple(void) {
+  /**
+   * A simple document: { doc: { foo: "bar" } }
+   */
+  const uint8_t bytes[] = {
+    0x1c, 0, 0, 0, 3, 'd', 'o', 'c', 0, 0x12, 0, 0, 0, 2, 'f', 'o', 'o', 0, 4,
+    0, 0, 0, 'b', 'a', 'r', 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/invalid-shared-null
+static inline void _test_case_subdoc_invalid_shared_null(void) {
+  /**
+   * A truncated subdocument element, with its null terminator accidentally
+   * overlapping the parent document's null.
+   */
+  const uint8_t bytes[] = {
+    0x0e, 0, 0, 0, 3, 'd', 'o', 'c', 0, 5, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/overlapping-utf8-null
+static inline void _test_case_subdoc_overlapping_utf8_null(void) {
+  /**
+   * Encodes the document:
+   * 
+   *     { "foo": { "bar": "baz" } }
+   * 
+   * but the foo.bar UTF-8 string is truncated improperly and reuses the null
+   * terminator for "foo"
+   */
+  const uint8_t bytes[] = {
+    0x1c, 0, 0, 0, 3, 'd', 'o', 'c', 0, 0x12, 0, 0, 0, 2, 'b', 'a', 'r', 0, 5,
+    0, 0, 0, 'b', 'a', 'z', 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/invalid-element
+static inline void _test_case_subdoc_invalid_element(void) {
+  /**
+   * A subdocument that contains an invalid element
+   */
+  const uint8_t bytes[] = {
+    0x18, 0, 0, 0, 3, 'd', 'o', 'c', 0, 0x0e, 0, 0, 0, 1, 'd', 'b', 'l', 0, 'a',
+    'b', 'c', 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/header-too-large
+static inline void _test_case_subdoc_header_too_large(void) {
+  /**
+   * Data {"foo": {}}, but the subdoc header is too large.
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 3, 'f', 'o', 'o', 0, 0xf7, 0xff, 0xff, 0xff, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/header-too-small
+static inline void _test_case_subdoc_header_too_small(void) {
+  /**
+   * Nested document with a header value of 4, which is always too small.
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 3, 't', 'e', 's', 't', 0, 4, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: subdoc/impossible-size
+static inline void _test_case_subdoc_impossible_size(void) {
+  /**
+   * Data {"foo": {}}, but the subdoc header is UINT32_MAX/INT32_MIN, which
+   * becomes is an invalid document header.
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 3, 'f', 'o', 'o', 0, 0xff, 0xff, 0xff, 0xff, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: null/simple
+static inline void _test_case_null_simple(void) {
+  /**
+   * A simple document: { "null": null }
+   */
+  const uint8_t bytes[] = {
+    0x0b, 0, 0, 0, 0x0a, 'n', 'u', 'l', 'l', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: undefined/simple
+static inline void _test_case_undefined_simple(void) {
+  /**
+   * A simple document: { "undefined": undefined }
+   */
+  const uint8_t bytes[] = {
+    0x10, 0, 0, 0, 6, 'u', 'n', 'd', 'e', 'f', 'i', 'n', 'e', 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/simple
+static inline void _test_case_binary_simple(void) {
+  /**
+   * Simple binary data { "binary": Binary(0x80, b'12345') }
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 5, 0, 0, 0, 0x80, '1',
+    '2', '3', '4', '5', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/bad-length-zero-subtype-2
+static inline void _test_case_binary_bad_length_zero_subtype_2(void) {
+  /**
+   * Binary data that has an invalid length header. It is subtype 2,
+   * which means it contains an additional length header.
+   */
+  const uint8_t bytes[] = {
+    0x1a, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 0, 0, 0, 0, 2, 4, 0, 0,
+    0, '1', '2', '3', '4', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 12);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/bad-inner-length-on-subtype-2
+static inline void _test_case_binary_bad_inner_length_on_subtype_2(void) {
+  /**
+   * Binary data that has an valid outer length header, but the inner length
+   * header for subtype 2 has an incorrect value.
+   */
+  const uint8_t bytes[] = {
+    0x1a, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 8, 0, 0, 0, 2, 2, 0, 0,
+    0, '1', '2', '3', '4', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 17);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/bad-length-too-small
+static inline void _test_case_binary_bad_length_too_small(void) {
+  /**
+   * Data { "binary": Binary(0x80, b'1234') }, but the length header on
+   * the Binary object is too small.
+   * 
+   * This won't cause the binary to decode wrong, but it will cause the iterator
+   * to jump into the middle of the binary data which will not decode as a
+   * proper BSON element.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 2, 0, 0, 0, 0x80, '1',
+    '2', '3', '4', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 22);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/bad-length-too-big
+static inline void _test_case_binary_bad_length_too_big(void) {
+  /**
+   * Data { "binary": Binary(0x80, b'1234') }, but the length header on
+   * the Binary object is too large.
+   */
+  const uint8_t bytes[] = {
+    0x16, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 0xf3, 0xff, 0xff, 0xff,
+    0x80, '1', '2', '3', '4', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 12);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/old-invalid/1
+static inline void _test_case_binary_old_invalid_1(void) {
+  /**
+   * This is an old-style binary type 0x2. It has an inner length header of 5,
+   * but it should be 4.
+   */
+  const uint8_t bytes[] = {
+    0x1a, 0, 0, 0, 5, 'b', 'i', 'n', 'a', 'r', 'y', 0, 8, 0, 0, 0, 2, 5, 0, 0,
+    0, 'a', 'b', 'c', 'd', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 17);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: binary/old-invalid/2
+static inline void _test_case_binary_old_invalid_2(void) {
+  /**
+   * This is an old-style binary type 0x2. The data segment is too small to
+   * be valid.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 5, 'b', 'i', 'n', 0, 3, 0, 0, 0, 2, 'a', 'b', 'c', 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: minkey/simple
+static inline void _test_case_minkey_simple(void) {
+  /**
+   * A simple document with a MinKey element
+   */
+  const uint8_t bytes[] = {
+    0x0a, 0, 0, 0, 0xff, 'm', 'i', 'n', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: maxkey/simple
+static inline void _test_case_maxkey_simple(void) {
+  /**
+   * A simple document with a MaxKey element
+   */
+  const uint8_t bytes[] = {
+    0x0a, 0, 0, 0, 0x7f, 'm', 'a', 'x', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: int32/simple
+static inline void _test_case_int32_simple(void) {
+  /**
+   * A simple document with a valid single int32 element
+   */
+  const uint8_t bytes[] = {
+    0x10, 0, 0, 0, 0x10, 'i', 'n', 't', '3', '2', 0, 0x2a, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: int32/truncated
+static inline void _test_case_int32_truncated(void) {
+  /**
+   * Truncated 32-bit integer
+   */
+  const uint8_t bytes[] = {
+    0x19, 0, 0, 0, 0x10, 'i', 'n', 't', '3', '2', '-', 't', 'r', 'u', 'n', 'c',
+    'a', 't', 'e', 'd', 0, 0x2a, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 21);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: timestamp/simple
+static inline void _test_case_timestamp_simple(void) {
+  /**
+   * A simple timestamp element
+   */
+  const uint8_t bytes[] = {
+    0x18, 0, 0, 0, 0x11, 't', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', 0, 0xc1,
+    6, 0, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: timestamp/truncated
+static inline void _test_case_timestamp_truncated(void) {
+  /**
+   * A truncated timestamp element
+   */
+  const uint8_t bytes[] = {
+    0x17, 0, 0, 0, 0x11, 't', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', 0, 0xc1,
+    6, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 15);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: int64/simple
+static inline void _test_case_int64_simple(void) {
+  /**
+   * A simple document with a valid single int64 element
+   */
+  const uint8_t bytes[] = {
+    0x14, 0, 0, 0, 0x12, 'i', 'n', 't', '6', '4', 0, 0xc1, 6, 0, 0, 0, 0, 0, 0,
+    0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: int64/truncated
+static inline void _test_case_int64_truncated(void) {
+  /**
+   * Truncated 64-bit integer
+   */
+  const uint8_t bytes[] = {
+    0x1d, 0, 0, 0, 0x12, 'i', 'n', 't', '6', '4', '-', 't', 'r', 'u', 'n', 'c',
+    'a', 't', 'e', 'd', 0, 0xc1, 6, 0, 0, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 21);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: double/simple
+static inline void _test_case_double_simple(void) {
+  /**
+   * Simple float64 element
+   */
+  const uint8_t bytes[] = {
+    0x15, 0, 0, 0, 1, 'd', 'o', 'u', 'b', 'l', 'e', 0, 0x1f, 0x85, 0xeb, 'Q',
+    0xb8, 0x1e, 9, 0x40, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: double/truncated
+static inline void _test_case_double_truncated(void) {
+  /**
+   * Truncated 64-bit float
+   */
+  const uint8_t bytes[] = {
+    0x1e, 0, 0, 0, 1, 'd', 'o', 'u', 'b', 'l', 'e', '-', 't', 'r', 'u', 'n',
+    'c', 'a', 't', 'e', 'd', 0, 0x0a, 0xd7, 0xa3, 'p', 0x3d, 0x0a, 9, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 22);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: boolean/simple-false
+static inline void _test_case_boolean_simple_false(void) {
+  /**
+   * A simple boolean 'false'
+   */
+  const uint8_t bytes[] = {
+    0x0c, 0, 0, 0, 8, 'b', 'o', 'o', 'l', 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: boolean/simple-true
+static inline void _test_case_boolean_simple_true(void) {
+  /**
+   * A simple boolean 'true'
+   */
+  const uint8_t bytes[] = {
+    0x0c, 0, 0, 0, 8, 'b', 'o', 'o', 'l', 0, 1, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: boolean/invalid
+static inline void _test_case_boolean_invalid(void) {
+  /**
+   * An invalid boolean octet. Must be '0' or '1', but is 0xc3.
+   */
+  const uint8_t bytes[] = {
+    0x0c, 0, 0, 0, 8, 'b', 'o', 'o', 'l', 0, 0xc3, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 10);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: datetime/simple
+static inline void _test_case_datetime_simple(void) {
+  /**
+   * Simple datetime element
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 9, 'u', 't', 'c', 0, 0x0b, 0x98, 0x8c, 0x2b, '3', 1, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: datetime/truncated
+static inline void _test_case_datetime_truncated(void) {
+  /**
+   * Truncated datetime element
+   */
+  const uint8_t bytes[] = {
+    0x11, 0, 0, 0, 9, 'u', 't', 'c', 0, 0x0b, 0x98, 0x8c, 0x2b, '3', 1, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, 0, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_CORRUPT);
+  mlib_check(error.message, str_eq, "corrupt BSON");
+  mlib_check(offset, eq, 9);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/missing-id
+static inline void _test_case_dbref_missing_id(void) {
+  /**
+   * This dbref document is missing an $id element
+   */
+  const uint8_t bytes[] = {
+    0x13, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Expected an $id element following $ref");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/non-id
+static inline void _test_case_dbref_non_id(void) {
+  /**
+   * The 'bar' element should be an '$id' element.
+   */
+  const uint8_t bytes[] = {
+    0x20, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    'b', 'a', 'r', 0, 4, 0, 0, 0, 'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Expected an $id element following $ref");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/not-first-elements
+static inline void _test_case_dbref_not_first_elements(void) {
+  /**
+   * This would be a valid DBRef, but the "$ref" key must come first.
+   */
+  const uint8_t bytes[] = {
+    0x29, 0, 0, 0, 2, 'f', 'o', 'o', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, '$',
+    'r', 'e', 'f', 0, 2, 0, 0, 0, 'a', 0, 2, '$', 'i', 'd', 0, 2, 0, 0, 0, 'b',
+    0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Disallowed '$' in element key: \"$ref\"");
+  mlib_check(offset, eq, 17);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/ref-without-id-with-db
+static inline void _test_case_dbref_ref_without_id_with_db(void) {
+  /**
+   * There should be an $id element, but we skip straight to $db
+   */
+  const uint8_t bytes[] = {
+    0x20, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'd', 'b', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Expected an $id element following $ref");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/non-string-ref
+static inline void _test_case_dbref_non_string_ref(void) {
+  /**
+   * The $ref element must be a string, but is an integer.
+   */
+  const uint8_t bytes[] = {
+    0x0f, 0, 0, 0, 0x10, '$', 'r', 'e', 'f', 0, 0x2a, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "$ref element must be a UTF-8 element");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/non-string-db
+static inline void _test_case_dbref_non_string_db(void) {
+  /**
+   * The $db element should be a string, but is an integer.
+   */
+  const uint8_t bytes[] = {
+    0x29, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0x10, '$', 'd', 'b', 0,
+    0x2a, 0, 0, 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "$db element in DBRef must be a UTF-8 element");
+  mlib_check(offset, eq, 31);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/invalid-extras-between
+static inline void _test_case_dbref_invalid_extras_between(void) {
+  /**
+   * Almost a valid DBRef, but there is an extra field before $db. We reject $db
+   * as an invalid key.
+   */
+  const uint8_t bytes[] = {
+    0x3e, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, 'e', 'x', 't', 'r', 'a',
+    0, 6, 0, 0, 0, 'f', 'i', 'e', 'l', 'd', 0, 2, '$', 'd', 'b', 0, 4, 0, 0, 0,
+    'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Disallowed '$' in element key: \"$db\"");
+  mlib_check(offset, eq, 48);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/invalid-double-ref
+static inline void _test_case_dbref_invalid_double_ref(void) {
+  /**
+   * Invalid DBRef contains a second $ref element.
+   */
+  const uint8_t bytes[] = {
+    '.', 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, '$', 'i', 'd', 0, 4,
+    0, 0, 0, 'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Expected an $id element following $ref");
+  mlib_check(offset, eq, 18);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/invalid-missing-ref
+static inline void _test_case_dbref_invalid_missing_ref(void) {
+  /**
+   * DBRef document requires a $ref key to be first.
+   */
+  const uint8_t bytes[] = {
+    0x12, 0, 0, 0, 2, '$', 'i', 'd', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  mlib_check(!is_valid);
+  mlib_check(error.code, eq, BSON_VALIDATE_DOLLAR_KEYS);
+  mlib_check(error.message, str_eq, "Disallowed '$' in element key: \"$id\"");
+  mlib_check(offset, eq, 4);
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/valid/simple
+static inline void _test_case_dbref_valid_simple(void) {
+  /**
+   * This is a simple valid DBRef element.
+   */
+  const uint8_t bytes[] = {
+    0x20, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/valid/simple-with-db
+static inline void _test_case_dbref_valid_simple_with_db(void) {
+  /**
+   * A simple DBRef of the form:
+   * 
+   *     { $ref: "foo", $id: "bar", $db: "baz" }
+   */
+  const uint8_t bytes[] = {
+    '-', 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, '$', 'd', 'b', 0, 4, 0,
+    0, 0, 'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/valid/nested-id-doc
+static inline void _test_case_dbref_valid_nested_id_doc(void) {
+  /**
+   * This is a valid DBRef of the form:
+   * 
+   *     { $ref: foo, $id: { $ref: "foo2", $id: "bar2", $db: "baz2" }, $db: "baz" }
+   */
+  const uint8_t bytes[] = {
+    'U', 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 3,
+    '$', 'i', 'd', 0, '0', 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 5, 0, 0, 0, 'f',
+    'o', 'o', '2', 0, 2, '$', 'i', 'd', 0, 5, 0, 0, 0, 'b', 'a', 'r', '2', 0, 2,
+    '$', 'd', 'b', 0, 5, 0, 0, 0, 'b', 'a', 'z', '2', 0, 0, 2, '$', 'd', 'b', 0,
+    4, 0, 0, 0, 'b', 'a', 'z', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/valid/trailing-content
+static inline void _test_case_dbref_valid_trailing_content(void) {
+  /**
+   * A valid DBRef of the form:
+   * 
+   *     {
+   *         $ref: "foo",
+   *         $id: "bar",
+   *         $db: "baz",
+   *         extra: "field",
+   *     }
+   */
+  const uint8_t bytes[] = {
+    0x3e, 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, '$', 'd', 'b', 0, 4, 0,
+    0, 0, 'b', 'a', 'z', 0, 2, 'e', 'x', 't', 'r', 'a', 0, 6, 0, 0, 0, 'f', 'i',
+    'e', 'l', 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+// Case: dbref/valid/trailing-content-no-db
+static inline void _test_case_dbref_valid_trailing_content_no_db(void) {
+  /**
+   * A valid DBRef of the form:
+   * 
+   *     {
+   *         $ref: "foo",
+   *         $id: "bar",
+   *         extra: "field",
+   *     }
+   */
+  const uint8_t bytes[] = {
+    '1', 0, 0, 0, 2, '$', 'r', 'e', 'f', 0, 4, 0, 0, 0, 'f', 'o', 'o', 0, 2,
+    '$', 'i', 'd', 0, 4, 0, 0, 0, 'b', 'a', 'r', 0, 2, 'e', 'x', 't', 'r', 'a',
+    0, 6, 0, 0, 0, 'f', 'i', 'e', 'l', 'd', 0, 0
+  };
+  bson_t doc;
+  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));
+  bson_error_t error = {0};
+  size_t offset = 999999;
+  const bool is_valid = bson_validate_with_error_and_offset(&doc, BSON_VALIDATE_DOLLAR_KEYS, &offset, &error);
+  ASSERT_OR_PRINT(is_valid, error);
+  mlib_check(error.code, eq, 0);
+  mlib_check(error.message, str_eq, "");
+}
+
+// ! This code is GENERATED! Do not edit it directly!
+void test_install_generated_bson_validation(TestSuite* suite) {
+  TestSuite_Add(suite, "/bson/validate/" "empty", _test_case_empty);
+  TestSuite_Add(suite, "/bson/validate/" "bad-element", _test_case_bad_element);
+  TestSuite_Add(suite, "/bson/validate/" "invalid-type", _test_case_invalid_type);
+  TestSuite_Add(suite, "/bson/validate/" "key/invalid/accept", _test_case_key_invalid_accept);
+  TestSuite_Add(suite, "/bson/validate/" "key/invalid/reject", _test_case_key_invalid_reject);
+  TestSuite_Add(suite, "/bson/validate/" "key/empty/accept", _test_case_key_empty_accept);
+  TestSuite_Add(suite, "/bson/validate/" "key/empty/reject", _test_case_key_empty_reject);
+  TestSuite_Add(suite, "/bson/validate/" "key/empty/accept-if-absent", _test_case_key_empty_accept_if_absent);
+  TestSuite_Add(suite, "/bson/validate/" "key/dot/accept", _test_case_key_dot_accept);
+  TestSuite_Add(suite, "/bson/validate/" "key/dot/reject", _test_case_key_dot_reject);
+  TestSuite_Add(suite, "/bson/validate/" "key/dot/accept-if-absent", _test_case_key_dot_accept_if_absent);
+  TestSuite_Add(suite, "/bson/validate/" "key/dollar/accept", _test_case_key_dollar_accept);
+  TestSuite_Add(suite, "/bson/validate/" "key/dollar/reject", _test_case_key_dollar_reject);
+  TestSuite_Add(suite, "/bson/validate/" "key/dollar/accept-in-middle", _test_case_key_dollar_accept_in_middle);
+  TestSuite_Add(suite, "/bson/validate/" "key/dollar/accept-if-absent", _test_case_key_dollar_accept_if_absent);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/simple", _test_case_utf8_simple);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/missing-null", _test_case_utf8_missing_null);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/length-zero", _test_case_utf8_length_zero);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/length-too-short", _test_case_utf8_length_too_short);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/header-too-large", _test_case_utf8_header_too_large);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/valid", _test_case_utf8_valid);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/invalid/accept", _test_case_utf8_invalid_accept);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/invalid/reject", _test_case_utf8_invalid_reject);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/valid-with-null/accept-1", _test_case_utf8_valid_with_null_accept_1);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/valid-with-null/accept-2", _test_case_utf8_valid_with_null_accept_2);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/valid-with-null/reject", _test_case_utf8_valid_with_null_reject);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/overlong-null/accept-1", _test_case_utf8_overlong_null_accept_1);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/overlong-null/accept-2", _test_case_utf8_overlong_null_accept_2);
+  TestSuite_Add(suite, "/bson/validate/" "utf8/overlong-null/reject", _test_case_utf8_overlong_null_reject);
+  TestSuite_Add(suite, "/bson/validate/" "utf8-key/invalid/accept", _test_case_utf8_key_invalid_accept);
+  TestSuite_Add(suite, "/bson/validate/" "utf8-key/invalid/reject", _test_case_utf8_key_invalid_reject);
+  TestSuite_Add(suite, "/bson/validate/" "utf8-key/overlong-null/reject", _test_case_utf8_key_overlong_null_reject);
+  TestSuite_Add(suite, "/bson/validate/" "utf8-key/overlong-null/accept", _test_case_utf8_key_overlong_null_accept);
+  TestSuite_Add(suite, "/bson/validate/" "array/empty", _test_case_array_empty);
+  TestSuite_Add(suite, "/bson/validate/" "array/simple", _test_case_array_simple);
+  TestSuite_Add(suite, "/bson/validate/" "array/invalid-element", _test_case_array_invalid_element);
+  TestSuite_Add(suite, "/bson/validate/" "array/invalid-element-check-offset", _test_case_array_invalid_element_check_offset);
+  TestSuite_Add(suite, "/bson/validate/" "symbol/simple", _test_case_symbol_simple);
+  TestSuite_Add(suite, "/bson/validate/" "symbol/invalid-utf8/accept", _test_case_symbol_invalid_utf8_accept);
+  TestSuite_Add(suite, "/bson/validate/" "symbol/invalid-utf8/reject", _test_case_symbol_invalid_utf8_reject);
+  TestSuite_Add(suite, "/bson/validate/" "symbol/length-zero", _test_case_symbol_length_zero);
+  TestSuite_Add(suite, "/bson/validate/" "symbol/length-too-short", _test_case_symbol_length_too_short);
+  TestSuite_Add(suite, "/bson/validate/" "code/simple", _test_case_code_simple);
+  TestSuite_Add(suite, "/bson/validate/" "code/invalid-utf8/accept", _test_case_code_invalid_utf8_accept);
+  TestSuite_Add(suite, "/bson/validate/" "code/invalid-utf8/reject", _test_case_code_invalid_utf8_reject);
+  TestSuite_Add(suite, "/bson/validate/" "code/length-zero", _test_case_code_length_zero);
+  TestSuite_Add(suite, "/bson/validate/" "code/length-too-short", _test_case_code_length_too_short);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/simple", _test_case_code_with_scope_simple);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/invalid-code-length-zero", _test_case_code_with_scope_invalid_code_length_zero);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/invalid-code-length-too-large", _test_case_code_with_scope_invalid_code_length_too_large);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/invalid-scope", _test_case_code_with_scope_invalid_scope);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/empty-key-in-scope", _test_case_code_with_scope_empty_key_in_scope);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/corrupt-scope", _test_case_code_with_scope_corrupt_scope);
+  TestSuite_Add(suite, "/bson/validate/" "code-with-scope/corrupt-scope-2", _test_case_code_with_scope_corrupt_scope_2);
+  TestSuite_Add(suite, "/bson/validate/" "regex/simple", _test_case_regex_simple);
+  TestSuite_Add(suite, "/bson/validate/" "regex/invalid-opts", _test_case_regex_invalid_opts);
+  TestSuite_Add(suite, "/bson/validate/" "regex/double-null", _test_case_regex_double_null);
+  TestSuite_Add(suite, "/bson/validate/" "regex/invalid-utf8/accept", _test_case_regex_invalid_utf8_accept);
+  TestSuite_Add(suite, "/bson/validate/" "regex/invalid-utf8/reject", _test_case_regex_invalid_utf8_reject);
+  TestSuite_Add(suite, "/bson/validate/" "regex/invalid-utf8/accept-if-absent", _test_case_regex_invalid_utf8_accept_if_absent);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/string-length-zero", _test_case_dbpointer_string_length_zero);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/string-length-too-big", _test_case_dbpointer_string_length_too_big);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/truncated", _test_case_dbpointer_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/missing-null", _test_case_dbpointer_missing_null);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/invalid-utf8/accept", _test_case_dbpointer_invalid_utf8_accept);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/invalid-utf8/reject", _test_case_dbpointer_invalid_utf8_reject);
+  TestSuite_Add(suite, "/bson/validate/" "dbpointer/invalid-utf8/accept-if-absent", _test_case_dbpointer_invalid_utf8_accept_if_absent);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/simple", _test_case_subdoc_simple);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/invalid-shared-null", _test_case_subdoc_invalid_shared_null);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/overlapping-utf8-null", _test_case_subdoc_overlapping_utf8_null);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/invalid-element", _test_case_subdoc_invalid_element);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/header-too-large", _test_case_subdoc_header_too_large);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/header-too-small", _test_case_subdoc_header_too_small);
+  TestSuite_Add(suite, "/bson/validate/" "subdoc/impossible-size", _test_case_subdoc_impossible_size);
+  TestSuite_Add(suite, "/bson/validate/" "null/simple", _test_case_null_simple);
+  TestSuite_Add(suite, "/bson/validate/" "undefined/simple", _test_case_undefined_simple);
+  TestSuite_Add(suite, "/bson/validate/" "binary/simple", _test_case_binary_simple);
+  TestSuite_Add(suite, "/bson/validate/" "binary/bad-length-zero-subtype-2", _test_case_binary_bad_length_zero_subtype_2);
+  TestSuite_Add(suite, "/bson/validate/" "binary/bad-inner-length-on-subtype-2", _test_case_binary_bad_inner_length_on_subtype_2);
+  TestSuite_Add(suite, "/bson/validate/" "binary/bad-length-too-small", _test_case_binary_bad_length_too_small);
+  TestSuite_Add(suite, "/bson/validate/" "binary/bad-length-too-big", _test_case_binary_bad_length_too_big);
+  TestSuite_Add(suite, "/bson/validate/" "binary/old-invalid/1", _test_case_binary_old_invalid_1);
+  TestSuite_Add(suite, "/bson/validate/" "binary/old-invalid/2", _test_case_binary_old_invalid_2);
+  TestSuite_Add(suite, "/bson/validate/" "minkey/simple", _test_case_minkey_simple);
+  TestSuite_Add(suite, "/bson/validate/" "maxkey/simple", _test_case_maxkey_simple);
+  TestSuite_Add(suite, "/bson/validate/" "int32/simple", _test_case_int32_simple);
+  TestSuite_Add(suite, "/bson/validate/" "int32/truncated", _test_case_int32_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "timestamp/simple", _test_case_timestamp_simple);
+  TestSuite_Add(suite, "/bson/validate/" "timestamp/truncated", _test_case_timestamp_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "int64/simple", _test_case_int64_simple);
+  TestSuite_Add(suite, "/bson/validate/" "int64/truncated", _test_case_int64_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "double/simple", _test_case_double_simple);
+  TestSuite_Add(suite, "/bson/validate/" "double/truncated", _test_case_double_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "boolean/simple-false", _test_case_boolean_simple_false);
+  TestSuite_Add(suite, "/bson/validate/" "boolean/simple-true", _test_case_boolean_simple_true);
+  TestSuite_Add(suite, "/bson/validate/" "boolean/invalid", _test_case_boolean_invalid);
+  TestSuite_Add(suite, "/bson/validate/" "datetime/simple", _test_case_datetime_simple);
+  TestSuite_Add(suite, "/bson/validate/" "datetime/truncated", _test_case_datetime_truncated);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/missing-id", _test_case_dbref_missing_id);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/non-id", _test_case_dbref_non_id);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/not-first-elements", _test_case_dbref_not_first_elements);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/ref-without-id-with-db", _test_case_dbref_ref_without_id_with_db);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/non-string-ref", _test_case_dbref_non_string_ref);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/non-string-db", _test_case_dbref_non_string_db);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/invalid-extras-between", _test_case_dbref_invalid_extras_between);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/invalid-double-ref", _test_case_dbref_invalid_double_ref);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/invalid-missing-ref", _test_case_dbref_invalid_missing_ref);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/valid/simple", _test_case_dbref_valid_simple);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/valid/simple-with-db", _test_case_dbref_valid_simple_with_db);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/valid/nested-id-doc", _test_case_dbref_valid_nested_id_doc);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/valid/trailing-content", _test_case_dbref_valid_trailing_content);
+  TestSuite_Add(suite, "/bson/validate/" "dbref/valid/trailing-content-no-db", _test_case_dbref_valid_trailing_content_no_db);
+}
diff -pruN 1.30.4-1/src/libbson/tests/validate-tests.py 2.0.2-1/src/libbson/tests/validate-tests.py
--- 1.30.4-1/src/libbson/tests/validate-tests.py	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libbson/tests/validate-tests.py	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,1481 @@
+"""
+This script generates a C source file containing test cases for BSON validation
+and iteration.
+
+Run this script with Python 3.12+, and pipe the output into a file.
+
+This script takes no command-line arguments.
+"""
+
+# /// script
+# requires-python = ">=3.12"
+# dependencies = []
+# ///
+
+import argparse
+import enum
+import json
+import re
+import struct
+import textwrap
+from dataclasses import dataclass
+from typing import Iterable
+
+
+class Tag(enum.Enum):
+    """BSON type tag byte values"""
+
+    EOD = 0
+    Double = 1
+    UTF8 = 2
+    Document = 3
+    Array = 4
+    Binary = 5
+    Undefined = 6
+    OID = 7
+    Boolean = 8
+    Datetime = 9
+    Null = 10
+    Regex = 11
+    DBPointer = 12
+    Code = 13
+    Symbol = 14
+    CodeWithScope = 15
+    Int32 = 16
+    Timestamp = 17
+    Int64 = 18
+    Decimal128 = 19
+    MinKey = 0xFF
+    MaxKey = 0x7F
+
+
+type _ByteIter = bytes | Iterable[_ByteIter]
+"""A set of bytes, or an iterable that yields more sets of bytes"""
+
+
+def flatten_bytes(data: _ByteIter) -> bytes:
+    """Flatten a (recursive) iterator of bytes into a single bytes object"""
+    match data:
+        case bytes(data):
+            return data
+        case it:
+            return b"".join(map(flatten_bytes, it))
+
+
+def i32le(i: int) -> bytes:
+    """Encode an integer as a 32-bit little-endian integer"""
+    return struct.pack("<i", i)
+
+
+def i64le(i: int) -> bytes:
+    """Encode an integer as a 64-bit little-endian integer"""
+    return struct.pack("<q", i)
+
+
+def f64le(f: float) -> bytes:
+    """Encode a float as a 64-bit little-endian float"""
+    return struct.pack("<d", f)
+
+
+def doc(*data: _ByteIter) -> bytes:
+    """Add a BSON document header a null terminator to a set of bytes"""
+    flat = flatten_bytes(data)
+    # +5 for the null terminator and the header bytes
+    hdr = i32le(len(flat) + 5)
+    return hdr + flat + b"\0"
+
+
+def code_with_scope(code: str, doc: _ByteIter) -> bytes:
+    """Create a BSON code-with-scope object with appropriate header"""
+    s = string(code)
+    doc = flatten_bytes(doc)
+    # +4 to include the length prefix too
+    len_prefix = i32le(len(s) + len(doc) + 4)
+    return len_prefix + s + doc
+
+
+def elem(key: str | _ByteIter, tag: int | Tag, *bs: _ByteIter) -> bytes:
+    """Add a BSON element header to a set of bytes"""
+    if isinstance(tag, Tag):
+        tag = tag.value
+    return bytes([tag]) + cstring(key) + flatten_bytes(bs)
+
+
+def binary(subtype: int, *bs: _ByteIter) -> bytes:
+    """
+    Create a BSON binary object with appropriate header and subtype tag byte.
+    """
+    flat = flatten_bytes(bs)
+    st = bytes([subtype])
+    return i32le(len(flat)) + st + flat
+
+
+def cstring(s: str | _ByteIter) -> bytes:
+    """Encode a string as UTF-8 and add a null terminator"""
+    match s:
+        case str(s):
+            return cstring(s.encode("utf-8"))
+        case bs:
+            bs = flatten_bytes(bs)
+            return bs + b"\0"
+
+
+def string(s: str | _ByteIter) -> bytes:
+    """Add a length header and null terminator to a UTF-8 string"""
+    cs = cstring(s)
+    # Length header includes the null terminator
+    hdr = i32le(len(cs))
+    return hdr + cs
+
+
+def utf8elem(key: str | _ByteIter, s: str | _ByteIter) -> bytes:
+    """Create a valid UTF-8 BSON element for the given string"""
+    return elem(key, Tag.UTF8, string(s))
+
+
+@dataclass(frozen=True)
+class ErrorInfo:
+    """
+    Information about an expected validation error
+    """
+
+    code: str
+    """Spellling of the error code to be expected"""
+    message: str
+    """The expected error message"""
+    offset: int
+    """The expected error offset"""
+
+
+@dataclass(frozen=True)
+class TestCase:
+    """
+    Defines a single validation test case.
+    """
+
+    name: str
+    """The name of the test case, as displayed in test runners, which will have a "/bson/validate" prefix"""
+    data: bytes
+    """The bytes that will be injested by `bson_init_static` to form the document to be validated"""
+    description: str | None
+    """A plaintext description of the test case and what it actually does. Rendered as a comment."""
+    flags: str = "0"
+    """Spelling of the flags argument passed to the validation API"""
+    error: ErrorInfo = ErrorInfo("0", "", 0)
+    """Expected error, if any"""
+
+    @property
+    def fn_name(self) -> str:
+        """Get a C identifier function name for this test case"""
+        return "_test_case_" + re.sub(r"[^\w]", "_", self.name).lower()
+
+
+def fmt_byte(n: int) -> str:
+    """
+    Format an octet value for C code. Will emit a char literal if certain ASCII,
+    otherwise an integer literal.
+    """
+    match n:
+        case 0:
+            return "0"
+        case a if re.match(r"[a-zA-Z0-9.$-]", chr(a)):
+            return f"'{chr(a)}'"
+        case a if a < 10:
+            return str(a)
+        case n:
+            return f"0x{n:0>2x}"
+
+
+GENERATED_NOTE = "// ! This code is GENERATED! Do not edit it directly!"
+
+HEADER = rf"""{GENERATED_NOTE}
+// clang-format off
+
+#include <bson/bson.h>
+
+#include <mlib/test.h>
+
+#include <TestSuite.h>
+"""
+
+
+def generate(case: TestCase) -> Iterable[str]:
+    """
+    Generate the lines of a test case function.
+    """
+    # A comment header
+    yield f"{GENERATED_NOTE}\n"
+    yield f"// Case: {case.name}\n"
+    # The function head
+    yield f"static inline void {case.fn_name}(void) {{\n"
+    # If we have a description, emit that in a block comment
+    if case.description:
+        yield "  /**\n"
+        lines = textwrap.dedent(case.description).strip().splitlines()
+        yield from (f"   * {ln}\n" for ln in lines)
+        yield "   */\n"
+    # Emit the byte array literal
+    yield "  const uint8_t bytes[] = {\n"
+    yield "\n".join(
+        textwrap.wrap(
+            ", ".join(map(fmt_byte, case.data)),
+            subsequent_indent=" " * 4,
+            initial_indent=" " * 4,
+            width=80,
+        )
+    )
+    yield "\n  };\n"
+    yield from [
+        # Initialize a BSON doc that points to the byte array
+        "  bson_t doc;\n",
+        "  mlib_check(bson_init_static(&doc, bytes, sizeof bytes));\n",
+        # The error object to be filled
+        "  bson_error_t error = {0};\n",
+        # The error offset. Expected to be reset to zero on success.
+        "  size_t offset = 999999;\n"
+        # Do the actual validation:
+        f"  const bool is_valid = bson_validate_with_error_and_offset(&doc, {case.flags}, &offset, &error);\n",
+    ]
+    is_error = case.error.code != "0"
+    yield from [
+        "  mlib_check(!is_valid);\n" if is_error else "  ASSERT_OR_PRINT(is_valid, error);\n",
+        f"  mlib_check(error.code, eq, {case.error.code});\n",
+        f"  mlib_check(error.message, str_eq, {json.dumps(case.error.message)});\n",
+        f"  mlib_check(offset, eq, {case.error.offset});\n" if is_error else "",
+    ]
+    yield "}\n"
+
+
+def corruption_at(off: int) -> ErrorInfo:
+    """
+    Generate an ErrorInfo to expect a message of "corrupt BSON" at the given
+    byte offset.
+
+    Note that this won't match if the error message is something other
+    than "corrupt BSON".
+    """
+    return ErrorInfo(BSON_VALIDATE_CORRUPT, "corrupt BSON", off)
+
+
+BSON_VALIDATE_CORRUPT = "BSON_VALIDATE_CORRUPT"
+BSON_VALIDATE_DOLLAR_KEYS = "BSON_VALIDATE_DOLLAR_KEYS"
+BSON_VALIDATE_DOT_KEYS = "BSON_VALIDATE_DOT_KEYS"
+BSON_VALIDATE_EMPTY_KEYS = "BSON_VALIDATE_EMPTY_KEYS"
+BSON_VALIDATE_UTF8 = "BSON_VALIDATE_UTF8"
+BSON_VALIDATE_UTF8_ALLOW_NULL = "BSON_VALIDATE_UTF8_ALLOW_NULL"
+MSG_EXPECTED_ID_FOLLOWING_REF = "Expected an $id element following $ref"
+
+
+def disallowed_key(char: str, k: str) -> str:
+    return f"Disallowed '{char}' in element key: \"{k}\""
+
+
+# d888888b d88888b .d8888. d888888b       .o88b.  .d8b.  .d8888. d88888b .d8888.
+# `~~88~~' 88'     88'  YP `~~88~~'      d8P  Y8 d8' `8b 88'  YP 88'     88'  YP
+#    88    88ooooo `8bo.      88         8P      88ooo88 `8bo.   88ooooo `8bo.
+#    88    88~~~~~   `Y8b.    88         8b      88~~~88   `Y8b. 88~~~~~   `Y8b.
+#    88    88.     db   8D    88         Y8b  d8 88   88 db   8D 88.     db   8D
+#    YP    Y88888P `8888Y'    YP          `Y88P' YP   YP `8888Y' Y88888P `8888Y'
+
+CASES: list[TestCase] = [
+    TestCase(
+        "empty",
+        doc(),
+        """Test a simple empty document object.""",
+    ),
+    TestCase(
+        "bad-element",
+        doc(b"f"),
+        "The element content is not valid",
+        error=corruption_at(6),
+    ),
+    TestCase(
+        "invalid-type",
+        doc(elem("foo", 0xE, b"foo")),
+        """The type tag "0x0e" is not a valid type""",
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "key/invalid/accept",
+        doc(
+            utf8elem("a", "b"),
+            utf8elem(b"foo\xffbar", "baz"),
+            utf8elem("c", "d"),
+        ),
+        """
+        The element key contains an invalid UTF-8 byte, but we accept it
+        because we aren't doing UTF-8 validation.
+        """,
+    ),
+    TestCase(
+        "key/invalid/reject",
+        doc(
+            utf8elem("a", "b"),
+            elem(b"foo\xffbar", Tag.UTF8, string("baz")),
+            utf8elem("c", "d"),
+        ),
+        """
+        The element key is not valid UTF-8 and we reject it when we do UTF-8
+        validation.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 13),
+    ),
+    TestCase(
+        "key/empty/accept",
+        doc(utf8elem("", "string")),
+        """
+        The element has an empty string key, and we accept this.
+        """,
+    ),
+    TestCase(
+        "key/empty/reject",
+        doc(
+            utf8elem("a", "b"),
+            utf8elem("", "string"),
+        ),
+        """
+        The element has an empty key, and we can reject it.
+        """,
+        flags=BSON_VALIDATE_EMPTY_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_EMPTY_KEYS, "Element key cannot be an empty string", 13),
+    ),
+    TestCase(
+        "key/empty/accept-if-absent",
+        doc(utf8elem("foo", "bar")),
+        """
+        We are checking for empty keys, and accept if they are absent.
+        """,
+        flags=BSON_VALIDATE_EMPTY_KEYS,
+    ),
+    TestCase(
+        "key/dot/accept",
+        doc(utf8elem("foo.bar", "baz")),
+        """
+        The element key has an ASCII dot, and we accept this since we don't
+        ask to validate it.
+        """,
+        flags=BSON_VALIDATE_EMPTY_KEYS,
+    ),
+    TestCase(
+        "key/dot/reject",
+        doc(utf8elem("a", "b"), utf8elem("foo.bar", "baz")),
+        """
+        The element has an ASCII dot, and we reject it when we ask to validate
+        it.
+        """,
+        flags=BSON_VALIDATE_DOT_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOT_KEYS, disallowed_key(".", "foo.bar"), 13),
+    ),
+    TestCase(
+        "key/dot/accept-if-absent",
+        doc(utf8elem("foo", "bar")),
+        """
+        We are checking for keys with dot '.', and accept if they are absent.
+        """,
+        flags=BSON_VALIDATE_DOT_KEYS,
+    ),
+    TestCase(
+        "key/dollar/accept",
+        doc(utf8elem("a", "b"), utf8elem("$foo", "bar")),
+        """
+        We can accept an element key that starts with a dollar '$' sign.
+        """,
+    ),
+    TestCase(
+        "key/dollar/reject",
+        doc(utf8elem("a", "b"), utf8elem("$foo", "bar")),
+        """
+        We can reject an element key that starts with a dollar '$' sign.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, disallowed_key("$", "$foo"), 13),
+    ),
+    TestCase(
+        "key/dollar/accept-in-middle",
+        doc(utf8elem("foo$bar", "baz")),
+        """
+        This contains a element key "foo$bar", but we don't reject this, as we
+        only care about keys that *start* with dollars.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "key/dollar/accept-if-absent",
+        doc(utf8elem("foo", "bar")),
+        """
+        We are validating for dollar-keys, and we accept because this document
+        doesn't contain any such keys.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "utf8/simple",
+        doc(utf8elem("string", "some string")),
+        "Simple UTF-8 string element",
+    ),
+    TestCase(
+        "utf8/missing-null",
+        doc(elem("a", Tag.UTF8, i32le(4), b"abcd")),
+        """
+        The UTF-8 element "a" contains 4 characters and declares its length of 4,
+        but the fourth character is supposed to be a null terminator. In this case,
+        it is the letter 'd'.
+        """,
+        error=corruption_at(14),
+    ),
+    TestCase(
+        "utf8/length-zero",
+        doc(elem("", Tag.UTF8, i32le(0), b"\0")),
+        "UTF-8 string length must always be at least 1 for the null terminator",
+        error=corruption_at(6),
+    ),
+    TestCase(
+        "utf8/length-too-short",
+        doc(elem("", Tag.UTF8, i32le(3), b"bar\0")),
+        "UTF-8 string is three chars and a null terminator, but the declared length is 3 (should be 4)",
+        error=corruption_at(12),
+    ),
+    TestCase(
+        "utf8/header-too-large",
+        doc(elem("foo", Tag.UTF8, b"\xff\xff\xff\xffbar\0")),
+        """
+        Data { "foo": "bar" } but the declared length of "bar" is way too large.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "utf8/valid",
+        doc(elem("foo", Tag.UTF8, string("abcd"))),
+        """
+        Validate a valid UTF-8 string with UTF-8 validation enabled.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+    ),
+    TestCase(
+        "utf8/invalid/accept",
+        doc(utf8elem("foo", b"abc\xffd")),
+        """
+        Validate an invalid UTF-8 string, but accept invalid UTF-8.
+        """,
+    ),
+    TestCase(
+        "utf8/invalid/reject",
+        doc(utf8elem("foo", b"abc\xffd")),
+        """
+        Validate an invalid UTF-8 string, and expect rejection.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "utf8/valid-with-null/accept-1",
+        doc(utf8elem("foo", b"abc\x00123")),
+        """
+        This is a valid UTF-8 string that contains a null character. We accept
+        it because we don't do UTF-8 validation.
+        """,
+    ),
+    TestCase(
+        "utf8/valid-with-null/accept-2",
+        doc(utf8elem("foo", b"abc\x00123")),
+        """
+        This is a valid UTF-8 string that contains a null character. We allow
+        it explicitly when we request UTF-8 validation.
+        """,
+        flags=f"{BSON_VALIDATE_UTF8} | {BSON_VALIDATE_UTF8_ALLOW_NULL}",
+    ),
+    TestCase(
+        "utf8/valid-with-null/reject",
+        doc(utf8elem("foo", b"abc\x00123")),
+        """
+        This is a valid UTF-8 string that contains a null character. We reject
+        this because we don't pass BSON_VALIDATE_UTF8_ALLOW_NULL.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8_ALLOW_NULL, "UTF-8 string contains a U+0000 (null) character", 4),
+    ),
+    TestCase(
+        "utf8/overlong-null/accept-1",
+        doc(utf8elem("foo", b"abc\xc0\x80123")),
+        """
+        This is an *invalid* UTF-8 string, and contains an overlong null. We should
+        accept it because we aren't doing UTF-8 validation.
+        """,
+    ),
+    TestCase(
+        "utf8/overlong-null/accept-2",
+        doc(utf8elem("foo", b"abc\xc0\x80123")),
+        """
+        ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+
+        This is an *invalid* UTF-8 string, because it contains an overlong null
+        "0xc0 0x80". Despite being invalid, we accept it because our current UTF-8
+        validation considers the overlong null to be a valid encoding for the null
+        codepoint (it isn't, but changing it would be a breaking change).
+
+        If/when UTF-8 validation is changed to reject overlong null, then this
+        test should change to expect rejection the invalid UTF-8.
+        """,
+        flags=f"{BSON_VALIDATE_UTF8} | {BSON_VALIDATE_UTF8_ALLOW_NULL}",
+    ),
+    TestCase(
+        "utf8/overlong-null/reject",
+        doc(utf8elem("foo", b"abc\xc0\x80123")),
+        """
+        ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+
+        This is an *invalid* UTF-8 string, because it contains an overlong null
+        character. Our UTF-8 validator wrongly accepts overlong null as a valid
+        UTF-8 sequence. This test fails because we disallow null codepoints, not
+        because the UTF-8 is invalid, and the error message reflects that.
+
+        If/when UTF-8 validation is changed to reject overlong null, then the
+        expected error code and error message for this test should change.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8_ALLOW_NULL, "UTF-8 string contains a U+0000 (null) character", 4),
+    ),
+    TestCase(
+        "utf8-key/invalid/accept",
+        doc(utf8elem(b"abc\xffdef", "bar")),
+        """
+        The element key is not valid UTf-8, but we accept it if we don't do
+        UTF-8 validation.
+        """,
+    ),
+    TestCase(
+        "utf8-key/invalid/reject",
+        doc(utf8elem(b"abc\xffdef", "bar")),
+        """
+        The element key is not valid UTF-8, and we reject it when we requested
+        UTF-8 validation.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "utf8-key/overlong-null/reject",
+        doc(utf8elem(b"abc\xc0\x80def", "bar")),
+        """
+        ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+
+        The element key is invalid UTF-8 because it contains an overlong null. We accept the
+        overlong null as a valid encoding of U+0000, but we reject the key because
+        we disallow null in UTF-8 strings.
+
+        If/when UTF-8 validation is changed to reject overlong null, then the
+        expected error code and error message for this test should change.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8_ALLOW_NULL, "UTF-8 string contains a U+0000 (null) character", 4),
+    ),
+    TestCase(
+        "utf8-key/overlong-null/accept",
+        doc(utf8elem(b"abc\xc0\x80def", "bar")),
+        """
+        ! NOTE: overlong-null: This test relies on our UTF-8 validation accepting the `c0 80` sequence
+
+        The element key is invalid UTF-8 because it contains an overlong null. We accept the
+        overlong null as a valid encoding of U+0000, and we allow it in an element key because
+        we pass ALLOW_NULL
+
+        If/when UTF-8 validation is changed to reject overlong null, then this
+        test case should instead reject the key string as invalid UTF-8.
+        """,
+        flags=f"{BSON_VALIDATE_UTF8} | {BSON_VALIDATE_UTF8_ALLOW_NULL}",
+    ),
+    TestCase(
+        "array/empty",
+        doc(elem("array", Tag.Array, doc())),
+        "Simple empty array element",
+    ),
+    TestCase(
+        "array/simple",
+        doc(
+            elem(
+                "array",
+                Tag.Array,
+                doc(
+                    elem("0", Tag.Int32, i32le(42)),
+                    elem("1", Tag.Int32, i32le(1729)),
+                    elem("2", Tag.Int32, i32le(-8)),
+                ),
+            )
+        ),
+        "Simple array element of integers",
+    ),
+    TestCase(
+        "array/invalid-element",
+        doc(
+            elem(
+                "array",
+                Tag.Array,
+                doc(
+                    elem("0", Tag.Int32, i32le(42)),
+                    elem("1", Tag.Int32, i32le(1729)[-1:]),  # Truncated
+                    elem("2", Tag.Int32, i32le(-8)),
+                ),
+            )
+        ),
+        "Simple array element of integers, but one element is truncated",
+        error=corruption_at(34),
+    ),
+    TestCase(
+        "array/invalid-element-check-offset",
+        doc(
+            elem(
+                "array-shifted",
+                Tag.Array,
+                doc(
+                    elem("0", Tag.Int32, i32le(42)),
+                    elem("1", Tag.Int32, i32le(1729)[-1:]),  # Truncated
+                    elem("2", Tag.Int32, i32le(-8)),
+                ),
+            )
+        ),
+        """
+        This is the same as the array/invalid-element test, but with a longer
+        key string on the parent array. This is to check that the error offset
+        is properly adjusted for the additional characters.
+        """,
+        error=corruption_at(42),
+    ),
+    TestCase(
+        "symbol/simple",
+        doc(elem("symbol", Tag.Symbol, string("void 0;"))),
+        """
+        A simple document: { symbol: Symbol("void 0;") }
+        """,
+    ),
+    TestCase(
+        "symbol/invalid-utf8/accept",
+        doc(elem("symbol", Tag.Symbol, string(b"void\xff 0;"))),
+        """
+        A simple symbol document, but the string contains invalid UTF-8
+        """,
+    ),
+    TestCase(
+        "symbol/invalid-utf8/reject",
+        doc(elem("symbol", Tag.Symbol, string(b"void\xff 0;"))),
+        """
+        A simple symbol document, but the string contains invalid UTF-8
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "symbol/length-zero",
+        doc(b"\x0e\0" + i32le(0) + b"\0"),
+        "Symbol string length must always be at least 1 for the null terminator",
+        error=corruption_at(6),
+    ),
+    TestCase(
+        "symbol/length-too-short",
+        doc(b"\x0e\0" + i32le(3) + b"bar\0"),
+        """
+        Symbol string is three chars and a null terminator, but the declared
+        length is 3 (should be 4)
+        """,
+        error=corruption_at(12),
+    ),
+    TestCase(
+        "code/simple",
+        doc(elem("code", Tag.Code, string("void 0;"))),
+        """
+        A simple document: { code: Code("void 0;") }
+        """,
+    ),
+    TestCase(
+        "code/invalid-utf8/accept",
+        doc(elem("code", Tag.Code, string(b"void\xff 0;"))),
+        """
+        A simple code document, but the string contains invalid UTF-8
+        """,
+    ),
+    TestCase(
+        "code/invalid-utf8/reject",
+        doc(elem("code", Tag.Code, string(b"void\xff 0;"))),
+        """
+        A simple code document, but the string contains invalid UTF-8
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "code/length-zero",
+        doc(elem("code", Tag.Code, i32le(0), b"\0")),
+        "Code string length must always be at least 1 for the null terminator",
+        error=corruption_at(10),
+    ),
+    TestCase(
+        "code/length-too-short",
+        doc(elem("code", Tag.Code, i32le(3), b"bar\0")),
+        "Code string is three chars and a null terminator, but the declared length is 3 (should be 4)",
+        error=corruption_at(16),
+    ),
+    # Code w/ scope
+    TestCase(
+        "code-with-scope/simple",
+        doc(elem("foo", Tag.CodeWithScope, code_with_scope("void 0;", doc()))),
+        "A simple valid code-with-scope element",
+    ),
+    TestCase(
+        "code-with-scope/invalid-code-length-zero",
+        doc(
+            elem(
+                "",
+                Tag.CodeWithScope,
+                i32le(10),
+                b"\0\0\0\0",  # strlen
+                b"\0",  # code
+                doc(),  # scope
+            )
+        ),
+        """
+        Data { "": CodeWithScope("", {}) }, but the code string length is zero, when
+        it must be at least 1
+        """,
+        error=corruption_at(6),
+    ),
+    TestCase(
+        "code-with-scope/invalid-code-length-too-large",
+        doc(
+            elem(
+                "",
+                Tag.CodeWithScope,
+                i32le(10),
+                b"\xff\xff\xff\xff",  # strlen (too big)
+                b"\0",
+                doc(),  # Scope
+            )
+        ),
+        """
+        Data { "": CodeWithScope("", {}) }, but the code string length is way too large
+        """,
+        error=corruption_at(6),
+    ),
+    TestCase(
+        "code-with-scope/invalid-scope",
+        doc(elem("foo", Tag.CodeWithScope, code_with_scope("void 0;", doc()[:-1]))),
+        "A code-with-scope element, but the scope document is corrupted",
+        error=corruption_at(13),
+    ),
+    TestCase(
+        "code-with-scope/empty-key-in-scope",
+        doc(
+            elem(
+                "code",
+                Tag.CodeWithScope,
+                code_with_scope(
+                    "void 0;",
+                    doc(
+                        elem("obj", Tag.Document, doc(utf8elem("", "string"))),
+                    ),
+                ),
+            )
+        ),
+        """
+        A code-with-scope element. The scope itself contains empty keys within
+        objects, and we ask to reject empty keys. But the scope document should
+        be treated as an opaque closure, so our outer validation rules do not
+        apply.
+        """,
+        flags=BSON_VALIDATE_EMPTY_KEYS,
+    ),
+    TestCase(
+        "code-with-scope/corrupt-scope",
+        doc(
+            elem(
+                "code",
+                Tag.CodeWithScope,
+                code_with_scope(
+                    "void 0;",
+                    doc(
+                        elem(
+                            "foo",
+                            Tag.UTF8,
+                            i32le(0),  # Invalid string length
+                            b"\0",
+                        )
+                    ),
+                ),
+            )
+        ),
+        "A code-with-scope element, but the scope contains corruption",
+        error=ErrorInfo(BSON_VALIDATE_CORRUPT, 'Error in scope document for element "code": corrupt BSON', offset=13),
+    ),
+    TestCase(
+        "code-with-scope/corrupt-scope-2",
+        doc(
+            elem(
+                "code",
+                Tag.CodeWithScope,
+                code_with_scope(
+                    "void 0;",
+                    doc(
+                        elem(
+                            "foo",
+                            Tag.UTF8,
+                            b"\xff\xff\xff\xff",  # Invalid string length
+                            b"\0",
+                        )
+                    ),
+                ),
+            )
+        ),
+        "A code-with-scope element, but the scope contains corruption",
+        error=ErrorInfo(BSON_VALIDATE_CORRUPT, 'Error in scope document for element "code": corrupt BSON', offset=13),
+    ),
+    TestCase(
+        "regex/simple",
+        doc(elem("regex", Tag.Regex, b"1234\0gi\0")),
+        """
+        Simple document: { regex: Regex("1234", "gi") }
+        """,
+    ),
+    TestCase(
+        "regex/invalid-opts",
+        doc(elem("regex", Tag.Regex, b"foo\0bar")),
+        """
+        A regular expression element with missing null terminator. The main
+        option string "foo" has a null terminator, but the option component "bar"
+        does not have a null terminator. A naive parse will see the doc's null
+        terminator as the null terminator for the options string, but that's
+        invalid!
+        """,
+        error=corruption_at(18),
+    ),
+    TestCase(
+        "regex/double-null",
+        doc(elem("regex", Tag.Regex, b"foo\0bar\0\0")),
+        """
+        A regular expression element with an extra null terminator. Since regex
+        is delimited by its null terminator, the iterator will stop early before
+        the actual EOD.
+        """,
+        error=corruption_at(21),
+    ),
+    TestCase(
+        "regex/invalid-utf8/accept",
+        doc(elem("regex", Tag.Regex, b"foo\xffbar\0gi\0")),
+        """
+        A regular expression that contains invalid UTF-8.
+        """,
+    ),
+    TestCase(
+        "regex/invalid-utf8/reject",
+        doc(elem("regex", Tag.Regex, b"foo\xffbar\0gi\0")),
+        """
+        A regular expression that contains invalid UTF-8.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "regex/invalid-utf8/accept-if-absent",
+        doc(elem("regex", Tag.Regex, b"foo\0gi\0")),
+        """
+        A regular valid UTf-8 regex. We check for invalid UTf-8, and accept becaues
+        the regex is fine.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+    ),
+    TestCase(
+        "dbpointer/string-length-zero",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                i32le(0),  # String length (invalid)
+                b"\0",  # Empty string
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        Document { "foo": DBPointer("", <oid>) }, but the length header on the inner
+        string is zero, when it must be at least 1.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "dbpointer/string-length-too-big",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                b"\xff\xff\xff\xff",  # String length  (invalid)
+                b"foobar\0",  # Simple string
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        Document { "foo": DBPointer("foobar", <oid>) }, but the length header on the inner
+        string is far too large
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "dbpointer/truncated",
+        doc(
+            utf8elem("a", "b"),
+            elem(
+                "foo",
+                Tag.DBPointer,
+                i32le(7),  # 7 bytes, bleeding into the null terminator
+                b"foobar",  # Simple string, missing a null terminator.
+                b"\x00\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            ),
+            utf8elem("a", "b"),
+        ),
+        """
+        Document { "foo": DBPointer("foobar", <oid>) }, but the length header on
+        the string is one byte too large, causing it to use the first byte of the
+        OID as the null terminator. This should fail when iterating.
+        """,
+        error=corruption_at(43),
+    ),
+    TestCase(
+        "dbpointer/missing-null",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                i32le(4),
+                b"abcd",  # Missing null terminator
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        Document { "foo": DBPointer("abcd", <oid>) }, the length header on
+        the string is 4, but the fourth byte is not a null terminator.
+        """,
+        error=corruption_at(16),
+    ),
+    TestCase(
+        "dbpointer/invalid-utf8/accept",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                string(b"abc\xffdef"),  # String with invalid UTF-8
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        DBPointer document, but the collection string contains invalid UTF-8
+        """,
+    ),
+    TestCase(
+        "dbpointer/invalid-utf8/reject",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                string(b"abc\xffdef"),  # String with invalid UTF-8
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        DBPointer document, but the collection string contains invalid UTF-8
+        """,
+        flags=BSON_VALIDATE_UTF8,
+        error=ErrorInfo(BSON_VALIDATE_UTF8, "Text element is not valid UTF-8", 4),
+    ),
+    TestCase(
+        "dbpointer/invalid-utf8/accept-if-absent",
+        doc(
+            elem(
+                "foo",
+                Tag.DBPointer,
+                string(b"abcdef"),  # Valid string
+                b"\x52\x59\xb5\x6a\xfa\x5b\xd8\x41\xd6\x58\x5d\x99",  # OID
+            )
+        ),
+        """
+        DBPointer document, and we validate UTF-8. Accepts because there is no
+        invalid UTF-8 here.
+        """,
+        flags=BSON_VALIDATE_UTF8,
+    ),
+    TestCase(
+        "subdoc/simple",
+        doc(elem("doc", Tag.Document, doc(utf8elem("foo", "bar")))),
+        """
+        A simple document: { doc: { foo: "bar" } }
+        """,
+    ),
+    TestCase(
+        "subdoc/invalid-shared-null",
+        doc(elem("doc", Tag.Document, doc()[:-1])),
+        """
+        A truncated subdocument element, with its null terminator accidentally
+        overlapping the parent document's null.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "subdoc/overlapping-utf8-null",
+        doc(elem("doc", Tag.Document, doc(utf8elem("bar", "baz\0")[:-1]))),
+        """
+        Encodes the document:
+
+            { "foo": { "bar": "baz" } }
+
+        but the foo.bar UTF-8 string is truncated improperly and reuses the null
+        terminator for "foo"
+        """,
+        error=corruption_at(18),
+    ),
+    TestCase(
+        "subdoc/invalid-element",
+        doc(elem("doc", Tag.Document, doc(elem("dbl", Tag.Double, b"abcd")))),
+        "A subdocument that contains an invalid element",
+        error=corruption_at(18),
+    ),
+    TestCase(
+        "subdoc/header-too-large",
+        doc(
+            elem(
+                "foo",
+                Tag.Document,
+                b"\xf7\xff\xff\xff\0",  # Bad document
+            ),
+        ),
+        """
+        Data {"foo": {}}, but the subdoc header is too large.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "subdoc/header-too-small",
+        doc(
+            elem(
+                "test",
+                Tag.Document,
+                b"\x04\0\0\0",  # Only four bytes. All docs must be at least 5
+            ),
+        ),
+        """
+        Nested document with a header value of 4, which is always too small.
+        """,
+        error=corruption_at(4),
+    ),
+    TestCase(
+        "subdoc/impossible-size",
+        doc(
+            elem(
+                "foo",
+                Tag.Document,
+                b"\xff\xff\xff\xff\0",  # Bad document
+            ),
+        ),
+        """
+        Data {"foo": {}}, but the subdoc header is UINT32_MAX/INT32_MIN, which
+        becomes is an invalid document header.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "null/simple",
+        doc(elem("null", Tag.Null)),
+        """
+        A simple document: { "null": null }
+        """,
+    ),
+    TestCase(
+        "undefined/simple",
+        doc(elem("undefined", Tag.Undefined)),
+        """
+        A simple document: { "undefined": undefined }
+        """,
+    ),
+    TestCase(
+        "binary/simple",
+        doc(elem("binary", Tag.Binary, binary(0x80, b"12345"))),
+        """
+        Simple binary data { "binary": Binary(0x80, b'12345') }
+        """,
+    ),
+    TestCase(
+        "binary/bad-length-zero-subtype-2",
+        doc(
+            elem(
+                "binary",
+                Tag.Binary,
+                i32le(0),  # Invalid: Zero length
+                b"\x02",  # subtype two
+                i32le(4),  # Length of 4
+                b"1234",  # payload
+            ),
+        ),
+        """
+        Binary data that has an invalid length header. It is subtype 2,
+        which means it contains an additional length header.
+        """,
+        error=corruption_at(12),
+    ),
+    TestCase(
+        "binary/bad-inner-length-on-subtype-2",
+        doc(
+            elem(
+                "binary",
+                Tag.Binary,
+                i32le(8),  # Valid length
+                b"\x02",  # subtype two
+                i32le(2),  # Invalid length of (should be 4)
+                b"1234",  # payload
+            ),
+        ),
+        """
+        Binary data that has an valid outer length header, but the inner length
+        header for subtype 2 has an incorrect value.
+        """,
+        error=corruption_at(17),
+    ),
+    TestCase(
+        "binary/bad-length-too-small",
+        doc(
+            elem(
+                "binary",
+                Tag.Binary,
+                i32le(2),  # Length prefix (too small)
+                b"\x80",  # subtype
+                b"1234",  # payload
+            ),
+        ),
+        """
+        Data { "binary": Binary(0x80, b'1234') }, but the length header on
+        the Binary object is too small.
+
+        This won't cause the binary to decode wrong, but it will cause the iterator
+        to jump into the middle of the binary data which will not decode as a
+        proper BSON element.
+        """,
+        error=corruption_at(22),
+    ),
+    TestCase(
+        "binary/bad-length-too-big",
+        doc(
+            elem(
+                "binary",
+                Tag.Binary,
+                b"\xf3\xff\xff\xff",  # Length prefix (too big)
+                b"\x80",  # subtype
+                b"1234",  # data
+            ),
+        ),
+        """
+        Data { "binary": Binary(0x80, b'1234') }, but the length header on
+        the Binary object is too large.
+        """,
+        error=corruption_at(12),
+    ),
+    TestCase(
+        "binary/old-invalid/1",
+        doc(
+            elem(
+                "binary",
+                Tag.Binary,
+                binary(
+                    2,
+                    i32le(5),  # Bad length prefix: Should be 4
+                    b"abcd",
+                ),
+            ),
+        ),
+        """
+        This is an old-style binary type 0x2. It has an inner length header of 5,
+        but it should be 4.
+        """,
+        error=corruption_at(17),
+    ),
+    TestCase(
+        "binary/old-invalid/2",
+        doc(
+            elem(
+                "bin",
+                Tag.Binary,
+                binary(
+                    2,
+                    b"abc",  # Bad: Subtype 2 requires at least four bytes
+                ),
+            )
+        ),
+        """
+        This is an old-style binary type 0x2. The data segment is too small to
+        be valid.
+        """,
+        error=corruption_at(9),
+    ),
+    TestCase(
+        "minkey/simple",
+        doc(elem("min", Tag.MinKey)),
+        "A simple document with a MinKey element",
+    ),
+    TestCase(
+        "maxkey/simple",
+        doc(elem("max", Tag.MaxKey)),
+        "A simple document with a MaxKey element",
+    ),
+    TestCase(
+        "int32/simple",
+        doc(elem("int32", Tag.Int32, i32le(42))),
+        "A simple document with a valid single int32 element",
+    ),
+    TestCase(
+        "int32/truncated",
+        doc(elem("int32-truncated", Tag.Int32, i32le(42)[:-1])),
+        "Truncated 32-bit integer",
+        error=corruption_at(21),
+    ),
+    TestCase("timestamp/simple", doc(elem("timestamp", Tag.Timestamp, i64le(1729))), """A simple timestamp element"""),
+    TestCase(
+        "timestamp/truncated",
+        doc(elem("timestamp", Tag.Timestamp, i64le(1729)[:-1])),
+        """A truncated timestamp element""",
+        error=corruption_at(15),
+    ),
+    TestCase(
+        "int64/simple",
+        doc(elem("int64", Tag.Int64, i64le(1729))),
+        "A simple document with a valid single int64 element",
+    ),
+    TestCase(
+        "int64/truncated",
+        doc(elem("int64-truncated", Tag.Int64, i64le(1729)[:-1])),
+        "Truncated 64-bit integer",
+        error=corruption_at(21),
+    ),
+    TestCase(
+        "double/simple",
+        doc(elem("double", Tag.Double, f64le(3.14))),
+        "Simple float64 element",
+    ),
+    TestCase(
+        "double/truncated",
+        doc(elem("double-truncated", Tag.Double, f64le(3.13)[:-1])),
+        "Truncated 64-bit float",
+        error=corruption_at(22),
+    ),
+    TestCase(
+        "boolean/simple-false",
+        doc(elem("bool", Tag.Boolean, b"\x00")),
+        """A simple boolean 'false'""",
+    ),
+    TestCase(
+        "boolean/simple-true",
+        doc(elem("bool", Tag.Boolean, b"\x01")),
+        """A simple boolean 'true'""",
+    ),
+    TestCase(
+        "boolean/invalid",
+        doc(elem("bool", Tag.Boolean, b"\xc3")),
+        """
+        An invalid boolean octet. Must be '0' or '1', but is 0xc3.
+        """,
+        error=corruption_at(10),
+    ),
+    TestCase(
+        "datetime/simple",
+        doc(elem("utc", Tag.Datetime, b"\x0b\x98\x8c\x2b\x33\x01\x00\x00")),
+        "Simple datetime element",
+    ),
+    TestCase(
+        "datetime/truncated",
+        doc(elem("utc", Tag.Datetime, b"\x0b\x98\x8c\x2b\x33\x01\x00")),
+        "Truncated datetime element",
+        error=corruption_at(9),
+    ),
+    # DBRef
+    TestCase(
+        "dbref/missing-id",
+        doc(utf8elem("$ref", "foo")),
+        """This dbref document is missing an $id element""",
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, MSG_EXPECTED_ID_FOLLOWING_REF, 18),
+    ),
+    TestCase(
+        "dbref/non-id",
+        doc(utf8elem("$ref", "foo"), utf8elem("bar", "baz")),
+        """
+        The 'bar' element should be an '$id' element.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, MSG_EXPECTED_ID_FOLLOWING_REF, 18),
+    ),
+    TestCase(
+        "dbref/not-first-elements",
+        doc(utf8elem("foo", "bar"), utf8elem("$ref", "a"), utf8elem("$id", "b")),
+        """
+        This would be a valid DBRef, but the "$ref" key must come first.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, disallowed_key("$", "$ref"), 17),
+    ),
+    TestCase(
+        "dbref/ref-without-id-with-db",
+        doc(utf8elem("$ref", "foo"), utf8elem("$db", "bar")),
+        """
+        There should be an $id element, but we skip straight to $db
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, MSG_EXPECTED_ID_FOLLOWING_REF, 18),
+    ),
+    TestCase(
+        "dbref/non-string-ref",
+        doc(elem("$ref", Tag.Int32, i32le(42))),
+        """
+        The $ref element must be a string, but is an integer.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, "$ref element must be a UTF-8 element", 4),
+    ),
+    TestCase(
+        "dbref/non-string-db",
+        doc(
+            utf8elem("$ref", "foo"),
+            utf8elem("$id", "bar"),
+            elem("$db", Tag.Int32, i32le(42)),
+        ),
+        """
+        The $db element should be a string, but is an integer.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, "$db element in DBRef must be a UTF-8 element", 31),
+    ),
+    TestCase(
+        "dbref/invalid-extras-between",
+        doc(
+            utf8elem("$ref", "foo"),
+            utf8elem("$id", "bar"),
+            utf8elem("extra", "field"),
+            utf8elem("$db", "baz"),
+        ),
+        """
+        Almost a valid DBRef, but there is an extra field before $db. We reject $db
+        as an invalid key.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, disallowed_key("$", "$db"), 48),
+    ),
+    TestCase(
+        "dbref/invalid-double-ref",
+        doc(
+            utf8elem("$ref", "foo"),
+            utf8elem("$ref", "bar"),
+            utf8elem("$id", "baz"),
+        ),
+        """
+        Invalid DBRef contains a second $ref element.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, MSG_EXPECTED_ID_FOLLOWING_REF, 18),
+    ),
+    TestCase(
+        "dbref/invalid-missing-ref",
+        doc(utf8elem("$id", "foo")),
+        """
+        DBRef document requires a $ref key to be first.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+        error=ErrorInfo(BSON_VALIDATE_DOLLAR_KEYS, disallowed_key("$", "$id"), 4),
+    ),
+    TestCase(
+        "dbref/valid/simple",
+        doc(utf8elem("$ref", "foo"), utf8elem("$id", "bar")),
+        """
+        This is a simple valid DBRef element.
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "dbref/valid/simple-with-db",
+        doc(utf8elem("$ref", "foo"), utf8elem("$id", "bar"), utf8elem("$db", "baz")),
+        """
+        A simple DBRef of the form:
+
+            { $ref: "foo", $id: "bar", $db: "baz" }
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "dbref/valid/nested-id-doc",
+        doc(
+            utf8elem("$ref", "foo"),
+            elem(
+                "$id",
+                Tag.Document,
+                doc(
+                    utf8elem("$ref", "foo2"),
+                    utf8elem("$id", "bar2"),
+                    utf8elem("$db", "baz2"),
+                ),
+            ),
+            utf8elem("$db", "baz"),
+        ),
+        """
+        This is a valid DBRef of the form:
+
+            { $ref: foo, $id: { $ref: "foo2", $id: "bar2", $db: "baz2" }, $db: "baz" }
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "dbref/valid/trailing-content",
+        doc(
+            utf8elem("$ref", "foo"),
+            utf8elem("$id", "bar"),
+            utf8elem("$db", "baz"),
+            utf8elem("extra", "field"),
+        ),
+        """
+        A valid DBRef of the form:
+
+            {
+                $ref: "foo",
+                $id: "bar",
+                $db: "baz",
+                extra: "field",
+            }
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+    TestCase(
+        "dbref/valid/trailing-content-no-db",
+        doc(
+            utf8elem("$ref", "foo"),
+            utf8elem("$id", "bar"),
+            utf8elem("extra", "field"),
+        ),
+        """
+        A valid DBRef of the form:
+
+            {
+                $ref: "foo",
+                $id: "bar",
+                extra: "field",
+            }
+        """,
+        flags=BSON_VALIDATE_DOLLAR_KEYS,
+    ),
+]
+
+if __name__ == "__main__":
+    # We don't take an arguments, but error if any are given
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.parse_args()
+    # Start with the header
+    print(HEADER)
+    # Print each test case
+    for c in CASES:
+        print()
+        for part in generate(c):
+            print(part, end="")
+
+    # Print the registration function
+    print(f"\n{GENERATED_NOTE}")
+    print("void test_install_generated_bson_validation(TestSuite* suite) {")
+    for c in CASES:
+        print(f'  TestSuite_Add(suite, "/bson/validate/" {json.dumps(c.name)}, {c.fn_name});')
+    print("}")
diff -pruN 1.30.4-1/src/libmongoc/.gitignore 2.0.2-1/src/libmongoc/.gitignore
--- 1.30.4-1/src/libmongoc/.gitignore	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/.gitignore	2025-06-19 15:42:22.000000000 +0000
@@ -1,12 +1,3 @@
-# CMake artifacts
-libmongoc-1.0-config-version.cmake
-libmongoc-1.0-config.cmake
-libmongoc-static-1.0-config-version.cmake
-libmongoc-static-1.0-config.cmake
-mongoc/mongoc-1.0-config.cmake
-mongoc/mongoc-1.0-config-version.cmake
-mongoc/mongoc-targets.cmake
-
 # Test program for mongoc_get_accept_args in CMakeLists.txt
 accept_test1.c
 
@@ -42,7 +33,7 @@ find-and-modify
 hello_mongoc
 mongoc-dump
 mongoc-ping
-mongoc-stat
+mongoc2-stat
 mongoc-tail
 
 # Test binaries
diff -pruN 1.30.4-1/src/libmongoc/CMakeLists.txt 2.0.2-1/src/libmongoc/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -12,8 +12,6 @@ project (libmongoc
 set(libmongoc_VERSION_PRERELEASE ${mongo-c-driver_VERSION_PRERELEASE})
 set(libmongoc_VERSION_FULL ${mongo-c-driver_VERSION_FULL})
 
-set (MONGOC_API_VERSION 1.0)
-
 include (CheckSchedGetCPU)
 include (CheckStructHasMember)
 include (CheckSymbolExists)
@@ -23,15 +21,19 @@ include (InstallRequiredSystemLibraries)
 
 message (STATUS "libmongoc version (from VERSION_CURRENT file): ${MONGOC_VERSION}")
 
-set (MONGOC_API_VERSION 1.0)
-set (MONGOC_TARGETS_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/mongoc-${MONGOC_API_VERSION}")
-
 # Defaults.
 set (MONGOC_ENABLE_COMPRESSION 0)
 set (MONGOC_ENABLE_COMPRESSION_SNAPPY 0)
 set (MONGOC_ENABLE_COMPRESSION_ZLIB 0)
 set (MONGOC_ENABLE_COMPRESSION_ZSTD 0)
 
+if(NOT DEFINED MONGOC_INSTALL_INCLUDEDIR)
+   set(MONGOC_INSTALL_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}/mongoc-${PROJECT_VERSION}")
+endif()
+if(NOT DEFINED MONGOC_INSTALL_CMAKEDIR)
+   set(MONGOC_INSTALL_CMAKEDIR "${MONGO_C_DRIVER_INSTALL_CMAKEDIR}/mongoc-${PROJECT_VERSION}")
+endif()
+
 # Definition for mongoc-config.h:
 mongo_pick(MONGOC_ENABLE_SRV 1 0 ENABLE_SRV)
 
@@ -195,13 +197,6 @@ function(_auto_pick_tls_lib)
       find_package(OpenSSL)
       if(OpenSSL_FOUND)
          _use_named_tls_lib(OPENSSL)
-      else()
-         # No OpenSSL. What about LibreSSL?
-         find_package(LibreSSL)
-         if(LibreSSL_FOUND)
-            message(DEPRECATION "LibreSSL was automatically chosen as the TLS library. Support for LibreSSL is deprecated and may be removed in a future major release. Use ENABLE_SSL option to specify a different TLS library.")
-            _use_named_tls_lib(LIBRESSL)
-         endif()
       endif()
    endif()
 endfunction()
@@ -211,12 +206,10 @@ set(SecureTransport/LINK_LIBRARIES "-fra
 set(SecureTransport/pkg_config_LIBS -framework Corefoundation -framework Security)
 set(SecureChannel/LINK_LIBRARIES secur32.lib crypt32.lib Bcrypt.lib)
 set(SecureChannel/pkg_config_LIBS ${SecureChannel/LINK_LIBRARIES})
-set(LibreSSL/LINK_LIBRARIES LibreSSL::TLS LibreSSL::Crypto)
-set(LibreSSL/pkg_config_LIBS -ltls -lcrypto)
 set(OpenSSL/LINK_LIBRARIES OpenSSL::SSL OpenSSL::Crypto $<$<PLATFORM_ID:Windows>:crypt32.lib>)
 set(OpenSSL/pkg_config_LIBS -lssl -lcrypto $<$<PLATFORM_ID:Windows>:crypt32.lib>)
 # Use *exactly* the TLS library identified by the given name, which is one of
-#  `OPENSSL`, `LIBRESSL`, `DARWIN`, or `WINDOWS`.
+#  `OPENSSL`, `DARWIN`, or `WINDOWS`.
 function(_use_named_tls_lib libname)
    # Use this property to track what package we import for our TLS libraries:
    set_property(DIRECTORY PROPERTY _mongoc-tls-package NO)
@@ -224,14 +217,6 @@ function(_use_named_tls_lib libname)
       find_package(OpenSSL REQUIRED)
       set(backend OpenSSL)
       set_property(DIRECTORY PROPERTY _mongoc-tls-package OpenSSL)
-   elseif(libname STREQUAL "LIBRESSL")
-      find_package(LibreSSL REQUIRED)
-      set(backend LibreSSL)
-      install(
-         FILES "${mongo-c-driver_SOURCE_DIR}/build/cmake/FindLibreSSL.cmake"
-         DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/mongoc-${MONGOC_API_VERSION}/3rdParty"
-         )
-      set_property(DIRECTORY PROPERTY _mongoc-tls-package LibreSSL)
    elseif(libname STREQUAL "DARWIN")
       set(backend SecureTransport)
    elseif(libname STREQUAL "WINDOWS")
@@ -260,21 +245,14 @@ set_package_properties(
    TYPE OPTIONAL
    PURPOSE "Provides a cryptography and TLS backend"
 )
-set_package_properties(
-   LibreSSL PROPERTIES
-   DESCRIPTION "an alternative implementation of the OpenSSL interface, created by the OpenBSD project"
-   TYPE OPTIONAL
-   PURPOSE "Provides a cryptography and TLS backend"
-)
 
 mongo_bool01(MONGOC_ENABLE_SSL [[TLS_BACKEND]])
 mongo_bool01(MONGOC_ENABLE_SSL_SECURE_CHANNEL [[TLS_BACKEND STREQUAL "SecureChannel"]])
 mongo_bool01(MONGOC_ENABLE_SSL_SECURE_TRANSPORT [[TLS_BACKEND STREQUAL "SecureTransport"]])
 mongo_bool01(MONGOC_ENABLE_SSL_OPENSSL [[TLS_BACKEND STREQUAL "OpenSSL"]])
-mongo_bool01(MONGOC_ENABLE_SSL_LIBRESSL [[TLS_BACKEND STREQUAL "LibreSSL"]])
 
 mongo_bool01(MONGOC_ENABLE_CRYPTO [[TLS_BACKEND]])
-mongo_bool01(MONGOC_ENABLE_CRYPTO_LIBCRYPTO [[MONGOC_ENABLE_SSL_OPENSSL OR MONGOC_ENABLE_SSL_LIBRESSL]])
+mongo_bool01(MONGOC_ENABLE_CRYPTO_LIBCRYPTO [[MONGOC_ENABLE_SSL_OPENSSL]])
 mongo_bool01(MONGOC_ENABLE_CRYPTO_CNG [[MONGOC_ENABLE_SSL_SECURE_CHANNEL]])
 mongo_bool01(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO [[MONGOC_ENABLE_SSL_SECURE_TRANSPORT]])
 mongo_bool01(MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE [[ENABLE_CRYPTO_SYSTEM_PROFILE]])
@@ -365,7 +343,7 @@ function(_use_sasl libname)
    elseif(libname STREQUAL "CYRUS")
       find_package(SASL2 2.0 REQUIRED)
       target_link_libraries(_mongoc-sasl_backend INTERFACE SASL2::SASL2)
-      install(FILES "${mongo-c-driver_SOURCE_DIR}/build/cmake/FindSASL2.cmake" DESTINATION "${MONGOC_TARGETS_INSTALL_DIR}/3rdParty")
+      install(FILES "${mongo-c-driver_SOURCE_DIR}/build/cmake/FindSASL2.cmake" DESTINATION "${MONGOC_INSTALL_CMAKEDIR}/3rdParty")
       set(backend "Cyrus")
    else()
       message(FATAL_ERROR "Unknown SASL backend “${libname}”")
@@ -404,12 +382,6 @@ add_feature_info(
    "authenticate with MongoDB servers using SASL: “Simple Authentication and Security Layer” (${SASL_BACKEND})"
 )
 
-if (ENABLE_AUTOMATIC_INIT_AND_CLEANUP)
-   set (MONGOC_NO_AUTOMATIC_GLOBALS 0)
-else ()
-   set (MONGOC_NO_AUTOMATIC_GLOBALS 1)
-endif ()
-
 if (WIN32)
    SET (CMAKE_EXTRA_INCLUDE_FILES "ws2tcpip.h")
 else ()
@@ -517,10 +489,10 @@ elseif (NOT ENABLE_CLIENT_SIDE_ENCRYPTIO
       find_package (mongocrypt QUIET)
    endif ()
 
-   if (mongocrypt_FOUND AND "${mongocrypt_VERSION}" VERSION_LESS 1.12.0)
+   if (mongocrypt_FOUND AND "${mongocrypt_VERSION}" VERSION_LESS 1.13.0)
       message (STATUS "  libmongocrypt found at ${mongocrypt_DIR}")
       message (STATUS "  libmongocrypt version ${mongocrypt_VERSION} found")
-      message (STATUS "  libmongocrypt version 1.12.0 is required to enable In-Use Encryption Support.")
+      message (STATUS "  libmongocrypt version 1.13.0 is required to enable In-Use Encryption Support.")
       set (REQUIRED_MONGOCRYPT_VERSION_FOUND OFF)
    elseif (mongocrypt_FOUND)
       set (REQUIRED_MONGOCRYPT_VERSION_FOUND ON)
@@ -617,15 +589,12 @@ set (MONGOC_SOURCES
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-handshake.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-host-list.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-http.c
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-index.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-init.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-interrupt.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-list.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-linux-distro-scanner.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-log.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-log-and-monitor-private.c
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-matcher.c
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-matcher-op.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-memcmp.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-cmd.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-opcode.c
@@ -680,8 +649,6 @@ set (MONGOC_SOURCES
 
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-crypto-openssl.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-rand-openssl.c
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-stream-tls-libressl.c
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-libressl.c
 
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-crypto-cng.c
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-rand-cng.c
@@ -747,11 +714,9 @@ set (HEADERS
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-handshake.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-host-list.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-init.h
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-index.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-iovec.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-log.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-macros.h
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-matcher.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-opcode.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-optional.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-prelude.h
@@ -762,7 +727,6 @@ set (HEADERS
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-client-session.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-sleep.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-socket.h
-   ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-stream-tls-libressl.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-stream-tls-openssl.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-stream.h
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-stream-buffered.h
@@ -780,10 +744,6 @@ set (HEADERS
    ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-bulkwrite.h
 )
 
-set (HEADERS_FORWARDING
-   ${PROJECT_SOURCE_DIR}/src/mongoc/forwarding/mongoc.h
-)
-
 configure_file (
    "${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-config.h.in"
    "${PROJECT_BINARY_DIR}/src/mongoc/mongoc-config.h"
@@ -794,13 +754,6 @@ configure_file (
    "${PROJECT_BINARY_DIR}/src/mongoc/mongoc-version.h"
 )
 
-if (ENABLE_APPLE_FRAMEWORK)
-   configure_file (
-      "${PROJECT_SOURCE_DIR}/src/mongoc/modules/module.modulemap.in"
-      "${PROJECT_BINARY_DIR}/src/mongoc/modules/module.modulemap"
-   )
-endif ()
-
 set (LIBRARIES
    ${SNAPPY_LIBRARIES} ${ZLIB_LIBRARIES} ${MONGOC_ZSTD_LIBRARIES} ${LIBMONGOCRYPT_LIBRARY}
 )
@@ -876,37 +829,32 @@ if (MONGOC_ENABLE_MONGODB_AWS_AUTH)
    endif()
 endif ()
 
-if (MONGOC_ENABLE_STATIC_BUILD)
+if (TARGET bson::static)
    add_library (mcd_rpc STATIC EXCLUDE_FROM_ALL ${PROJECT_SOURCE_DIR}/src/mongoc/mcd-rpc.c)
    target_include_directories (mcd_rpc PUBLIC ${PROJECT_SOURCE_DIR}/src)
-   target_link_libraries (mcd_rpc PUBLIC ${BSON_STATIC_LIBRARIES})
+   target_link_libraries (mcd_rpc PUBLIC bson::static)
    if (NOT WIN32 AND ENABLE_PIC)
       target_compile_options (mcd_rpc PUBLIC -fPIC)
    endif ()
-   target_compile_definitions (mcd_rpc PUBLIC ${BSON_STATIC_PUBLIC_DEFINITIONS})
    set_target_properties (mcd_rpc PROPERTIES OUTPUT_NAME "mcd-rpc")
 endif ()
 
-set_property(
-   SOURCE ${PROJECT_SOURCE_DIR}/src/mongoc/mongoc-cyrus.c
-   APPEND PROPERTY COMPILE_DEFINITIONS
-   "MONGOC_CYRUS_PLUGIN_PATH_PREFIX=$<IF:$<STREQUAL:${CYRUS_PLUGIN_PATH_PREFIX},>,NULL,\"${CYRUS_PLUGIN_PATH_PREFIX}\">"
-)
-
 set (
    UTHASH_INCLUDE_DIR
    "${mongo-c-driver_SOURCE_DIR}/src/uthash"
 )
 
 if (ENABLE_SHARED)
-   add_library (mongoc_shared SHARED ${SOURCES} ${HEADERS} ${HEADERS_FORWARDING})
+   add_library (mongoc_shared SHARED ${SOURCES} ${HEADERS})
+   add_library(mongoc::shared ALIAS mongoc_shared)
+   set_property(TARGET mongoc_shared PROPERTY EXPORT_NAME mongoc::shared)
    if(WIN32)
       # Add resource-definition script for Windows shared library (.dll).
       configure_file(libmongoc.rc.in libmongoc.rc)
       target_sources(mongoc_shared PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/libmongoc.rc)
    endif()
    set_target_properties (mongoc_shared PROPERTIES CMAKE_CXX_VISIBILITY_PRESET hidden)
-   target_link_libraries (mongoc_shared PRIVATE ${LIBRARIES} PUBLIC ${BSON_LIBRARIES} mongo::detail::c_dependencies)
+   target_link_libraries (mongoc_shared PRIVATE ${LIBRARIES} PUBLIC bson::shared mongo::detail::c_dependencies)
    target_include_directories (mongoc_shared PRIVATE ${ZLIB_INCLUDE_DIRS})
    target_include_directories (mongoc_shared PRIVATE ${UTF8PROC_INCLUDE_DIRS})
    target_include_directories (mongoc_shared PRIVATE ${LIBMONGOCRYPT_INCLUDE_DIRECTORIES})
@@ -944,27 +892,17 @@ if (ENABLE_SHARED)
    )
 
    set_target_properties (mongoc_shared PROPERTIES
-      OUTPUT_NAME "${MONGOC_OUTPUT_BASENAME}-${MONGOC_API_VERSION}"
-      VERSION 0.0.0
-      SOVERSION 0
-      pkg_config_REQUIRES "libbson-1.0"
-      )
-   mongo_generate_pkg_config(mongoc_shared INSTALL RENAME libmongoc-${MONGOC_API_VERSION}.pc)
-
-   if (ENABLE_APPLE_FRAMEWORK)
-      set_target_properties (mongoc_shared PROPERTIES
-         FRAMEWORK TRUE
-         MACOSX_FRAMEWORK_BUNDLE_VERSION ${MONGOC_VERSION}
-         MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MONGOC_VERSION}
-         MACOSX_FRAMEWORK_IDENTIFIER org.mongodb.mongoc
-         OUTPUT_NAME "${MONGOC_OUTPUT_BASENAME}"
-         PUBLIC_HEADER "${HEADERS}"
+      OUTPUT_NAME "${MONGOC_OUTPUT_BASENAME}${PROJECT_VERSION_MAJOR}"
+      VERSION "${PROJECT_VERSION}"
+      SOVERSION "${PROJECT_VERSION_MAJOR}"
+      pkg_config_REQUIRES "bson${PROJECT_VERSION_MAJOR}"
       )
-   endif () # ENABLE_APPLE_FRAMEWORK
+   mongo_generate_pkg_config(mongoc_shared INSTALL RENAME mongoc${PROJECT_VERSION_MAJOR}.pc)
 
    add_executable (mongoc-stat ${mongo-c-driver_SOURCE_DIR}/src/tools/mongoc-stat.c)
    target_compile_options (mongoc-stat PRIVATE ${mongoc-warning-options})
    target_link_libraries (mongoc-stat mongoc_shared ${LIBRARIES})
+   set_property (TARGET mongoc-stat PROPERTY OUTPUT_NAME mongoc${PROJECT_VERSION_MAJOR}-stat)
 
    # mongoc-stat works if shared memory performance counters are enabled.
    if (ENABLE_SHM_COUNTERS)
@@ -976,8 +914,10 @@ if (ENABLE_SHARED)
 endif () # ENABLE_SHARED
 
 if (MONGOC_ENABLE_STATIC_BUILD)
-   add_library (mongoc_static STATIC ${SOURCES} ${HEADERS} ${HEADERS_FORWARDING})
-   target_link_libraries (mongoc_static PUBLIC ${STATIC_LIBRARIES} ${BSON_STATIC_LIBRARIES} mongo::detail::c_dependencies)
+   add_library (mongoc_static STATIC ${SOURCES} ${HEADERS})
+   add_library(mongoc::static ALIAS mongoc_static)
+   set_property(TARGET mongoc_static PROPERTY EXPORT_NAME mongoc::static)
+   target_link_libraries (mongoc_static PUBLIC ${STATIC_LIBRARIES} bson::static mongo::detail::c_dependencies)
    if (NOT WIN32 AND ENABLE_PIC)
       target_compile_options (mongoc_static PUBLIC -fPIC)
       message (STATUS "Adding -fPIC to compilation of mongoc_static components")
@@ -1001,7 +941,6 @@ if (MONGOC_ENABLE_STATIC_BUILD)
    target_compile_definitions (mongoc_static
       PUBLIC
          MONGOC_STATIC
-         ${BSON_STATIC_PUBLIC_DEFINITIONS}
       PRIVATE
          MONGOC_COMPILATION
          ${KMS_MSG_DEFINITIONS}
@@ -1022,31 +961,28 @@ if (MONGOC_ENABLE_STATIC_BUILD)
          $<BUILD_INTERFACE:${mongo-c-driver_BINARY_DIR}/src/common/src>
    )
    set_target_properties (mongoc_static PROPERTIES
-      VERSION 0.0.0
-      OUTPUT_NAME "${MONGOC_OUTPUT_BASENAME}-static-${MONGOC_API_VERSION}"
-      pkg_config_REQUIRES "libbson-static-1.0"
+      VERSION "${PROJECT_VERSION}"
+      OUTPUT_NAME "${MONGOC_OUTPUT_BASENAME}${PROJECT_VERSION_MAJOR}"
+      pkg_config_REQUIRES "bson${PROJECT_VERSION_MAJOR}-static"
       )
    if(MONGOC_ENABLE_STATIC_INSTALL)
-      mongo_generate_pkg_config (mongoc_static FILENAME libmongoc-static-${MONGOC_API_VERSION}.pc INSTALL)
+      mongo_generate_pkg_config (mongoc_static FILENAME mongoc${PROJECT_VERSION_MAJOR}-static.pc INSTALL)
    endif()
 endif ()
 
 
 set (test-libmongoc-sources
    ${mongo-c-driver_SOURCE_DIR}/src/common/tests/test-common-atomic.c
-   ${mongo-c-driver_SOURCE_DIR}/src/common/tests/test-common-cmp.c
+   ${mongo-c-driver_SOURCE_DIR}/src/common/tests/test-mlib.c
    ${mongo-c-driver_SOURCE_DIR}/src/common/tests/test-common-oid.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/corpus-test.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/corpus-test.h
-   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-atomic.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-b64.c
-   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bcon-basic.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bcon-extract.c
-   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-cmp.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-corpus.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-error.c
-   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-sync.c
+   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-vector.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson-version.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-bson.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-clock.c
@@ -1059,6 +995,7 @@ set (test-libmongoc-sources
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-reader.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-string.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-utf8.c
+   ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-validate.generated.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-value.c
    ${mongo-c-driver_SOURCE_DIR}/src/libbson/tests/test-writer.c
    ${PROJECT_SOURCE_DIR}/tests/bsonutil/bson-match.c
@@ -1093,7 +1030,6 @@ set (test-libmongoc-sources
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-cluster.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-cmd.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-collection-find-with-opts.c
-   ${PROJECT_SOURCE_DIR}/tests/test-mongoc-collection-find.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-collection.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-command-logging-and-monitoring.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-command-monitoring.c
@@ -1119,7 +1055,6 @@ set (test-libmongoc-sources
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-loadbalanced.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-log.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-long-namespace.c
-   ${PROJECT_SOURCE_DIR}/tests/test-mongoc-matcher.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-max-staleness.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-mongohouse.c
    ${PROJECT_SOURCE_DIR}/tests/test-mongoc-mongos-pinning.c
@@ -1204,7 +1139,7 @@ if (ENABLE_TESTS)
       # Remove once support for VS 2013 is dropped.
       target_compile_options(test-libmongoc-lib PRIVATE /wd4756)
    endif ()
-   target_link_libraries (test-libmongoc-lib PUBLIC mongoc_static)
+   target_link_libraries (test-libmongoc-lib PUBLIC mongoc::static)
    # We have tests that test our deprecated api.
    target_compile_options (test-libmongoc-lib
       PRIVATE $<$<NOT:$<C_COMPILER_ID:MSVC>>:-Wno-deprecated-declarations>
@@ -1214,7 +1149,6 @@ if (ENABLE_TESTS)
    target_include_directories (test-libmongoc-lib
       PRIVATE
          ${PROJECT_SOURCE_DIR}/tests
-         ${BSON_STATIC_INCLUDE_DIRS}
          ${UTHASH_INCLUDE_DIR}
    )
    target_compile_definitions (test-libmongoc-lib
@@ -1242,7 +1176,6 @@ if (ENABLE_TESTS)
       target_include_directories (${test}
          PRIVATE
             ${PROJECT_SOURCE_DIR}/tests
-            ${BSON_STATIC_INCLUDE_DIRS}
       )
       target_compile_definitions (${test}
          PUBLIC
@@ -1279,9 +1212,9 @@ if (ENABLE_EXAMPLES AND ENABLE_SHARED)
       # Enable unconditional warnings-as-errors for our source code.
       target_compile_options (${example} PRIVATE ${mongoc-warning-options})
 
-      target_link_libraries (${example} mongoc_shared ${LIBRARIES})
+      target_link_libraries (${example} PRIVATE mongoc::shared ${LIBRARIES})
       if (WIN32)
-         target_link_libraries (${example} shlwapi)
+         target_link_libraries (${example} PRIVATE shlwapi)
       endif ()
    endfunction ()
 
@@ -1348,11 +1281,6 @@ if (ENABLE_EXAMPLES AND ENABLE_SHARED)
    # examples/tutorial
    mongoc_add_example (executing ${PROJECT_SOURCE_DIR}/examples/tutorial/executing.c)
    mongoc_add_example (appending ${PROJECT_SOURCE_DIR}/examples/tutorial/appending.c)
-   mongoc_add_example (migrating ${PROJECT_SOURCE_DIR}/examples/migrating.c)
-   # Ignore deprecation warnings in migrating examples. Migrating examples deliberately call deprecated API to show how to migrate.
-   target_compile_options (migrating
-      PRIVATE $<$<NOT:$<C_COMPILER_ID:MSVC>>:-Wno-deprecated-declarations>
-   )
 endif ()
 
 if (ENABLE_TESTS AND ENABLE_SHARED AND MONGOC_ENABLE_SSL AND NOT WIN32)
@@ -1360,7 +1288,7 @@ if (ENABLE_TESTS AND ENABLE_SHARED AND M
    # Benchmarks require SSL, and do not build on Windows.
    add_executable (benchmark-tls-pooled ${PROJECT_SOURCE_DIR}/tests/benchmark-tls-pooled.c)
    target_compile_options (benchmark-tls-pooled PRIVATE ${mongoc-warning-options})
-   target_link_libraries (benchmark-tls-pooled mongoc_shared ${LIBRARIES})
+   target_link_libraries (benchmark-tls-pooled PRIVATE mongoc::shared ${LIBRARIES})
 endif ()
 
 file (COPY ${PROJECT_SOURCE_DIR}/tests/binary DESTINATION ${PROJECT_BINARY_DIR}/tests)
@@ -1378,9 +1306,7 @@ if (ENABLE_SHARED)
    list (APPEND TARGETS_TO_INSTALL mongoc_shared)
 endif ()
 
-set (MONGOC_HEADER_INSTALL_DIR
-   "${CMAKE_INSTALL_INCLUDEDIR}/libmongoc-${MONGOC_API_VERSION}"
-)
+
 
 install (
    TARGETS ${TARGETS_TO_INSTALL}
@@ -1388,27 +1314,14 @@ install (
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
-   INCLUDES DESTINATION ${MONGOC_HEADER_INSTALL_DIR}
-   FRAMEWORK DESTINATION ${CMAKE_INSTALL_BINDIR}
+   INCLUDES DESTINATION ${MONGOC_INSTALL_INCLUDEDIR}
 )
 
 install (
    FILES ${HEADERS}
-   DESTINATION "${MONGOC_HEADER_INSTALL_DIR}/mongoc"
+   DESTINATION "${MONGOC_INSTALL_INCLUDEDIR}/mongoc"
 )
 
-install (
-   FILES ${HEADERS_FORWARDING}
-   DESTINATION "${MONGOC_HEADER_INSTALL_DIR}"
-)
-
-if (ENABLE_APPLE_FRAMEWORK)
-   install (
-      FILES "${PROJECT_BINARY_DIR}/src/mongoc/modules/module.modulemap"
-      DESTINATION "${CMAKE_INSTALL_BINDIR}/mongoc.framework/Modules/"
-   )
-endif ()
-
 # Collect link items for the static library to be inserted into the pkg-config
 if(TARGET mongoc_static)
    set(link_options ${ZLIB_LIBRARIES}
@@ -1426,69 +1339,36 @@ if(TARGET mongoc_static)
 endif()
 
 # Relative include-path will be given the install prefix:
-set_property(TARGET ${TARGETS_TO_INSTALL} APPEND PROPERTY pkg_config_INCLUDE_DIRECTORIES "${MONGOC_HEADER_INSTALL_DIR}")
-
-# Deprecated alias for libmongoc-1.0.pc, see CDRIVER-2086.
-if (MONGOC_ENABLE_SSL)
-   configure_file (
-      ${CMAKE_CURRENT_SOURCE_DIR}/src/libmongoc-ssl-1.0.pc.in
-      ${CMAKE_CURRENT_BINARY_DIR}/src/libmongoc-ssl-1.0.pc
-   @ONLY)
-   install (
-      FILES ${CMAKE_CURRENT_BINARY_DIR}/src/libmongoc-ssl-1.0.pc
-      DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
-   )
-endif ()
-
-include (CMakePackageConfigHelpers)
-
-write_basic_package_version_file (
-   "${CMAKE_CURRENT_BINARY_DIR}/mongoc/mongoc-${MONGOC_API_VERSION}-config-version.cmake"
-   VERSION ${MONGOC_VERSION}
-   COMPATIBILITY AnyNewerVersion
-)
-
-configure_file (src/mongoc-config.cmake
-   "${CMAKE_CURRENT_BINARY_DIR}/mongoc/mongoc-${MONGOC_API_VERSION}-config.cmake"
-   @ONLY
-)
+set_property(TARGET ${TARGETS_TO_INSTALL} APPEND PROPERTY pkg_config_INCLUDE_DIRECTORIES "${MONGOC_INSTALL_INCLUDEDIR}")
 
 install (EXPORT mongoc-targets
-   NAMESPACE mongo::
    FILE mongoc-targets.cmake
-   DESTINATION ${MONGOC_TARGETS_INSTALL_DIR}
+   DESTINATION "${MONGOC_INSTALL_CMAKEDIR}"
 )
 
-install (
-   FILES
-      "${CMAKE_CURRENT_BINARY_DIR}/mongoc/mongoc-${MONGOC_API_VERSION}-config.cmake"
-      "${CMAKE_CURRENT_BINARY_DIR}/mongoc/mongoc-${MONGOC_API_VERSION}-config-version.cmake"
-   DESTINATION
-      ${MONGOC_TARGETS_INSTALL_DIR}
-   COMPONENT
-      Devel
-)
-
-set(mongoc_cmake_prefix "${MONGO_C_DRIVER_INSTALL_CMAKEDIR}/mongoc-${PROJECT_VERSION}")
 configure_file(
    ${mongo-c-driver_SOURCE_DIR}/build/cmake/packageConfigVersion.cmake.in
    mongocConfigVersion.cmake
    @ONLY
 )
+configure_file(
+   etc/mongocConfig.cmake.in
+   mongocConfig.cmake
+   @ONLY
+)
 install(
-   FILES etc/mongocConfig.cmake "${CMAKE_CURRENT_BINARY_DIR}/mongocConfigVersion.cmake"
-   DESTINATION "${mongoc_cmake_prefix}"
+   FILES "${CMAKE_CURRENT_BINARY_DIR}/mongocConfig.cmake"
+         "${CMAKE_CURRENT_BINARY_DIR}/mongocConfigVersion.cmake"
+   DESTINATION "${MONGOC_INSTALL_CMAKEDIR}"
 )
 
-include (LegacyPackage)
-
-if (ENABLE_MAN_PAGES STREQUAL ON OR ENABLE_HTML_DOCS STREQUAL ON)
+if (ENABLE_MAN_PAGES OR ENABLE_HTML_DOCS)
    find_package (Sphinx REQUIRED)
    add_subdirectory (doc)
    add_custom_target (mongoc-doc
       ALL
       DEPENDS
-      $<$<STREQUAL:"${ENABLE_MAN_PAGES}","ON">:mongoc-man>
-      $<$<STREQUAL:"${ENABLE_HTML_DOCS}","ON">:mongoc-html>
+      $<TARGET_NAME_IF_EXISTS:mongoc-man>
+      $<TARGET_NAME_IF_EXISTS:mongoc-html>
    )
 endif ()
diff -pruN 1.30.4-1/src/libmongoc/doc/api.rst 2.0.2-1/src/libmongoc/doc/api.rst
--- 1.30.4-1/src/libmongoc/doc/api.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/api.rst	2025-06-19 15:42:22.000000000 +0000
@@ -30,7 +30,6 @@ API Reference
    mongoc_collection_t
    mongoc_cursor_t
    mongoc_database_t
-   mongoc_delete_flags_t
    mongoc_find_and_modify_opts_t
    mongoc_gridfs_file_list_t
    mongoc_gridfs_file_opt_t
@@ -38,9 +37,6 @@ API Reference
    mongoc_gridfs_bucket_t
    mongoc_gridfs_t
    mongoc_host_list_t
-   mongoc_index_opt_geo_t
-   mongoc_index_opt_t
-   mongoc_index_opt_wt_t
    mongoc_insert_flags_t
    mongoc_iovec_t
    mongoc_optional_t
@@ -50,7 +46,6 @@ API Reference
    mongoc_read_mode_t
    mongoc_read_prefs_t
    mongoc_remove_flags_t
-   mongoc_reply_flags_t
    mongoc_server_api_t
    mongoc_server_api_version_t
    mongoc_server_description_t
diff -pruN 1.30.4-1/src/libmongoc/doc/errors.rst 2.0.2-1/src/libmongoc/doc/errors.rst
--- 1.30.4-1/src/libmongoc/doc/errors.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/errors.rst	2025-06-19 15:42:22.000000000 +0000
@@ -35,6 +35,8 @@ Many C Driver functions report errors by
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 |                                         | ``MONGOC_ERROR_CLIENT_INVALID_LOAD_BALANCER``                                                                                    | You attempted to connect to a MongoDB server behind a load balancer, but the server does not advertize load balanced support.                                                                                                                                                                                            |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+|                                         | ``MONGOC_ERROR_CLIENT_NOT_READY``                                                                                                | You attempted to create a client but did not previously call :symbol:`mongoc_init`                                                                                                                                                                                                                                       |
++-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | ``MONGOC_ERROR_STREAM``                 | ``MONGOC_ERROR_STREAM_NAME_RESOLUTION``                                                                                          | DNS failure.                                                                                                                                                                                                                                                                                                             |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 |                                         | ``MONGOC_ERROR_STREAM_SOCKET``                                                                                                   | Timeout communicating with server, or connection closed.                                                                                                                                                                                                                                                                 |
@@ -55,7 +57,7 @@ Many C Driver functions report errors by
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | ``MONGOC_ERROR_SASL``                   | A SASL error code.                                                                                                               | ``man sasl_errors`` for a list of codes.                                                                                                                                                                                                                                                                                 |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| ``MONGOC_ERROR_BSON``                   | ``MONGOC_ERROR_BSON_INVALID``                                                                                                    | You passed an invalid or oversized BSON document as a parameter, or called :symbol:`mongoc_collection_create_index` with invalid keys, or the server reply was corrupt.                                                                                                                                                  |
+| ``MONGOC_ERROR_BSON``                   | ``MONGOC_ERROR_BSON_INVALID``                                                                                                    | You passed an invalid or oversized BSON document as a parameter or the server reply was corrupt.                                                                                                                                                                                                                         |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | ``MONGOC_ERROR_NAMESPACE``              | ``MONGOC_ERROR_NAMESPACE_INVALID``                                                                                               | You tried to create a collection with an invalid name.                                                                                                                                                                                                                                                                   |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -73,11 +75,11 @@ Many C Driver functions report errors by
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | ``MONGOC_ERROR_SERVER``                 | `Error code from server`_.                                                                                                       | :ref:`Error API Version 2 <error_api_version>`: Server error from a command. The server error message is in ``message``.                                                                                                                                                                                                 |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| ``MONGOC_ERROR_COLLECTION``             | ``MONGOC_ERROR_COLLECTION_INSERT_FAILED``, ``MONGOC_ERROR_COLLECTION_UPDATE_FAILED``, ``MONGOC_ERROR_COLLECTION_DELETE_FAILED``. | Invalid or empty input to :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_bulk`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`, :symbol:`mongoc_collection_delete_one`, or :symbol:`mongoc_collection_delete_many`. |
+| ``MONGOC_ERROR_COLLECTION``             | ``MONGOC_ERROR_COLLECTION_INSERT_FAILED``, ``MONGOC_ERROR_COLLECTION_UPDATE_FAILED``, ``MONGOC_ERROR_COLLECTION_DELETE_FAILED``. | Invalid or empty input to :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_many`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`, :symbol:`mongoc_collection_delete_one`, or :symbol:`mongoc_collection_delete_many`. |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| ``MONGOC_ERROR_COLLECTION``             | `Error code from server`_.                                                                                                       | :ref:`Error API Version 1 <error_api_version>`: Server error from :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_bulk`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`,                                             |
+| ``MONGOC_ERROR_COLLECTION``             | `Error code from server`_.                                                                                                       | :ref:`Error API Version 1 <error_api_version>`: Server error from :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_many`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`,                                             |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| ``MONGOC_ERROR_SERVER``                 | `Error code from server`_.                                                                                                       | :ref:`Error API Version 2 <error_api_version>`: Server error from :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_bulk`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`,                                             |
+| ``MONGOC_ERROR_SERVER``                 | `Error code from server`_.                                                                                                       | :ref:`Error API Version 2 <error_api_version>`: Server error from :symbol:`mongoc_collection_insert_one`, :symbol:`mongoc_collection_insert_many`, :symbol:`mongoc_collection_update_one`, :symbol:`mongoc_collection_update_many`, :symbol:`mongoc_collection_replace_one`,                                             |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | ``MONGOC_ERROR_GRIDFS``                 | ``MONGOC_ERROR_GRIDFS_CHUNK_MISSING``                                                                                            | The GridFS file is missing a document in its ``chunks`` collection.                                                                                                                                                                                                                                                      |
 +-----------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -158,12 +160,11 @@ To fix this flaw while preserving backwa
 | :symbol:`mongoc_database_command_with_opts`, and     |                                        |                                        |
 | other command functions                              |                                        |                                        |
 +------------------------------------------------------+----------------------------------------+----------------------------------------+
-| :symbol:`mongoc_collection_count_with_opts`          | ``MONGOC_ERROR_QUERY``                 | ``MONGOC_ERROR_SERVER``                |
-| :symbol:`mongoc_client_get_database_names_with_opts`,|                                        |                                        |
+| :symbol:`mongoc_client_get_database_names_with_opts` | ``MONGOC_ERROR_QUERY``                 | ``MONGOC_ERROR_SERVER``                |
 | and other command helper functions                   |                                        |                                        |
 +------------------------------------------------------+----------------------------------------+----------------------------------------+
 | :symbol:`mongoc_collection_insert_one`               | ``MONGOC_ERROR_COMMAND``               | ``MONGOC_ERROR_SERVER``                |
-| :symbol:`mongoc_collection_insert_bulk`              |                                        |                                        |
+| :symbol:`mongoc_collection_insert_many`              |                                        |                                        |
 | :symbol:`mongoc_collection_update_one`               |                                        |                                        |
 | :symbol:`mongoc_collection_update_many`              |                                        |                                        |
 | :symbol:`mongoc_collection_replace_one`              |                                        |                                        |
diff -pruN 1.30.4-1/src/libmongoc/doc/includes/change-stream-opts.txt 2.0.2-1/src/libmongoc/doc/includes/change-stream-opts.txt
--- 1.30.4-1/src/libmongoc/doc/includes/change-stream-opts.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/includes/change-stream-opts.txt	2025-06-19 15:42:22.000000000 +0000
@@ -3,9 +3,11 @@
    Generated with build/generate-opts.py
    DO NOT EDIT THIS FILE
 
+.. versionchanged:: 2.0.0 ``batchSize`` of 0 is applied to the ``aggregate`` command. 0 was previously ignored.
+
 ``opts`` may be NULL or a BSON document with additional command options:
 
-* ``batchSize``: An ``int32`` representing number of documents requested to be returned on each call to :symbol:`mongoc_change_stream_next`
+* ``batchSize``: An ``int32`` requesting a limit of documents returned in each server reply. If positive, the ``batchSize`` is applied to both ``aggregate`` and ``getMore`` commands. If 0, the ``batchSize`` is only applied to the ``aggregate`` command (Useful to request an immediate cursor without significant server-side work. See `Aggregate Data Specifying Batch Size <https://www.mongodb.com/docs/manual/reference/command/aggregate/#aggregate-data-specifying-batch-size>`_). If omitted or negative, the value is ignored and server defaults are used (See `Cursor Batches <https://www.mongodb.com/docs/manual/core/cursors/#cursor-batches>`_ for a description of server defaults).
 * ``resumeAfter``: A ``Document`` representing the logical starting point of the change stream. The result of :symbol:`mongoc_change_stream_get_resume_token()` or the ``_id`` field  of any change received from a change stream can be used here. This option is mutually exclusive with ``startAfter`` and ``startAtOperationTime``.
 * ``startAfter``: A ``Document`` representing the logical starting point of the change stream. Unlike ``resumeAfter``, this can resume notifications after an "invalidate" event. The result of :symbol:`mongoc_change_stream_get_resume_token()` or the ``_id`` field  of any change received from a change stream can be used here.  This option is mutually exclusive with ``resumeAfter`` and ``startAtOperationTime``.
 * ``startAtOperationTime``: A ``Timestamp``. The change stream only provides changes that occurred at or after the specified timestamp. Any command run against the server will return an operation time that can be used here. This option is mutually exclusive with ``resumeAfter`` and ``startAfter``.
Binary files 1.30.4-1/src/libmongoc/doc/includes/libbson.inv and 2.0.2-1/src/libmongoc/doc/includes/libbson.inv differ
diff -pruN 1.30.4-1/src/libmongoc/doc/init-cleanup.rst 2.0.2-1/src/libmongoc/doc/init-cleanup.rst
--- 1.30.4-1/src/libmongoc/doc/init-cleanup.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/init-cleanup.rst	2025-06-19 15:42:22.000000000 +0000
@@ -17,13 +17,4 @@ Synopsis
     mongoc_init
     mongoc_cleanup
 
-Deprecated feature: automatic initialization and cleanup
---------------------------------------------------------
-
-On some platforms the driver can automatically call :symbol:`mongoc_init` before ``main``, and call :symbol:`mongoc_cleanup` as the process exits. This is problematic in situations where related libraries also execute cleanup code on shutdown, and it creates inconsistent rules across platforms. Therefore the automatic initialization and cleanup feature is deprecated, and will be dropped in version 2.0. Meanwhile, for backward compatibility, the feature is *enabled* by default on platforms where it is available.
-
-For portable, future-proof code, always call :symbol:`mongoc_init` and :symbol:`mongoc_cleanup` yourself, and configure the driver like:
-
-.. code-block:: none
-
-  cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF
+.. versionchanged:: 2.0.0 Versions prior to 2.0.0 supported a non-portable automatic initialization and cleanup with the CMake option ``ENABLE_AUTOMATIC_INIT_AND_CLEANUP``. This was removed in 2.0.0. Ensure your application call :symbol:`mongoc_init` and :symbol:`mongoc_cleanup`.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_failed_get_server_connection_id.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_failed_get_server_connection_id.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_failed_get_server_connection_id.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_failed_get_server_connection_id.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,40 +0,0 @@
-:man_page: mongoc_apm_command_failed_get_server_connection_id
-
-mongoc_apm_command_failed_get_server_connection_id()
-====================================================
-
-.. warning::
-   .. deprecated:: 1.24.0
-
-      Use :symbol:`mongoc_apm_command_failed_get_server_connection_id_int64()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  int32_t
-  mongoc_apm_command_failed_get_server_connection_id (
-    const mongoc_apm_command_failed_t *event);
-
-Returns this event's context.
-
-Returns the server connection ID for the command. The server connection ID is
-distinct from the server ID (:symbol:`mongoc_apm_command_failed_get_server_id`)
-and is returned by the hello or legacy hello response as "connectionId" from the
-server on 4.2+.
-
-Parameters
-----------
-
-* ``event``: A :symbol:`mongoc_apm_command_failed_t`.
-
-Returns
--------
-
-The server connection ID as a positive integer or -1 if it is not available.
-
-.. seealso::
-
-  | :doc:`Introduction to Application Performance Monitoring <application-performance-monitoring>`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_failed_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_failed_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_failed_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_failed_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -30,7 +30,6 @@ An event notification sent when the driv
     mongoc_apm_command_failed_get_request_id
     mongoc_apm_command_failed_get_server_id
     mongoc_apm_command_failed_get_service_id
-    mongoc_apm_command_failed_get_server_connection_id
     mongoc_apm_command_failed_get_server_connection_id_int64
 
 .. seealso::
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_started_get_server_connection_id.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_started_get_server_connection_id.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_started_get_server_connection_id.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_started_get_server_connection_id.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-:man_page: mongoc_apm_command_started_get_server_connection_id
-
-mongoc_apm_command_started_get_server_connection_id()
-=====================================================
-
-.. warning::
-   .. deprecated:: 1.24.0
-
-      Use :symbol:`mongoc_apm_command_started_get_server_connection_id_int64()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  int32_t
-  mongoc_apm_command_started_get_server_connection_id (
-    const mongoc_apm_command_started_t *event);
-
-Returns the server connection ID for the command. The server connection ID is
-distinct from the server ID (:symbol:`mongoc_apm_command_started_get_server_id`)
-and is returned by the hello or legacy hello response as "connectionId" from the
-server on 4.2+.
-
-Parameters
-----------
-
-* ``event``: A :symbol:`mongoc_apm_command_started_t`.
-
-Returns
--------
-
-The server connection ID as a positive integer or -1 if it is not available.
-
-.. seealso::
-
-  | :doc:`Introduction to Application Performance Monitoring <application-performance-monitoring>`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_started_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_started_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_started_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_started_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -32,6 +32,5 @@ An event notification sent when the driv
     mongoc_apm_command_started_get_request_id
     mongoc_apm_command_started_get_server_id
     mongoc_apm_command_started_get_service_id
-    mongoc_apm_command_started_get_server_connection_id
     mongoc_apm_command_started_get_server_connection_id_int64
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_succeeded_get_server_connection_id.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_succeeded_get_server_connection_id.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_succeeded_get_server_connection_id.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_succeeded_get_server_connection_id.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-:man_page: mongoc_apm_command_succeeded_get_server_connection_id
-
-mongoc_apm_command_succeeded_get_server_connection_id()
-=======================================================
-
-.. warning::
-   .. deprecated:: 1.24.0
-
-      Use :symbol:`mongoc_apm_command_succeeded_get_server_connection_id_int64()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  int32_t
-  mongoc_apm_command_succeeded_get_server_connection_id (
-    const mongoc_apm_command_succeeded_t *event);
-
-Returns the server connection ID for the command. The server connection ID is
-distinct from the server ID
-(:symbol:`mongoc_apm_command_succeeded_get_server_id`) and is returned by the
-hello or legacy hello response as "connectionId" from the server on 4.2+.
-
-Parameters
-----------
-
-* ``event``: A :symbol:`mongoc_apm_command_succeeded_t`.
-
-Returns
--------
-
-The server connection ID as a positive integer or -1 if it is not available.
-
-.. seealso::
-
-  | :doc:`Introduction to Application Performance Monitoring <application-performance-monitoring>`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_succeeded_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_succeeded_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_apm_command_succeeded_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_apm_command_succeeded_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -33,6 +33,5 @@ An event notification sent when the driv
     mongoc_apm_command_succeeded_get_request_id
     mongoc_apm_command_succeeded_get_server_id
     mongoc_apm_command_succeeded_get_service_id
-    mongoc_apm_command_succeeded_get_server_connection_id
     mongoc_apm_command_succeeded_get_server_connection_id_int64
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_delete.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_delete.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_delete.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_delete.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-:man_page: mongoc_bulk_operation_delete
-
-mongoc_bulk_operation_delete()
-==============================
-
-.. warning::
-   .. deprecated:: 0.96.0
-
-   Use :symbol:`mongoc_bulk_operation_remove()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk,
-                                const bson_t *selector);
-
-Deletes documents as part of a bulk operation. This only queues the operation. To execute it, call :symbol:`mongoc_bulk_operation_execute()`.
-
-Parameters
-----------
-
-* ``bulk``: A :symbol:`mongoc_bulk_operation_t`.
-* ``selector``: A :symbol:`bson:bson_t`.
-
-Errors
-------
-
-Errors are propagated via :symbol:`mongoc_bulk_operation_execute()`.
-
-.. seealso::
-
-  | :symbol:`mongoc_bulk_operation_remove_many_with_opts()`
-
-  | :symbol:`mongoc_bulk_operation_remove_one_with_opts()`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_delete_one.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_delete_one.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_delete_one.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_delete_one.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-:man_page: mongoc_bulk_operation_delete_one
-
-mongoc_bulk_operation_delete_one()
-==================================
-
-.. warning::
-   .. deprecated:: 0.96.0
-
-      Use :symbol:`mongoc_bulk_operation_remove_one()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk,
-                                    const bson_t *selector);
-
-Delete a single document as part of a bulk operation. This only queues the operation. To execute it, call :symbol:`mongoc_bulk_operation_execute()`.
-
-Parameters
-----------
-
-* ``bulk``: A :symbol:`mongoc_bulk_operation_t`.
-* ``selector``: A :symbol:`bson:bson_t`.
-
-Errors
-------
-
-Errors are propagated via :symbol:`mongoc_bulk_operation_execute()`.
-
-.. seealso::
-
-  | :symbol:`mongoc_bulk_operation_remove_one_with_opts()`
-
-  | :symbol:`mongoc_bulk_operation_remove_many_with_opts()`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_execute.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_execute.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_execute.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_execute.rst	2025-06-19 15:42:22.000000000 +0000
@@ -15,7 +15,9 @@ Synopsis
 
 This function executes all operations queued into the bulk operation. Unless ``ordered: false`` was specified in the ``opts`` passed to :symbol:`mongoc_collection_create_bulk_operation_with_opts()`, then forward progress will be stopped upon the first error.
 
-It is only valid to call :symbol:`mongoc_bulk_operation_execute()` once. The ``mongoc_bulk_operation_t`` must be destroyed afterwards.
+It is only valid to call :symbol:`mongoc_bulk_operation_execute()` once on the same :symbol:`mongoc_bulk_operation_t`. Calling repeatedly results in error. Call :symbol:`mongoc_bulk_operation_destroy` to destroy ``bulk`` afterwards.
+
+.. versionchanged:: 2.0.0 Calling :symbol:`mongoc_bulk_operation_execute()` repeatedly results in an error.
 
 .. warning::
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_get_hint.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_get_hint.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_get_hint.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_get_hint.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,32 +0,0 @@
-:man_page: mongoc_bulk_operation_get_hint
-
-mongoc_bulk_operation_get_hint()
-================================
-
-.. warning::
-   .. deprecated:: 1.28.0
-
-      Use :symbol:`mongoc_bulk_operation_get_server_id()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  uint32_t
-  mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk);
-
-Parameters
-----------
-
-* ``bulk``: A :symbol:`mongoc_bulk_operation_t`.
-
-Description
------------
-
-Retrieves the opaque id of the server used for the operation.
-
-(The function name includes the old term "hint" for the sake of backward compatibility, but we now call this number a "server id".)
-
-This number is zero until the driver actually uses a server in :symbol:`mongoc_bulk_operation_execute`. The server id is the same number as the return value of a successful :symbol:`mongoc_bulk_operation_execute`, so ``mongoc_bulk_operation_get_hint`` is useful mainly in case :symbol:`mongoc_bulk_operation_execute` fails and returns zero.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_set_hint.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_set_hint.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_set_hint.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_set_hint.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,33 +0,0 @@
-:man_page: mongoc_bulk_operation_set_hint
-
-mongoc_bulk_operation_set_hint()
-================================
-
-.. warning::
-   .. deprecated:: 1.28.0
-
-      Use :symbol:`mongoc_bulk_operation_set_server_id()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id);
-
-Parameters
-----------
-
-* ``bulk``: A :symbol:`mongoc_bulk_operation_t`.
-* ``server_id``: An opaque id identifying the server to use.
-
-Description
------------
-
-Specifies which server to use for the operation. This function has an effect only if called before :symbol:`mongoc_bulk_operation_execute`.
-
-(The function name includes the old term "hint" for the sake of backward compatibility, but we now call this number a "server id".)
-
-Use ``mongoc_bulk_operation_set_hint`` only for building a language driver that wraps the C Driver. When writing applications in C, leave the server id unset and allow the driver to choose a suitable server for the bulk operation.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_bulk_operation_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_bulk_operation_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -42,11 +42,8 @@ After adding all of the write operations
     :titlesonly:
     :maxdepth: 1
 
-    mongoc_bulk_operation_delete
-    mongoc_bulk_operation_delete_one
     mongoc_bulk_operation_destroy
     mongoc_bulk_operation_execute
-    mongoc_bulk_operation_get_hint
     mongoc_bulk_operation_get_server_id
     mongoc_bulk_operation_get_write_concern
     mongoc_bulk_operation_insert
@@ -60,7 +57,6 @@ After adding all of the write operations
     mongoc_bulk_operation_set_bypass_document_validation
     mongoc_bulk_operation_set_client_session
     mongoc_bulk_operation_set_comment
-    mongoc_bulk_operation_set_hint
     mongoc_bulk_operation_set_server_id
     mongoc_bulk_operation_set_let
     mongoc_bulk_operation_update
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_command.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_command.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_command.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_command.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,79 +0,0 @@
-:man_page: mongoc_client_command
-
-mongoc_client_command()
-=======================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-      This function is deprecated and should not be used in new code.
-      Use :symbol:`mongoc_client_command_simple()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_client_command (mongoc_client_t *client,
-                         const char *db_name,
-                         mongoc_query_flags_t flags,
-                         uint32_t skip,
-                         uint32_t limit,
-                         uint32_t batch_size,
-                         const bson_t *query,
-                         const bson_t *fields,
-                         const mongoc_read_prefs_t *read_prefs);
-
-.. include:: includes/not-retryable-read.txt
-
-Description
------------
-
-This function creates a cursor which will execute the command when :symbol:`mongoc_cursor_next` is called on it. The client's read preference, read concern, and write concern are not applied to the command, and :symbol:`mongoc_cursor_next` will not check the server response for a write concern error or write concern timeout.
-
-If :symbol:`mongoc_cursor_next()` returns ``false``, then retrieve error details with :symbol:`mongoc_cursor_error()` or :symbol:`mongoc_cursor_error_document()`.
-
-Parameters
-----------
-
-* ``client``: A :symbol:`mongoc_client_t`.
-* ``db_name``: The name of the database to run the command on.
-* ``flags``: Unused.
-* ``skip``: Unused.
-* ``limit``: Unused.
-* ``batch_size``: Unused.
-* ``query``: A :symbol:`bson:bson_t` containing the command specification.
-* ``fields``: Unused.
-* ``read_prefs``: An optional :symbol:`mongoc_read_prefs_t`. Otherwise, the command uses mode ``MONGOC_READ_PRIMARY``.
-
-Migrating
----------
-
-:symbol:`mongoc_client_command` is deprecated.
-
-The following example uses :symbol:`mongoc_client_command`:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_client_command ... before ... begin
-   :end-before:  // mongoc_client_command ... before ... end
-   :caption: Before
-
-The above code block may be rewritten to use :symbol:`mongoc_client_command_simple` instead, as shown below:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_client_command ... after ... begin
-   :end-before:  // mongoc_client_command ... after ... end
-   :caption: After
-
-Returns
--------
-
-A :symbol:`mongoc_cursor_t`.
-
-The cursor should be freed with :symbol:`mongoc_cursor_destroy()`.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_command_simple.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_command_simple.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_command_simple.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_command_simple.rst	2025-06-19 15:42:22.000000000 +0000
@@ -16,7 +16,7 @@ Synopsis
                                 bson_t *reply,
                                 bson_error_t *error);
 
-This is a simplified interface to :symbol:`mongoc_client_command()`. It returns the first document from the result cursor into ``reply``. The client's read preference, read concern, and write concern are not applied to the command.
+The client's read preference, read concern, and write concern are not applied to the command.
 
 .. warning::
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_get_server_status.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_get_server_status.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_get_server_status.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_get_server_status.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,43 +0,0 @@
-:man_page: mongoc_client_get_server_status
-
-mongoc_client_get_server_status()
-=================================
-
-.. warning::
-   .. deprecated:: 1.10.0
-
-      Run the `serverStatus <https://www.mongodb.com/docs/manual/reference/command/serverStatus/>`_ command directly with :symbol:`mongoc_client_read_command_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_client_get_server_status (mongoc_client_t *client,
-                                   mongoc_read_prefs_t *read_prefs,
-                                   bson_t *reply,
-                                   bson_error_t *error);
-
-Queries the server for the current server status. The result is stored in ``reply``.
-
-``reply`` is always initialized, even in the case of failure. Always call :symbol:`bson:bson_destroy()` to release it.
-
-Parameters
-----------
-
-* ``client``: A :symbol:`mongoc_client_t`.
-* ``read_prefs``: A :symbol:`mongoc_read_prefs_t`.
-* ``reply``: A |bson_t-opt-storage-ptr| to contain the results.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_pool_min_size.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_pool_min_size.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_pool_min_size.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_pool_min_size.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,32 +0,0 @@
-:man_page: mongoc_client_pool_min_size
-
-mongoc_client_pool_min_size()
-=============================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      This function is deprecated because its behavior does not match what developers expect from a "minimum pool size", and its actual behavior is likely to hurt performance.
-
-      Applications should not call this function, they should instead accept the default behavior, which is to keep all idle clients that are pushed into the pool.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_client_pool_min_size (mongoc_client_pool_t *pool,
-                               uint32_t min_pool_size);
-
-This function sets the *maximum* number of idle clients to be kept in the pool. Any idle clients in excess of the maximum are destroyed.
-
-Parameters
-----------
-
-* ``pool``: A :symbol:`mongoc_client_pool_t`.
-* ``min_pool_size``: The number of idle clients to keep in the pool.
-
-.. include:: includes/mongoc_client_pool_thread_safe.txt
-
-Subsequent calls to :symbol:`mongoc_client_pool_push` respect the new minimum size, and close the least recently used :symbol:`mongoc_client_t` if the minimum size is exceeded.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_pool_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_pool_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_pool_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_pool_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -33,7 +33,6 @@ Example
     mongoc_client_pool_destroy
     mongoc_client_pool_enable_auto_encryption
     mongoc_client_pool_max_size
-    mongoc_client_pool_min_size
     mongoc_client_pool_new
     mongoc_client_pool_new_with_error
     mongoc_client_pool_pop
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_set_ssl_opts.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_set_ssl_opts.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_set_ssl_opts.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_set_ssl_opts.rst	2025-06-19 15:42:22.000000000 +0000
@@ -32,6 +32,8 @@ It is a programming error to call this f
 :symbol:`mongoc_client_pool_set_ssl_opts` on the pool before popping any
 clients.
 
+.. versionchanged:: 2.0.0 This function logs an error and immediately returns if ``client`` is from a :symbol:`mongoc_client_pool_t`. Previously this function unsafely applied the options to the pooled client.
+
 Parameters
 ----------
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_set_stream_initiator.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_set_stream_initiator.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_set_stream_initiator.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_set_stream_initiator.rst	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,10 @@ Synopsis
 
 The :symbol:`mongoc_client_set_stream_initiator()` function shall associate a given :symbol:`mongoc_client_t` with a new stream initiator. This will completely replace the default transport (buffered TCP, possibly with TLS). The ``initiator`` should fulfill the :symbol:`mongoc_stream_t` contract. ``user_data`` is passed through to the ``initiator`` callback and may be used for whatever run time customization is necessary.
 
+It is a programming error to call this function on a :symbol:`mongoc_client_t` from a :symbol:`mongoc_client_pool_t`.
+
+.. versionchanged:: 2.0.0 This function logs an error and immediately returns if ``client`` is from a :symbol:`mongoc_client_pool_t`. Previously this function unsafely applied the initiator to the pooled client.
+
 If ``user_data`` is passed, it is the application's responsibility to ensure ``user_data`` remains valid for the lifetime of the client.
 
 Parameters
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_client_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_client_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_client_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_client_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -53,7 +53,6 @@ Example
     :maxdepth: 1
 
     mongoc_client_bulkwrite_new
-    mongoc_client_command
     mongoc_client_command_simple
     mongoc_client_command_simple_with_server_id
     mongoc_client_command_with_opts
@@ -72,7 +71,6 @@ Example
     mongoc_client_get_read_prefs
     mongoc_client_get_server_description
     mongoc_client_get_server_descriptions
-    mongoc_client_get_server_status
     mongoc_client_get_uri
     mongoc_client_get_write_concern
     mongoc_client_new
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_command.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_command.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_command.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_command.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,67 +0,0 @@
-:man_page: mongoc_collection_command
-
-mongoc_collection_command()
-===========================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-      This function is deprecated and should not be used in new code.
-      Use :symbol:`mongoc_collection_command_simple()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_collection_command (mongoc_collection_t *collection,
-                             mongoc_query_flags_t flags,
-                             uint32_t skip,
-                             uint32_t limit,
-                             uint32_t batch_size,
-                             const bson_t *command,
-                             const bson_t *fields,
-                             const mongoc_read_prefs_t *read_prefs);
-
-.. include:: includes/not-retryable-read.txt
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: Unused.
-* ``skip``: Unused.
-* ``limit``: Unused.
-* ``batch_size``: Unused.
-* ``command``: A :symbol:`bson:bson_t` containing the command to execute.
-* ``fields``: Unused.
-* ``read_prefs``: An optional :symbol:`mongoc_read_prefs_t`. Otherwise, the command uses mode ``MONGOC_READ_PRIMARY``.
-
-Migrating
----------
-
-:symbol:`mongoc_collection_command` is deprecated.
-
-The following example uses :symbol:`mongoc_collection_command`:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_collection_command ... before ... begin
-   :end-before:  // mongoc_collection_command ... before ... end
-   :caption: Before
-
-The above code block may be rewritten to use :symbol:`mongoc_collection_command_simple` instead, as shown below:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_collection_command ... after ... begin
-   :end-before:  // mongoc_collection_command ... after ... end
-   :caption: After
-
-Returns
--------
-
-.. include:: includes/returns-cursor.txt
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_command_simple.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_command_simple.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_command_simple.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_command_simple.rst	2025-06-19 15:42:22.000000000 +0000
@@ -27,7 +27,7 @@ Parameters
 Description
 -----------
 
-This is a simplified version of :symbol:`mongoc_collection_command()` that returns the first result document in ``reply``. The collection's read preference, read concern, and write concern are not applied to the command. The parameter ``reply`` is initialized even upon failure to simplify memory management.
+The collection's read preference, read concern, and write concern are not applied to the command. The parameter ``reply`` is initialized even upon failure to simplify memory management.
 
 This function tries to unwrap an embedded error in the command when possible. The unwrapped error will be propagated via the ``error`` parameter. Additionally, the result document is set in ``reply``.
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_count.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_count.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_count.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_count.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,85 +0,0 @@
-:man_page: mongoc_collection_count
-
-mongoc_collection_count()
-=========================
-
-.. warning::
-   .. deprecated:: 1.11.0
-
-      Use :symbol:`mongoc_collection_count_documents` or :symbol:`mongoc_collection_estimated_document_count` instead.
-
-      :symbol:`mongoc_collection_count_documents` has similar performance to calling :symbol:`mongoc_collection_count` with a non-NULL ``query``, and is guaranteed to retrieve an accurate collection count. See :ref:`migrating from deprecated count functions <migrating-from-deprecated-count>` for details.
-
-      :symbol:`mongoc_collection_estimated_document_count` has the same performance as calling :symbol:`mongoc_collection_count` with a NULL ``query``, but is not guaranteed to retrieve an accurate collection count.
-
-.. include:: includes/retryable-read.txt
-
-Synopsis
---------
-
-.. code-block:: c
-
-  int64_t
-  mongoc_collection_count (mongoc_collection_t *collection,
-                           mongoc_query_flags_t flags,
-                           const bson_t *query,
-                           int64_t skip,
-                           int64_t limit,
-                           const mongoc_read_prefs_t *read_prefs,
-                           bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: A :symbol:`mongoc_query_flags_t`.
-* ``query``: A :symbol:`bson:bson_t` containing the query.
-* ``skip``: A int64_t, zero to ignore.
-* ``limit``: A int64_t, zero to ignore.
-* ``read_prefs``: A :symbol:`mongoc_read_prefs_t` or ``NULL``.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function shall execute a count query on the underlying 'collection'. The bson 'query' is not validated, simply passed along as appropriate to the server.  As such, compatibility and errors should be validated in the appropriate server documentation.
-
-For more information, see the `query reference <https://www.mongodb.com/docs/manual/reference/operator/query/>`_ at the MongoDB website.
-
-The :symbol:`mongoc_read_concern_t` specified on the :symbol:`mongoc_collection_t` will be used, if any. If ``read_prefs`` is NULL, the collection's read preferences are used.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
--1 on failure, otherwise the number of documents counted.
-
-Example
--------
-
-.. code-block:: c
-
-  #include <bson/bson.h>
-  #include <mongoc/mongoc.h>
-  #include <stdio.h>
-
-  static void
-  print_query_count (mongoc_collection_t *collection, bson_t *query)
-  {
-     bson_error_t error;
-     int64_t count;
-
-     count = mongoc_collection_count (
-        collection, MONGOC_QUERY_NONE, query, 0, 0, NULL, &error);
-
-     if (count < 0) {
-        fprintf (stderr, "Count failed: %s\n", error.message);
-     } else {
-        printf ("%" PRId64 " documents counted.\n", count);
-     }
-  }
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_count_documents.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_count_documents.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_count_documents.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_count_documents.rst	2025-06-19 15:42:22.000000000 +0000
@@ -76,29 +76,6 @@ Example
      }
   }
 
-.. _migrating-from-deprecated-count:
-
-Migrating from deprecated count functions
------------------------------------------
-
-When migrating to :symbol:`mongoc_collection_count_documents` from the deprecated :symbol:`mongoc_collection_count` or :symbol:`mongoc_collection_count_with_opts`, the following query operators in the filter must be replaced:
-
-+-------------+-------------------------------------+
-| Operator    | Replacement                         |
-+=============+=====================================+
-| $where      | `$expr`_                            |
-+-------------+-------------------------------------+
-| $near       | `$geoWithin`_ with `$center`_       |
-+-------------+-------------------------------------+
-| $nearSphere | `$geoWithin`_ with `$centerSphere`_ |
-+-------------+-------------------------------------+
-
-$expr requires MongoDB 3.6+
-
-.. _$expr: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
-.. _$geoWithin: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
-.. _$center: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
-.. _$centerSphere: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
 
 .. seealso::
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_count_with_opts.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_count_with_opts.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_count_with_opts.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_count_with_opts.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,139 +0,0 @@
-:man_page: mongoc_collection_count_with_opts
-
-mongoc_collection_count_with_opts()
-===================================
-
-.. warning::
-   .. deprecated:: 1.11.0
-
-      Use :symbol:`mongoc_collection_count_documents` or :symbol:`mongoc_collection_estimated_document_count` instead.
-
-      :symbol:`mongoc_collection_count_documents` has similar performance to calling :symbol:`mongoc_collection_count` with a non-NULL ``query``, and is guaranteed to retrieve an accurate collection count. See :ref:`migrating from deprecated count functions <migrating-from-deprecated-count>` for details.
-
-      :symbol:`mongoc_collection_estimated_document_count` has the same performance as calling :symbol:`mongoc_collection_count` with a NULL ``query``, but is not guaranteed to retrieve an accurate collection count.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  int64_t
-  mongoc_collection_count_with_opts (mongoc_collection_t *collection,
-                                     mongoc_query_flags_t flags,
-                                     const bson_t *query,
-                                     int64_t skip,
-                                     int64_t limit,
-                                     const bson_t *opts,
-                                     const mongoc_read_prefs_t *read_prefs,
-                                     bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: A :symbol:`mongoc_query_flags_t`.
-* ``query``: A :symbol:`bson:bson_t` containing the query.
-* ``skip``: A int64_t, zero to ignore.
-* ``limit``: A int64_t, zero to ignore.
-* ``opts``: A :symbol:`bson:bson_t`, ``NULL`` to ignore.
-* ``read_prefs``: An optional :symbol:`mongoc_read_prefs_t`, otherwise uses the collection's read preference.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-.. |opts-source| replace:: ``collection``
-
-.. include:: includes/read-opts.txt
-
-Description
------------
-
-This function shall execute a count query on the underlying 'collection'. The bson 'query' is not validated, simply passed along as appropriate to the server.  As such, compatibility and errors should be validated in the appropriate server documentation.
-
-The :symbol:`mongoc_read_concern_t` specified on the :symbol:`mongoc_collection_t` will be used, if any. If ``read_prefs`` is NULL, the collection's read preferences are used.
-
-In addition to the standard functionality available from mongoc_collection_count, this function allows the user to add arbitrary extra keys to the count.  This pass through enables features such as hinting for counts.
-
-For more information, see the `query reference <https://www.mongodb.com/docs/manual/reference/operator/query/>`_ at the MongoDB website.
-
-.. include:: includes/retryable-read.txt
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
--1 on failure, otherwise the number of documents counted.
-
-Examples
---------
-
-.. code-block:: c
-  :caption: Basic Counting
-
-  #include <bson/bson.h>
-  #include <mongoc/mongoc.h>
-  #include <stdio.h>
-
-  static void
-  print_query_count (mongoc_collection_t *collection, bson_t *query)
-  {
-     bson_error_t error;
-     int64_t count;
-     bson_t opts;
-
-     bson_init (&opts);
-     BSON_APPEND_UTF8 (&opts, "hint", "_id_");
-
-     count = mongoc_collection_count_with_opts (
-        collection, MONGOC_QUERY_NONE, query, 0, 0, &opts, NULL, &error);
-
-     bson_destroy (&opts);
-
-     if (count < 0) {
-        fprintf (stderr, "Count failed: %s\n", error.message);
-     } else {
-        printf ("%" PRId64 " documents counted.\n", count);
-     }
-  }
-
-.. code-block:: c
-  :caption: Counting with Collation
-
-  #include <bson/bson.h>
-  #include <mongoc/mongoc.h>
-  #include <stdio.h>
-
-  static void
-  print_query_count (mongoc_collection_t *collection, bson_t *query)
-  {
-     bson_t *selector;
-     bson_t *opts;
-     bson_error_t error;
-     int64_t count;
-
-     selector = BCON_NEW ("_id", "{", "$gt", BCON_UTF8 ("one"), "}");
-
-     /* "One" normally sorts before "one"; make "one" come first */
-     opts = BCON_NEW ("collation",
-                      "{",
-                      "locale",
-                      BCON_UTF8 ("en_US"),
-                      "caseFirst",
-                      BCON_UTF8 ("lower"),
-                      "}");
-
-     count = mongoc_collection_count_with_opts (
-        collection, MONGOC_QUERY_NONE, query, 0, 0, opts, NULL, &error);
-
-     bson_destroy (selector);
-     bson_destroy (opts);
-
-     if (count < 0) {
-        fprintf (stderr, "Count failed: %s\n", error.message);
-     } else {
-        printf ("%" PRId64 " documents counted.\n", count);
-     }
-  }
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_bulk_operation.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_bulk_operation.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_bulk_operation.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_bulk_operation.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,61 +0,0 @@
-:man_page: mongoc_collection_create_bulk_operation
-
-mongoc_collection_create_bulk_operation()
-=========================================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_collection_create_bulk_operation_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_bulk_operation_t *
-  mongoc_collection_create_bulk_operation (
-     mongoc_collection_t *collection,
-     bool ordered,
-     const mongoc_write_concern_t *write_concern);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``ordered``: If the operations must be performed in order.
-* ``write_concern``: An optional :symbol:`mongoc_write_concern_t` or ``NULL``.
-
-Description
------------
-
-This function shall begin a new bulk operation. After creating this you may call various functions such as :symbol:`mongoc_bulk_operation_update()`, :symbol:`mongoc_bulk_operation_insert()` and others.
-
-After calling :symbol:`mongoc_bulk_operation_execute()` the commands will be executed in as large as batches as reasonable by the client.
-
-If ``ordered`` is true, then processing will stop at the first error.
-
-If ``ordered`` is not true, then the bulk operation will attempt to continue processing even after the first failure.
-
-``write_concern`` contains the write concern for all operations in the bulk operation. If ``NULL``, the collection's write concern is used. The global default is acknowledged writes: MONGOC_WRITE_CONCERN_W_DEFAULT.
-
-Errors
-------
-
-Errors are propagated when executing the bulk operation.
-
-Returns
--------
-
-A newly allocated :symbol:`mongoc_bulk_operation_t` that should be freed with :symbol:`mongoc_bulk_operation_destroy()` when no longer in use.
-
-.. warning::
-
-  Failure to handle the result of this function is a programming error.
-
-.. seealso::
-
-  | `Bulk Write Operations <bulk_>`_
-
-  :symbol:`mongoc_bulk_operation_t`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_index.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_index.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_index.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_index.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,28 +0,0 @@
-:man_page: mongoc_collection_create_index
-
-mongoc_collection_create_index()
-================================
-
-.. warning::
-   .. deprecated:: 1.8.0
-
-      See `Manage Collection Indexes <manage-collection-indexes_>`_ for alternatives.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_create_index (mongoc_collection_t *collection,
-                                  const bson_t *keys,
-                                  const mongoc_index_opt_t *opt,
-                                  bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``keys``: A :symbol:`bson:bson_t`.
-* ``opt``: A mongoc_index_opt_t.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_index_with_opts.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_index_with_opts.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_create_index_with_opts.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_create_index_with_opts.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,60 +0,0 @@
-:man_page: mongoc_collection_create_index_with_opts
-
-mongoc_collection_create_index_with_opts()
-==========================================
-
-.. warning::
-   .. deprecated:: 1.8.0
-
-      See `Manage Collection Indexes <manage-collection-indexes_>`_ for alternatives.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_create_index_with_opts (mongoc_collection_t *collection,
-                                            const bson_t *keys,
-                                            const mongoc_index_opt_t *index_opts,
-                                            const bson_t *command_opts,
-                                            bson_t *reply,
-                                            bson_error_t *error); 
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``keys``: A :symbol:`bson:bson_t`.
-* ``index_opts``: A mongoc_index_opt_t.
-* ``reply``: A |bson_t-opt-storage-ptr| to contain the results.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-.. |opts-source| replace:: ``collection``
-
-.. include:: includes/create-index-opts.txt
-
-Description
------------
-
-This function will request the creation of a new index.
-
-This function will use the ``createIndexes`` command.
-The server's reply is stored in ``reply``.
-
-If no write concern is provided in ``command_opts``, the collection's write concern is used.
-
-See :symbol:`mongoc_index_opt_t` for options on creating indexes.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
-``reply`` is always initialized and must be destroyed with :symbol:`bson:bson_destroy()`. If the server is running an obsolete version of MongoDB then ``reply`` may be empty, though it will still be initialized.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_delete.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_delete.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_delete.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_delete.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,50 +0,0 @@
-:man_page: mongoc_collection_delete
-
-mongoc_collection_delete()
-==========================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_collection_remove`, :symbol:`mongoc_collection_delete_one()` or :symbol:`mongoc_collection_delete_many()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_delete (mongoc_collection_t *collection,
-                            mongoc_delete_flags_t flags,
-                            const bson_t *selector,
-                            const mongoc_write_concern_t *write_concern,
-                            bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: A :symbol:`mongoc_delete_flags_t`.
-* ``selector``: A :symbol:`bson:bson_t` containing the query to match documents.
-* ``write_concern``: A :symbol:`mongoc_write_concern_t` or ``NULL``.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function shall delete documents in the given ``collection`` that match ``selector``. The bson ``selector`` is not validated, simply passed along as appropriate to the server.  As such, compatibility and errors should be validated in the appropriate server documentation.
-
-If you want to limit deletes to a single document, provide ``MONGOC_DELETE_SINGLE_REMOVE`` in ``flags``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
-A write concern timeout or write concern error is considered a failure.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_ensure_index.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_ensure_index.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_ensure_index.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_ensure_index.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,34 +0,0 @@
-:man_page: mongoc_collection_ensure_index
-
-mongoc_collection_ensure_index()
-================================
-
-.. warning::
-   .. deprecated:: 1.8.0
-
-      See `Manage Collection Indexes <manage-collection-indexes_>`_ for alternatives.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_ensure_index (mongoc_collection_t *collection,
-                                  const bson_t *keys,
-                                  const mongoc_index_opt_t *opt,
-                                  bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``keys``: A :symbol:`bson:bson_t`.
-* ``opt``: A mongoc_index_opt_t.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_find.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_find.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_find.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_find.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,159 +0,0 @@
-:man_page: mongoc_collection_find
-
-mongoc_collection_find()
-========================
-
-.. warning::
-   .. deprecated:: 1.5.0
-
-      Use :symbol:`mongoc_collection_find_with_opts` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_collection_find (mongoc_collection_t *collection,
-                          mongoc_query_flags_t flags,
-                          uint32_t skip,
-                          uint32_t limit,
-                          uint32_t batch_size,
-                          const bson_t *query,
-                          const bson_t *fields,
-                          const mongoc_read_prefs_t *read_prefs);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: A :symbol:`mongoc_query_flags_t`.
-* ``skip``: A uint32_t of number of documents to skip or 0.
-* ``limit``: A uint32_t of max number of documents to return or 0.
-* ``batch_size``: A uint32_t containing batch size of document result sets or 0 for default. Default is 100.
-* ``query``: A :symbol:`bson:bson_t` containing the query and options to execute.
-* ``fields``: A :symbol:`bson:bson_t` containing fields to return or ``NULL``.
-* ``read_prefs``: A :symbol:`mongoc_read_prefs_t` or ``NULL`` for default read preferences.
-
-Description
------------
-
-This function shall execute a query on the underlying ``collection``.
-
-If no options are necessary, ``query`` can simply contain a query such as ``{a:1}``. If you would like to specify options such as a sort order, the query must be placed inside of ``{"$query": {}}``. See the example below for how to properly specify additional options to ``query``.
-
-.. include:: includes/retryable-read.txt
-
-Returns
--------
-
-.. include:: includes/returns-cursor.txt
-
-Example
--------
-
-.. code-block:: c
-  :caption: Print All Documents in a Collection
-
-  #include <bson/bson.h>
-  #include <mongoc/mongoc.h>
-  #include <stdio.h>
-
-  static void
-  print_all_documents (mongoc_collection_t *collection)
-  {
-     mongoc_cursor_t *cursor;
-     bson_error_t error;
-     const bson_t *doc;
-     char *str;
-     bson_t *query;
-
-     query = BCON_NEW ("$query",
-                       "{",
-                       "foo",
-                       BCON_INT32 (1),
-                       "}",
-                       "$orderby",
-                       "{",
-                       "bar",
-                       BCON_INT32 (-1),
-                       "}");
-     cursor = mongoc_collection_find (
-        collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
-
-     while (mongoc_cursor_next (cursor, &doc)) {
-        str = bson_as_canonical_extended_json (doc, NULL);
-        printf ("%s\n", str);
-        bson_free (str);
-     }
-
-     if (mongoc_cursor_error (cursor, &error)) {
-        fprintf (stderr, "An error occurred: %s\n", error.message);
-     }
-
-     mongoc_cursor_destroy (cursor);
-     bson_destroy (query);
-  }
-
-The "find" command
-------------------
-
-Queries have historically been sent as OP_QUERY wire protocol messages, but beginning in MongoDB 3.2 queries use `the "find" command <https://www.mongodb.com/docs/master/reference/command/find/>`_ instead.
-
-The driver automatically converts queries to the new "find" command syntax if needed, so this change is typically invisible to C Driver users. However, an application written exclusively for MongoDB 3.2 and later can choose to use the new syntax directly instead of relying on the driver to convert from the old syntax:
-
-.. code-block:: c
-
-  /* MongoDB 3.2+ "find" command syntax */
-  query = BCON_NEW ("filter",
-                    "{",
-                    "foo",
-                    BCON_INT32 (1),
-                    "}",
-                    "sort",
-                    "{",
-                    "bar",
-                    BCON_INT32 (-1),
-                    "}");
-  cursor = mongoc_collection_find (
-     collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
-
-The "find" command takes different options from the traditional OP_QUERY message.
-
-====================  ==================  =================
-Query                 ``$query``          ``filter``
-Sort                  ``$orderby``        ``sort``
-Show record location  ``$showDiskLoc``    ``showRecordId``
-Other $-options       ``$<option name>``  ``<option name>``
-====================  ==================  =================
-
-Most applications should use the OP_QUERY syntax, with "$query", "$orderby", and so on, and rely on the driver to convert to the new syntax if needed.
-
-.. seealso::
-
-  | `The "find" command <https://www.mongodb.com/docs/master/reference/command/find/>`_ in the MongoDB Manual.
-
-The "explain" command
----------------------
-
-With MongoDB before 3.2, a query with option ``$explain: true`` returns information about the query plan, instead of the query results. Beginning in MongoDB 3.2, there is a separate "explain" command. The driver will not convert "$explain" queries to "explain" commands, you must call the "explain" command explicitly:
-
-.. code-block:: c
-
-  /* MongoDB 3.2+, "explain" command syntax */
-  command = BCON_NEW ("explain",
-                      "{",
-                      "find",
-                      BCON_UTF8 ("collection_name"),
-                      "filter",
-                      "{",
-                      "foo",
-                      BCON_INT32 (1),
-                      "}",
-                      "}");
-  mongoc_collection_command_simple (collection, command, NULL, &reply, &error);
-
-.. seealso::
-
-  | `The "explain" command <https://www.mongodb.com/docs/master/reference/command/explain/>`_ in the MongoDB Manual.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_find_indexes.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_find_indexes.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_find_indexes.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_find_indexes.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,43 +0,0 @@
-:man_page: mongoc_collection_find_indexes
-
-mongoc_collection_find_indexes()
-================================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_collection_find_indexes_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_collection_find_indexes (mongoc_collection_t *collection,
-                                  bson_error_t *error);
-
-Fetches a cursor containing documents, each corresponding to an index on this collection.
-
-.. include:: includes/retryable-read.txt
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-.. include:: includes/returns-cursor.txt
-
-In the returned cursor each result corresponds to the server's representation of an index on this collection. If the collection does not exist on the server, the cursor will be empty.
-
-The cursor functions :symbol:`mongoc_cursor_set_limit`, :symbol:`mongoc_cursor_set_batch_size`, and :symbol:`mongoc_cursor_set_max_await_time_ms` have no use on the returned cursor.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_get_last_error.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_get_last_error.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_get_last_error.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_get_last_error.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,51 +0,0 @@
-:man_page: mongoc_collection_get_last_error
-
-mongoc_collection_get_last_error()
-==================================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-    To get write results from write operations, instead use:
-
-    - :symbol:`mongoc_collection_update_one`
-    - :symbol:`mongoc_collection_update_many`
-    - :symbol:`mongoc_collection_replace_one`
-    - :symbol:`mongoc_collection_delete_one`
-    - :symbol:`mongoc_collection_delete_many`
-    - :symbol:`mongoc_collection_insert_one`
-    - :symbol:`mongoc_collection_insert_many`
-    - :symbol:`mongoc_bulkwrite_t`
-    - :symbol:`mongoc_bulk_operation_t`
-
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const bson_t *
-  mongoc_collection_get_last_error (const mongoc_collection_t *collection);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-
-Description
------------
-
-:symbol:`mongoc_collection_get_last_error` returns write results from some operations:
-
-- :symbol:`mongoc_collection_update`
-- :symbol:`mongoc_collection_remove`
-- :symbol:`mongoc_collection_delete`
-- :symbol:`mongoc_collection_insert_bulk`
-- :symbol:`mongoc_collection_insert`
-
-Returns
--------
-
-A :symbol:`bson:bson_t` that should not be modified or ``NULL``. The returned :symbol:`bson:bson_t` is may be
-invalidated by the next operation on ``collection``.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_insert_bulk.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_insert_bulk.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_insert_bulk.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_insert_bulk.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,50 +0,0 @@
-:man_page: mongoc_collection_insert_bulk
-
-mongoc_collection_insert_bulk()
-===============================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-    Use :symbol:`mongoc_collection_insert_many()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_insert_bulk (mongoc_collection_t *collection,
-                                 mongoc_insert_flags_t flags,
-                                 const bson_t **documents,
-                                 uint32_t n_documents,
-                                 const mongoc_write_concern_t *write_concern,
-                                 bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``flags``: A bitwise or of :symbol:`mongoc_insert_flags_t`.
-* ``documents``: An array of :symbol:`const bson_t * <bson:bson_t>`.
-* ``n_documents``: The number of documents in ``documents``.
-* ``write_concern``: A :symbol:`mongoc_write_concern_t` or ``NULL``.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function performs a bulk insert of all of the documents in ``documents``. This function is deprecated as it cannot accurately return which documents may have failed during the bulk insert.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-A write concern timeout or write concern error is considered a failure.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_save.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_save.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_save.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_save.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,46 +0,0 @@
-:man_page: mongoc_collection_save
-
-mongoc_collection_save()
-========================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_collection_insert_one()` or :symbol:`mongoc_collection_replace_one()` with "upsert" instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_save (mongoc_collection_t *collection,
-                          const bson_t *document,
-                          const mongoc_write_concern_t *write_concern,
-                          bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``document``: A :symbol:`bson:bson_t` containing the document.
-* ``write_concern``: A :symbol:`mongoc_write_concern_t` or ``NULL`` for default write concern.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function shall save a document into ``collection``. If the document has an ``_id`` field it will be updated. Otherwise it will be inserted.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
-A write concern timeout or write concern error is considered a failure.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_stats.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_stats.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_stats.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_stats.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,48 +0,0 @@
-:man_page: mongoc_collection_stats
-
-mongoc_collection_stats()
-=========================
-
-.. warning::
-   .. deprecated:: 1.10.0
-
-      Use the `$collStats aggregation pipeline stage <https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/>`_ with :symbol:`mongoc_collection_aggregate()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_stats (mongoc_collection_t *collection,
-                           const bson_t *options,
-                           bson_t *reply,
-                           bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``options``: An optional :symbol:`bson:bson_t` containing extra options to pass to the ``collStats`` command.
-* ``reply``: A |bson_t-opt-storage-ptr| to contain the results.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-Run the ``collStats`` command to retrieve statistics about the collection.
-
-The command uses the :symbol:`mongoc_read_prefs_t` set on ``collection``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
-``reply`` is always initialized and must be freed with :symbol:`bson:bson_destroy`.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -27,20 +27,13 @@ Read preferences and write concerns are
     :maxdepth: 1
 
     mongoc_collection_aggregate
-    mongoc_collection_command
     mongoc_collection_command_simple
     mongoc_collection_command_with_opts
     mongoc_collection_copy
     mongoc_collection_count_documents
     mongoc_collection_estimated_document_count
-    mongoc_collection_count
-    mongoc_collection_count_with_opts
-    mongoc_collection_create_bulk_operation
     mongoc_collection_create_bulk_operation_with_opts
-    mongoc_collection_create_index
-    mongoc_collection_create_index_with_opts
     mongoc_collection_create_indexes_with_opts
-    mongoc_collection_delete
     mongoc_collection_delete_many
     mongoc_collection_delete_one
     mongoc_collection_destroy
@@ -48,20 +41,15 @@ Read preferences and write concerns are
     mongoc_collection_drop_index
     mongoc_collection_drop_index_with_opts
     mongoc_collection_drop_with_opts
-    mongoc_collection_ensure_index
-    mongoc_collection_find
     mongoc_collection_find_and_modify
     mongoc_collection_find_and_modify_with_opts
-    mongoc_collection_find_indexes
     mongoc_collection_find_indexes_with_opts
     mongoc_collection_find_with_opts
-    mongoc_collection_get_last_error
     mongoc_collection_get_name
     mongoc_collection_get_read_concern
     mongoc_collection_get_read_prefs
     mongoc_collection_get_write_concern
     mongoc_collection_insert
-    mongoc_collection_insert_bulk
     mongoc_collection_insert_many
     mongoc_collection_insert_one
     mongoc_collection_keys_to_index_string
@@ -71,14 +59,11 @@ Read preferences and write concerns are
     mongoc_collection_rename
     mongoc_collection_rename_with_opts
     mongoc_collection_replace_one
-    mongoc_collection_save
     mongoc_collection_set_read_concern
     mongoc_collection_set_read_prefs
     mongoc_collection_set_write_concern
-    mongoc_collection_stats
     mongoc_collection_update
     mongoc_collection_update_one
     mongoc_collection_update_many
-    mongoc_collection_validate
     mongoc_collection_write_command_with_opts
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_collection_validate.rst 2.0.2-1/src/libmongoc/doc/mongoc_collection_validate.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_collection_validate.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_collection_validate.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,50 +0,0 @@
-:man_page: mongoc_collection_validate
-
-mongoc_collection_validate()
-============================
-
-.. warning::
-   .. deprecated:: 1.10.0
-
-      Run the `validate <https://www.mongodb.com/docs/manual/reference/command/validate/>`_ command directly with :symbol:`mongoc_client_read_command_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_collection_validate (mongoc_collection_t *collection,
-                              const bson_t *options,
-                              bson_t *reply,
-                              bson_error_t *error);
-
-Parameters
-----------
-
-* ``collection``: A :symbol:`mongoc_collection_t`.
-* ``options``: A :symbol:`bson:bson_t`.
-* ``reply``: A |bson_t-opt-storage-ptr| to contain the results.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function is a helper function to execute the ``validate`` MongoDB command.
-
-Currently, the only supported options are ``full``, which is a boolean and ``scandata``, also a boolean.
-
-See the MongoDB documentation for more information on this command.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.
-
-``reply`` is always initialized if it's not ``NULL`` and must be destroyed with :symbol:`bson:bson_destroy()`.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_get_hint.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_get_hint.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_get_hint.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_get_hint.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,32 +0,0 @@
-:man_page: mongoc_cursor_get_hint
-
-mongoc_cursor_get_hint()
-========================
-
-.. warning::
-   .. deprecated:: 1.28.0
-
-      Use :symbol:`mongoc_cursor_get_server_id()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  uint32_t
-  mongoc_cursor_get_hint (const mongoc_cursor_t *cursor);
-
-Parameters
-----------
-
-* ``cursor``: A :symbol:`mongoc_cursor_t`.
-
-Description
------------
-
-Retrieves the opaque id of the server used for the operation.
-
-(The function name includes the old term "hint" for the sake of backward compatibility, but we now call this number a "server id".)
-
-This number is zero until the driver actually uses a server when executing the find operation or :symbol:`mongoc_cursor_set_server_id` is called.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_get_limit.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_get_limit.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_get_limit.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_get_limit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -19,5 +19,5 @@ Parameters
 Description
 -----------
 
-Return the value set with :symbol:`mongoc_cursor_set_limit` or :symbol:`mongoc_collection_find`.
+Return the value set with :symbol:`mongoc_cursor_set_limit` or :symbol:`mongoc_collection_find_with_opts`.
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_is_alive.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_is_alive.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_is_alive.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_is_alive.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-:man_page: mongoc_cursor_is_alive
-
-mongoc_cursor_is_alive()
-========================
-
-.. warning::
-   .. deprecated:: 1.10.0
-
-      Use :symbol:`mongoc_cursor_more()` instead.
-
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_cursor_is_alive (const mongoc_cursor_t *cursor);
-
-Parameters
-----------
-
-* ``cursor``: A :symbol:`mongoc_cursor_t`.
-
-
-Returns
--------
-
-See :symbol:`mongoc_cursor_more()`.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_new_from_command_reply.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_new_from_command_reply.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_new_from_command_reply.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_new_from_command_reply.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,63 +0,0 @@
-:man_page: mongoc_cursor_new_from_command_reply
-
-mongoc_cursor_new_from_command_reply()
-======================================
-
-.. warning::
-   .. deprecated:: 1.11.0
-
-      Use :symbol:`mongoc_cursor_new_from_command_reply_with_opts()` instead.
-
-      When migrating from the deprecated :symbol:`mongoc_cursor_new_from_command_reply()` to :symbol:`mongoc_cursor_new_from_command_reply_with_opts()`,
-      note that options previously passed to the ``reply`` argument (e.g. "batchSize") must instead be provided in the ``opts`` argument.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_cursor_new_from_command_reply (mongoc_client_t *client,
-                                        bson_t *reply,
-                                        uint32_t server_id);
-
-Parameters
-----------
-
-* ``client``: A :symbol:`mongoc_client_t`.
-* ``reply``: The reply to a command, such as "aggregate", "find", or "listCollections", that returns a cursor document. The reply is destroyed by ``mongoc_cursor_new_from_command_reply`` and must not be accessed afterward.
-* ``server_id``: The opaque id of the server used to execute the command.
-
-Description
------------
-
-Some MongoDB commands return a "cursor" document. For example, given an "aggregate" command:
-
-.. code-block:: none
-
-  { "aggregate" : "collection", "pipeline" : [], "cursor" : {}}
-
-The server replies:
-
-.. code-block:: none
-
-  {
-     "cursor" : {
-        "id" : 1234,
-        "ns" : "db.collection",
-        "firstBatch" : [ ]
-     },
-     "ok" : 1
-  }
-
-``mongoc_cursor_new_from_command_reply`` is a low-level function that initializes a :symbol:`mongoc_cursor_t` from such a reply. Additional options such as "tailable" or "awaitData" can be included in the reply.
-
-When synthesizing a completed cursor response that has no more batches (i.e. with cursor id 0), ``server_id`` may be 0. If the cursor response is not completed (i.e. with non-zero cursor id), pass the ``server_id`` of the server used to create the cursor.
-
-Use this function only for building a language driver that wraps the C Driver. When writing applications in C, higher-level functions such as :symbol:`mongoc_collection_aggregate` are more appropriate, and ensure compatibility with a range of MongoDB versions.
-
-Returns
--------
-
-A :symbol:`mongoc_cursor_t`. On failure, the cursor's error is set. Check for failure with :symbol:`mongoc_cursor_error`.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_set_hint.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_set_hint.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_set_hint.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_set_hint.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-:man_page: mongoc_cursor_set_hint
-
-mongoc_cursor_set_hint()
-========================
-
-.. warning::
-   .. deprecated:: 1.28.0
-
-      Use :symbol:`mongoc_cursor_set_server_id()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_cursor_set_hint (mongoc_cursor_t *cursor, uint32_t server_id);
-
-Parameters
-----------
-
-* ``cursor``: A :symbol:`mongoc_cursor_t`.
-* ``server_id``: An opaque id identifying the server to use.
-
-Description
------------
-
-Specifies which server to use for the operation. This function has an effect only if called before the find operation is executed.
-
-(The function name includes the old term "hint" for the sake of backward compatibility, but we now call this number a "server id".)
-
-Use ``mongoc_cursor_set_hint`` only for building a language driver that wraps the C Driver. When writing applications in C, leave the server id unset and allow the driver to choose a suitable server from the find operation's read preference.
-
-Returns
--------
-
-Returns true on success. If any arguments are invalid, returns false and logs an error.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_set_limit.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_set_limit.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_set_limit.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_set_limit.rst	2025-06-19 15:42:22.000000000 +0000
@@ -22,7 +22,7 @@ Description
 
 Limits the number of documents in the result set.
 
-This function is useful for setting the limit on a cursor after the cursor is created, but before any calls to :symbol:`mongoc_cursor_next`. It can also be used to pass a negative limit: The ``limit`` parameter to ``mongoc_cursor_set_limit`` is signed, although for backward-compatibility reasons the ``limit`` parameter to :symbol:`mongoc_collection_find` is not.
+This function is useful for setting the limit on a cursor after the cursor is created, but before any calls to :symbol:`mongoc_cursor_next`. It can also be used to pass a negative limit: The ``limit`` parameter to ``mongoc_cursor_set_limit`` is signed.
 
 Calling this function after :symbol:`mongoc_cursor_next` has no effect.
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_cursor_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_cursor_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_cursor_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_cursor_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -51,19 +51,15 @@ Example
     mongoc_cursor_error
     mongoc_cursor_error_document
     mongoc_cursor_get_batch_size
-    mongoc_cursor_get_hint
     mongoc_cursor_get_server_id
     mongoc_cursor_get_host
     mongoc_cursor_get_id
     mongoc_cursor_get_limit
     mongoc_cursor_get_max_await_time_ms
-    mongoc_cursor_is_alive
     mongoc_cursor_more
-    mongoc_cursor_new_from_command_reply
     mongoc_cursor_new_from_command_reply_with_opts
     mongoc_cursor_next
     mongoc_cursor_set_batch_size
-    mongoc_cursor_set_hint
     mongoc_cursor_set_server_id
     mongoc_cursor_set_limit
     mongoc_cursor_set_max_await_time_ms
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_database_command.rst 2.0.2-1/src/libmongoc/doc/mongoc_database_command.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_database_command.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_database_command.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,73 +0,0 @@
-:man_page: mongoc_database_command
-
-mongoc_database_command()
-=========================
-
-.. warning::
-   .. deprecated:: 1.29.0
-
-      This function is deprecated and should not be used in new code.
-      Use :symbol:`mongoc_database_command_simple()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_database_command (mongoc_database_t *database,
-                           mongoc_query_flags_t flags,
-                           uint32_t skip,
-                           uint32_t limit,
-                           uint32_t batch_size,
-                           const bson_t *command,
-                           const bson_t *fields,
-                           const mongoc_read_prefs_t *read_prefs);
-
-Description
------------
-
-This function creates a cursor which will execute the command when :symbol:`mongoc_cursor_next` is called on it. The database's read preference, read concern, and write concern are not applied to the command, and :symbol:`mongoc_cursor_next` will not check the server response for a write concern error or write concern timeout.
-
-.. include:: includes/not-retryable-read.txt
-
-Parameters
-----------
-
-* ``database``: A :symbol:`mongoc_database_t`.
-* ``flags``: Unused.
-* ``skip``: Unused.
-* ``limit``: Unused.
-* ``batch_size``: Unused.
-* ``command``: A :symbol:`bson:bson_t` containing the command.
-* ``fields``: Unused.
-* ``read_prefs``: An optional :symbol:`mongoc_read_prefs_t`. Otherwise, the command uses mode ``MONGOC_READ_PRIMARY``.
-
-Migrating
----------
-
-:symbol:`mongoc_database_command` is deprecated.
-
-The following example uses :symbol:`mongoc_database_command`:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_database_command ... before ... begin
-   :end-before:  // mongoc_database_command ... before ... end
-   :caption: Before
-
-The above code block may be rewritten to use :symbol:`mongoc_database_command_simple` instead, as shown below:
-
-.. literalinclude:: ../examples/migrating.c
-   :language: c
-   :dedent: 6
-   :start-after: // mongoc_database_command ... after ... begin
-   :end-before:  // mongoc_database_command ... after ... end
-   :caption: After
-
-Returns
--------
-
-.. include:: includes/returns-cursor.txt
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_database_command_simple.rst 2.0.2-1/src/libmongoc/doc/mongoc_database_command_simple.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_database_command_simple.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_database_command_simple.rst	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@ Parameters
 * ``reply``: A |bson_t-opt-storage-ptr| to contain the results.
 * ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
 
-This is a simplified interface to :symbol:`mongoc_database_command()` that returns the first result document. The database's read preference, read concern, and write concern are not applied to the command.  The parameter ``reply`` is initialized even upon failure to simplify memory management.
+The database's read preference, read concern, and write concern are not applied to the command.  The parameter ``reply`` is initialized even upon failure to simplify memory management.
 
 .. include:: includes/not-retryable-read.txt
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_database_find_collections.rst 2.0.2-1/src/libmongoc/doc/mongoc_database_find_collections.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_database_find_collections.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_database_find_collections.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,47 +0,0 @@
-:man_page: mongoc_database_find_collections
-
-mongoc_database_find_collections()
-==================================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_database_find_collections_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_cursor_t *
-  mongoc_database_find_collections (mongoc_database_t *database,
-                                    const bson_t *filter,
-                                    bson_error_t *error);
-
-Description
------------
-
-Fetches a cursor containing documents, each corresponding to a collection on this database.
-
-.. include:: includes/retryable-read.txt
-
-Parameters
-----------
-
-* ``database``: A :symbol:`mongoc_database_t`.
-* ``filter``: A matcher used by the server to filter the returned collections. May be ``NULL``.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-This function returns a newly allocated :symbol:`mongoc_cursor_t` that should be freed with :symbol:`mongoc_cursor_destroy()` when no longer in use, or `NULL` in case of error. The user must call :symbol:`mongoc_cursor_next()` on the returned :symbol:`mongoc_cursor_t` to execute the initial command.
-
-In the returned cursor each result corresponds to the server's representation of a collection in this database.
-
-The cursor functions :symbol:`mongoc_cursor_set_limit`, :symbol:`mongoc_cursor_set_batch_size`, and :symbol:`mongoc_cursor_set_max_await_time_ms` have no use on the returned cursor.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_database_get_collection_names.rst 2.0.2-1/src/libmongoc/doc/mongoc_database_get_collection_names.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_database_get_collection_names.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_database_get_collection_names.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,41 +0,0 @@
-:man_page: mongoc_database_get_collection_names
-
-mongoc_database_get_collection_names()
-======================================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_database_get_collection_names_with_opts()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  char **
-  mongoc_database_get_collection_names (mongoc_database_t *database,
-                                        bson_error_t *error);
-
-Description
------------
-
-Fetches a ``NULL`` terminated array of ``NULL-byte`` terminated ``char*`` strings containing the names of all of the collections in ``database``.
-
-.. include:: includes/retryable-read.txt
-
-Parameters
-----------
-
-* ``database``: A :symbol:`mongoc_database_t`.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-A ``NULL`` terminated array of ``NULL`` terminated ``char*`` strings that should be freed with :symbol:`bson:bson_strfreev()`. Upon failure, ``NULL`` is returned and ``error`` is set.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_database_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_database_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_database_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_database_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -27,7 +27,6 @@ Read preferences and write concerns are
 
     mongoc_database_add_user
     mongoc_database_aggregate
-    mongoc_database_command
     mongoc_database_command_simple
     mongoc_database_command_with_opts
     mongoc_database_copy
@@ -35,10 +34,8 @@ Read preferences and write concerns are
     mongoc_database_destroy
     mongoc_database_drop
     mongoc_database_drop_with_opts
-    mongoc_database_find_collections
     mongoc_database_find_collections_with_opts
     mongoc_database_get_collection
-    mongoc_database_get_collection_names
     mongoc_database_get_collection_names_with_opts
     mongoc_database_get_name
     mongoc_database_get_read_concern
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_delete_flags_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_delete_flags_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_delete_flags_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_delete_flags_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,21 +0,0 @@
-:man_page: mongoc_delete_flags_t
-
-mongoc_delete_flags_t
-=====================
-
-.. warning::
-   .. deprecated:: 1.9.0
-
-      Use :symbol:`mongoc_collection_delete_one()` or :symbol:`mongoc_collection_delete_many()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  typedef enum {
-     MONGOC_DELETE_NONE = 0,
-     MONGOC_DELETE_SINGLE_REMOVE = 1 << 0,
-  } mongoc_delete_flags_t;
-
-Flags for deletion operations
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_file_list_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_file_list_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_file_list_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_file_list_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -25,7 +25,7 @@ Example
   mongoc_gridfs_file_list_t *list;
   mongoc_gridfs_file_t *file;
 
-  list = mongoc_gridfs_find (gridfs, query);
+  list = mongoc_gridfs_find_with_opts (gridfs, query, NULL);
 
   while ((file = mongoc_gridfs_file_list_next (list))) {
      do_something (file);
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_find.rst 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_find.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_find.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_find.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-:man_page: mongoc_gridfs_find
-
-mongoc_gridfs_find()
-====================
-
-.. warning::
-   .. deprecated:: 1.5.0
-
-      This function is deprecated, use :symbol:`mongoc_gridfs_find_with_opts` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_gridfs_file_list_t *
-  mongoc_gridfs_find (mongoc_gridfs_t *gridfs,
-                      const bson_t *query);
-
-Parameters
-----------
-
-* ``gridfs``: A :symbol:`mongoc_gridfs_t`.
-* ``query``: A :symbol:`bson:bson_t`.
-
-Description
------------
-
-Finds all gridfs files matching ``query``. You can iterate the matched gridfs files with the resulting file list.
-
-.. include:: includes/retryable-read.txt
-
-Returns
--------
-
-A newly allocated :symbol:`mongoc_gridfs_file_list_t` that should be freed with :symbol:`mongoc_gridfs_file_list_destroy()` when no longer in use.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_find_one.rst 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_find_one.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_find_one.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_find_one.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,44 +0,0 @@
-:man_page: mongoc_gridfs_find_one
-
-mongoc_gridfs_find_one()
-========================
-
-.. warning::
-   .. deprecated:: 1.5.0
-
-      This function is deprecated, use :symbol:`mongoc_gridfs_find_one_with_opts` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  mongoc_gridfs_file_t *
-  mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs,
-                          const bson_t *query,
-                          bson_error_t *error);
-
-Parameters
-----------
-
-* ``gridfs``: A :symbol:`mongoc_gridfs_t`.
-* ``query``: A :symbol:`bson:bson_t`.
-* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.
-
-Description
------------
-
-This function shall execute a query on the underlying gridfs implementation. The first file matching ``query`` will be returned. If there is an error, NULL is returned and ``error`` is filled out; if there is no error but no matching file is found, NULL is returned and the error code and domain are 0.
-
-.. include:: includes/retryable-read.txt
-
-Errors
-------
-
-Errors are propagated via the ``error`` parameter.
-
-Returns
--------
-
-A newly allocated :symbol:`mongoc_gridfs_file_t` or ``NULL`` if no file could be found. You must free the resulting file with :symbol:`mongoc_gridfs_file_destroy()` if non-NULL.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_gridfs_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_gridfs_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -65,8 +65,6 @@ Example
     mongoc_gridfs_create_file_from_stream
     mongoc_gridfs_destroy
     mongoc_gridfs_drop
-    mongoc_gridfs_find
-    mongoc_gridfs_find_one
     mongoc_gridfs_find_one_by_filename
     mongoc_gridfs_find_one_with_opts
     mongoc_gridfs_find_with_opts
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_get_default.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_get_default.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_get_default.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_get_default.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,18 +0,0 @@
-:man_page: mongoc_index_opt_geo_get_default
-
-mongoc_index_opt_geo_get_default()
-==================================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const mongoc_index_opt_geo_t *
-  mongoc_index_opt_geo_get_default (void);
-
-Returns
--------
-
-Returns a pointer to the default GEO index creation options.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_init.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_init.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_init.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_init.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,23 +0,0 @@
-:man_page: mongoc_index_opt_geo_init
-
-mongoc_index_opt_geo_init()
-===========================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_index_opt_geo_init (mongoc_index_opt_geo_t *opt);
-
-Parameters
-----------
-
-* ``opt``: A :symbol:`mongoc_index_opt_geo_t`.
-
-Description
------------
-
-This function will initialize ``opt`` to the default values. It should be called before modifying any fields within the structure.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_geo_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_geo_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,44 +0,0 @@
-:man_page: mongoc_index_opt_geo_t
-
-mongoc_index_opt_geo_t
-======================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  #include <mongoc/mongoc.h>
-
-  typedef struct {
-     uint8_t twod_sphere_version;
-     uint8_t twod_bits_precision;
-     double twod_location_min;
-     double twod_location_max;
-     double haystack_bucket_size;
-     uint8_t *padding[32];
-  } mongoc_index_opt_geo_t;
-
-Description
------------
-
-This structure contains the options that may be used for tuning a GEO index.
-
-.. only:: html
-
-  Functions
-  ---------
-
-  .. toctree::
-    :titlesonly:
-    :maxdepth: 1
-
-    mongoc_index_opt_geo_get_default
-    mongoc_index_opt_geo_init
-
-.. seealso::
-
-  | :doc:`mongoc_index_opt_t`
-
-  | :doc:`mongoc_index_opt_wt_t`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_get_default.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_get_default.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_get_default.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_get_default.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,18 +0,0 @@
-:man_page: mongoc_index_opt_get_default
-
-mongoc_index_opt_get_default()
-==============================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const mongoc_index_opt_t *
-  mongoc_index_opt_get_default (void);
-
-Returns
--------
-
-Returns a pointer to the default index creation options.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_init.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_init.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_init.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_init.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,23 +0,0 @@
-:man_page: mongoc_index_opt_init
-
-mongoc_index_opt_init()
-=======================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_index_opt_init (mongoc_index_opt_t *opt);
-
-Parameters
-----------
-
-* ``opt``: A :symbol:`mongoc_index_opt_t`.
-
-Description
------------
-
-This function will initialize ``opt`` to the default values. It should be called before modifying any fields within the structure.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,95 +0,0 @@
-:man_page: mongoc_index_opt_t
-
-mongoc_index_opt_t
-==================
-
-.. warning::
-   .. deprecated:: 1.8.0
-
-      See `Manage Collection Indexes <manage-collection-indexes_>`_ for alternatives.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  #include <mongoc/mongoc.h>
-
-  typedef struct {
-     bool is_initialized;
-     bool background;
-     bool unique;
-     const char *name;
-     bool drop_dups;
-     bool sparse;
-     int32_t expire_after_seconds;
-     int32_t v;
-     const bson_t *weights;
-     const char *default_language;
-     const char *language_override;
-     mongoc_index_opt_geo_t *geo_options;
-     mongoc_index_opt_storage_t *storage_options;
-     const bson_t *partial_filter_expression;
-     const bson_t *collation;
-     void *padding[4];
-  } mongoc_index_opt_t;
-
-Description
------------
-
-This structure contains the options that may be used for tuning a specific index.
-
-See the `createIndexes documentations <https://www.mongodb.com/docs/manual/reference/command/createIndexes/>`_ in the MongoDB manual for descriptions of individual options.
-
-.. note::
-
-   dropDups is deprecated as of MongoDB version 3.0.0.  This option is silently ignored by the server and unique index builds using this option will fail if a duplicate value is detected.
-
-Example
--------
-
-.. code-block:: c
-
-  {
-     bson_t keys;
-     bson_error_t error;
-     mongoc_index_opt_t opt;
-     mongoc_index_opt_geo_t geo_opt;
-
-     mongoc_index_opt_init (&opt);
-     mongoc_index_opt_geo_init (&geo_opt);
-
-     bson_init (&keys);
-     BSON_APPEND_UTF8 (&keys, "location", "2d");
-
-     geo_opt.twod_location_min = -123;
-     geo_opt.twod_location_max = +123;
-     geo_opt.twod_bits_precision = 30;
-     opt.geo_options = &geo_opt;
-
-     collection = mongoc_client_get_collection (client, "test", "geo_test");
-     if (mongoc_collection_create_index (collection, &keys, &opt, &error)) {
-        /* Successfully created the geo index */
-     }
-     bson_destroy (&keys);
-     mongoc_collection_destroy (&collection);
-  }
-
-.. only:: html
-
-  Functions
-  ---------
-
-  .. toctree::
-    :titlesonly:
-    :maxdepth: 1
-
-    mongoc_index_opt_get_default
-    mongoc_index_opt_init
-
-.. seealso::
-
-  | :doc:`mongoc_index_opt_geo_t`
-
-  | :doc:`mongoc_index_opt_wt_t`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_get_default.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_get_default.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_get_default.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_get_default.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,18 +0,0 @@
-:man_page: mongoc_index_opt_wt_get_default
-
-mongoc_index_opt_wt_get_default()
-=================================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const mongoc_index_opt_wt_t *
-  mongoc_index_opt_wt_get_default (void);
-
-Returns
--------
-
-Returns a pointer to the default WiredTiger index creation options.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_init.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_init.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_init.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_init.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,23 +0,0 @@
-:man_page: mongoc_index_opt_wt_init
-
-mongoc_index_opt_wt_init()
-==========================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_index_opt_wt_init (mongoc_index_opt_wt_t *opt);
-
-Parameters
-----------
-
-* ``opt``: A :symbol:`mongoc_index_opt_wt_t`.
-
-Description
------------
-
-This function will initialize ``opt`` to the default values. It should be called before modifying any fields within the structure.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_index_opt_wt_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_index_opt_wt_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,41 +0,0 @@
-:man_page: mongoc_index_opt_wt_t
-
-mongoc_index_opt_wt_t
-=====================
-
-Synopsis
---------
-
-.. code-block:: c
-
-  #include <mongoc/mongoc.h>
-
-  typedef struct {
-     mongoc_index_opt_storage_t base;
-     const char *config_str;
-     void *padding[8];
-  } mongoc_index_opt_wt_t;
-
-Description
------------
-
-This structure contains the options that may be used for tuning a WiredTiger specific index.
-
-.. only:: html
-
-  Functions
-  ---------
-
-  .. toctree::
-    :titlesonly:
-    :maxdepth: 1
-
-    mongoc_index_opt_wt_get_default
-    mongoc_index_opt_wt_init
-
-.. seealso::
-
-  | :doc:`mongoc_index_opt_t`
-
-  | :doc:`mongoc_index_opt_geo_t`
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_query_flags_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_query_flags_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_query_flags_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_query_flags_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -36,8 +36,7 @@ MONGOC_QUERY_SECONDARY_OK       Allow qu
 MONGOC_QUERY_OPLOG_REPLAY       Used internally by MongoDB.
 MONGOC_QUERY_NO_CURSOR_TIMEOUT  The server normally times out an idle cursor after an inactivity period (10 minutes). This prevents that.
 MONGOC_QUERY_AWAIT_DATA         Use with MONGOC_QUERY_TAILABLE_CURSOR. Block rather than returning no data. After a period, time out.
-MONGOC_QUERY_EXHAUST            Stream the data down full blast in multiple "reply" packets. Faster when you are pulling down a lot of data and you know you want to retrieve it all.
-                                Only applies to cursors created from a find operation (i.e. :symbol:`mongoc_collection_find()`).
+MONGOC_QUERY_EXHAUST            Unused.
 MONGOC_QUERY_PARTIAL            Get partial results from mongos if some shards are down (instead of throwing an error).
 ==============================  =====================================================================================================================================================
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_get_hedge.rst 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_get_hedge.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_get_hedge.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_get_hedge.rst	2025-06-19 15:42:22.000000000 +0000
@@ -3,6 +3,11 @@
 mongoc_read_prefs_get_hedge()
 =============================
 
+.. deprecated:: MongoDB Server 8.0
+
+  Hedged reads are deprecated in MongoDB version 8.0 and will be removed in
+  a future release.
+
 Synopsis
 --------
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_set_hedge.rst 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_set_hedge.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_set_hedge.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_set_hedge.rst	2025-06-19 15:42:22.000000000 +0000
@@ -3,6 +3,11 @@
 mongoc_read_prefs_set_hedge()
 =============================
 
+.. deprecated:: MongoDB Server 8.0
+
+  Hedged reads are deprecated in MongoDB version 8.0 and will be removed in
+  a future release.
+
 Synopsis
 --------
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_read_prefs_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_read_prefs_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -70,9 +70,19 @@ Max Staleness is also supported by shard
 Hedged Reads
 ------------
 
-When connecting to a sharded cluster running MongoDB 4.4 or later, reads can be sent in parallel to the two "best" hosts.  Once one result returns, any other outstanding operations that were part of the hedged read are cancelled.
+.. deprecated:: MongoDB Server 8.0
 
-When the read preference mode is ``MONGOC_READ_NEAREST`` and the sharded cluster is running MongoDB 4.4 or later, hedged reads are enabled by default.  Additionally, hedged reads may be explicitly enabled or disabled by calling :symbol:`mongoc_read_prefs_set_hedge` with a BSON document, e.g.
+  Hedged reads are deprecated in MongoDB version 8.0 and will be removed in
+  a future release.
+
+When connecting to a sharded cluster running MongoDB 4.4 or later, reads can be
+sent in parallel to the two "best" hosts. Once one result returns, any other
+outstanding operations that were part of the hedged read are cancelled.
+
+When the read preference mode is ``MONGOC_READ_NEAREST`` and the sharded cluster
+is running MongoDB 4.4 or later, hedged reads are enabled by default.
+Additionally, hedged reads may be explicitly enabled or disabled by calling
+:symbol:`mongoc_read_prefs_set_hedge` with a BSON document, e.g.
 
 .. code-block:: none
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_reply_flags_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_reply_flags_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_reply_flags_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_reply_flags_t.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,36 +0,0 @@
-:man_page: mongoc_reply_flags_t
-
-mongoc_reply_flags_t
-====================
-
-Flags from server replies
-
-Synopsis
---------
-
-.. code-block:: c
-
-  typedef enum {
-     MONGOC_REPLY_NONE = 0,
-     MONGOC_REPLY_CURSOR_NOT_FOUND = 1 << 0,
-     MONGOC_REPLY_QUERY_FAILURE = 1 << 1,
-     MONGOC_REPLY_SHARD_CONFIG_STALE = 1 << 2,
-     MONGOC_REPLY_AWAIT_CAPABLE = 1 << 3,
-  } mongoc_reply_flags_t;
-
-Description
------------
-
-These flags correspond to the wire protocol. They may be bitwise or'd together.
-
-Flag Values
------------
-
-===============================  ==================================================================
-MONGOC_REPLY_NONE                No flags set.
-MONGOC_REPLY_CURSOR_NOT_FOUND    No matching cursor was found on the server.
-MONGOC_REPLY_QUERY_FAILURE       The query failed or was invalid. Error document has been provided.
-MONGOC_REPLY_SHARD_CONFIG_STALE  Shard config is stale.
-MONGOC_REPLY_AWAIT_CAPABLE       If the returned cursor is capable of MONGOC_QUERY_AWAIT_DATA.
-===============================  ==================================================================
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_server_description_host.rst 2.0.2-1/src/libmongoc/doc/mongoc_server_description_host.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_server_description_host.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_server_description_host.rst	2025-06-19 15:42:22.000000000 +0000
@@ -8,7 +8,7 @@ Synopsis
 
 .. code-block:: c
 
-  mongoc_host_list_t *
+  const mongoc_host_list_t *
   mongoc_server_description_host (const mongoc_server_description_t *description);
 
 Parameters
@@ -24,5 +24,7 @@ Return the server's host and port. This
 Returns
 -------
 
-A reference to the server description's :symbol:`mongoc_host_list_t`, which you must not modify or free.
+.. versionchanged:: 2.0.0 The return type changed from ``mongoc_host_list_t *`` to ``const mongoc_host_list_t *``.
+
+A reference to the server description's :symbol:`mongoc_host_list_t`.
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_server_description_ismaster.rst 2.0.2-1/src/libmongoc/doc/mongoc_server_description_ismaster.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_server_description_ismaster.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_server_description_ismaster.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,34 +0,0 @@
-:man_page: mongoc_server_description_ismaster
-
-mongoc_server_description_ismaster()
-====================================
-
-.. warning::
-   .. deprecated:: 1.18.0
-
-      Use :doc:`mongoc_server_description_hello_response() <mongoc_server_description_hello_response>` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const bson_t *
-  mongoc_server_description_ismaster (
-     const mongoc_server_description_t *description);
-
-Parameters
-----------
-
-* ``description``: A :symbol:`mongoc_server_description_t`.
-
-Description
------------
-
-The client or client pool periodically runs a `"hello" <https://www.mongodb.com/docs/manual/reference/command/hello/>`_ command on each server, to update its view of the MongoDB deployment. Use :symbol:`mongoc_client_get_server_descriptions()` and ``mongoc_server_description_hello_response()`` to get the most recent "hello" response.
-
-Returns
--------
-
-A reference to a BSON document, owned by the server description. The document is empty if the driver is not connected to the server.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_server_description_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_server_description_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_server_description_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_server_description_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -36,7 +36,6 @@ Applications receive a temporary referen
     mongoc_server_description_hello_response
     mongoc_server_description_host
     mongoc_server_description_id
-    mongoc_server_description_ismaster
     mongoc_server_description_last_update_time
     mongoc_server_description_new_copy
     mongoc_server_description_round_trip_time
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_read_prefs.rst 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_read_prefs.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_read_prefs.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_read_prefs.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,33 +0,0 @@
-:man_page: mongoc_uri_get_read_prefs
-
-mongoc_uri_get_read_prefs()
-===========================
-
-.. warning::
-   .. deprecated:: 1.2.0
-
-      Use :doc:`mongoc_uri_get_read_prefs_t() <mongoc_uri_get_read_prefs_t>` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const bson_t *
-  mongoc_uri_get_read_prefs (const mongoc_uri_t *uri);
-
-Parameters
-----------
-
-* ``uri``: A :symbol:`mongoc_uri_t`.
-
-Description
------------
-
-Fetches a bson document containing read preference tag information from a URI. Note that this does not include the read preference mode.
-
-Returns
--------
-
-Returns a bson document that should not be modified or freed if ``uri`` has read preferences, otherwise ``NULL``.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_service.rst 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_service.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_service.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_service.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-:man_page: mongoc_uri_get_service
-
-mongoc_uri_get_service()
-========================
-
-.. warning::
-   .. deprecated:: 1.21.0
-
-      Use :symbol:`mongoc_uri_get_srv_hostname()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  const char *
-  mongoc_uri_get_service (const mongoc_uri_t *uri);
-
-Parameters
-----------
-
-* ``uri``: A :symbol:`mongoc_uri_t`.
-
-Returns the SRV host and domain name of a MongoDB URI.
-
-Returns
--------
-
-A string if this URI's scheme is "mongodb+srv://", or NULL if the scheme is "mongodb://".
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_ssl.rst 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_ssl.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_uri_get_ssl.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_uri_get_ssl.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,34 +0,0 @@
-:man_page: mongoc_uri_get_ssl
-
-mongoc_uri_get_ssl()
-====================
-
-.. warning::
-   .. deprecated:: 1.15.0
-
-      Use :doc:`mongoc_uri_get_tls() <mongoc_uri_get_tls>` instead.
-
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_uri_get_ssl (const mongoc_uri_t *uri);
-
-Parameters
-----------
-
-* ``uri``: A :symbol:`mongoc_uri_t`.
-
-Description
------------
-
-Fetches a boolean indicating if TLS was specified for use in the URI.
-
-Returns
--------
-
-Returns a boolean, true indicating that TLS should be used. This returns true if *any* :ref:`TLS option <tls_options>` is specified.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_uri_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_uri_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_uri_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_uri_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -122,20 +122,67 @@ Authentication Options
 Constant                                   Key                               Description
 ========================================== ================================= =========================================================================================================================================================================================================================
 MONGOC_URI_AUTHMECHANISM                   authmechanism                     Specifies the mechanism to use when authenticating as the provided user. See `Authentication <authentication_>`_ for supported values.
-MONGOC_URI_AUTHMECHANISMPROPERTIES         authmechanismproperties           Certain authentication mechanisms have additional options that can be configured. These options should be provided as comma separated option_key:option_value pair and provided as authMechanismProperties. Specifying the same option_key multiple times has undefined behavior.
-MONGOC_URI_AUTHSOURCE                      authsource                        The authSource defines the database that should be used to authenticate to. It is unnecessary to provide this option the database name is the same as the database used in the URI.
+MONGOC_URI_AUTHMECHANISMPROPERTIES         authmechanismproperties           Additional properties for the specified mechanism using key-value pair format, e.g. ``key1:value1,key2:value2``.
+MONGOC_URI_AUTHSOURCE                      authsource                        The name of the database to which authentication commands are sent or ``$external`` depending on the specified mechanism. Overrides the auth database in the URI when applicable.
 ========================================== ================================= =========================================================================================================================================================================================================================
 
+.. _authentication_mechanism_properties:
+
 Mechanism Properties
 ~~~~~~~~~~~~~~~~~~~~
 
-========================================== ================================= =========================================================================================================================================================================================================================
-Constant                                   Key                               Description
-========================================== ================================= =========================================================================================================================================================================================================================
-MONGOC_URI_CANONICALIZEHOSTNAME            canonicalizehostname              Use the canonical hostname of the service, rather than its configured alias, when authenticating with Cyrus-SASL Kerberos.
-MONGOC_URI_GSSAPISERVICENAME               gssapiservicename                 Use alternative service name. The default is ``mongodb``.
-========================================== ================================= =========================================================================================================================================================================================================================
+The following properties may be specified as key-value pairs for the ``MONGOC_URI_AUTHMECHANISMPROPERTIES`` option.
+
+Invalid or unsupported properties may be reported as a client error when a corresponding authentication mechanism is also specified.
+
+MONGODB-OIDC
+^^^^^^^^^^^^
+
+============== =========================================================================================
+Key            Value
+============== =========================================================================================
+ENVIRONMENT    The name of a built-in OIDC provider integration. Must be one of ["azure", "gcp", "k8s"].
+TOKEN_RESOURCE The URI of the target resource. ``ENVIRONMENT`` must be one of ["azure", "gcp"].
+============== =========================================================================================
+
+.. warning::
+
+  A ``TOKEN_RESOURCE`` property value MUST NOT contain the comma character "," when specified as a connection string query option, even when percent-encoded.
+  A value containing a comma character may be set using :symbol:`mongoc_uri_set_mechanism_properties()` instead.
+  However, the value MAY contain the colon character ":", as only the first colon is interpreted as a key-value delimiter.
+
+GSSAPI
+^^^^^^
+
+====================== ===================================================================================================================================================================================================================================
+Key                    Value
+====================== ===================================================================================================================================================================================================================================
+SERVICE_NAME           Optional. Defaults to "mongodb".
+CANONICALIZE_HOST_NAME Optional. Must be one of ["false", "true"]. "false" performs no canonicalization (aka "none"). "true" performs a forward DNS lookup and then a reverse lookup on that value to canonicalize the hostname (aka "forwardAndReverse").
+SERVICE_REALM          Optional. May be needed for cross-realm authentication where the user and service exist in different realms.
+SERVICE_HOST           Optional. May be needed to use a service host that differs from the initial role.
+====================== ===================================================================================================================================================================================================================================
+
+MONGODB-AWS
+^^^^^^^^^^^
+
+================= ====================================================================================
+Key               Value
+================= ====================================================================================
+AWS_SESSION_TOKEN Optional. An AWS session token to use for authentication with temporary credentials.
+================= ====================================================================================
+
+Deprecated Mechanism Property Options
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The following options have been deprecated and may be removed from future releases of libmongoc.
 
+========================================== ================================= ==================================================================== =======================
+Constant                                   Key                               Deprecated For                                                       Key
+========================================== ================================= ==================================================================== =======================
+MONGOC_URI_CANONICALIZEHOSTNAME            canonicalizehostname              MONGOC_URI_AUTHMECHANISMPROPERTIES (CANONICALIZE_HOST_NAME)          authmechanismproperties
+MONGOC_URI_GSSAPISERVICENAME               gssapiservicename                 MONGOC_URI_AUTHMECHANISMPROPERTIES (SERVICE_NAME)                    authmechanismproperties
+========================================== ================================= ==================================================================== =======================
 
 .. _tls_options:
 
@@ -201,9 +248,6 @@ These options govern the behavior of a :
 Constant                                   Key                               Description
 ========================================== ================================= =========================================================================================================================================================================================================================
 MONGOC_URI_MAXPOOLSIZE                     maxpoolsize                       The maximum number of clients created by a :symbol:`mongoc_client_pool_t` total (both in the pool and checked out). The default value is 100. Once it is reached, :symbol:`mongoc_client_pool_pop` blocks until another thread pushes a client.
-MONGOC_URI_MINPOOLSIZE                     minpoolsize                       Deprecated. This option's behavior does not match its name, and its actual behavior will likely hurt performance.
-MONGOC_URI_MAXIDLETIMEMS                   maxidletimems                     Not implemented.
-MONGOC_URI_WAITQUEUEMULTIPLE               waitqueuemultiple                 Not implemented.
 MONGOC_URI_WAITQUEUETIMEOUTMS              waitqueuetimeoutms                The maximum time to wait for a client to become available from the pool.
 ========================================== ================================= =========================================================================================================================================================================================================================
 
@@ -305,12 +349,9 @@ MONGOC_URI_SAFE
     mongoc_uri_get_options
     mongoc_uri_get_password
     mongoc_uri_get_read_concern
-    mongoc_uri_get_read_prefs
     mongoc_uri_get_read_prefs_t
     mongoc_uri_get_replica_set
     mongoc_uri_get_server_monitoring_mode
-    mongoc_uri_get_service
-    mongoc_uri_get_ssl
     mongoc_uri_get_string
     mongoc_uri_get_srv_hostname
     mongoc_uri_get_srv_service_name
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_get_fsync.rst 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_get_fsync.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_get_fsync.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_get_fsync.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,33 +0,0 @@
-:man_page: mongoc_write_concern_get_fsync
-
-mongoc_write_concern_get_fsync()
-================================
-
-.. warning::
-   .. deprecated:: 1.4.0
-
-      Use :symbol:`mongoc_write_concern_get_journal()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  bool
-  mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern);
-
-Parameters
-----------
-
-* ``write_concern``: A :symbol:`mongoc_write_concern_t`.
-
-Description
------------
-
-Fetches if an fsync should be performed before returning success on a write operation.
-
-Returns
--------
-
-Returns true if ``fsync`` is set as part of the write concern.
-
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_get_w.rst 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_get_w.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_get_w.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_get_w.rst	2025-06-19 15:42:22.000000000 +0000
@@ -24,5 +24,5 @@ Fetches the ``w`` parameter of the write
 Returns
 -------
 
-Returns an integer containing the w value. If wmajority is set, this would be MONGOC_WRITE_CONCERN_W_MAJORITY.
+Returns an integer containing the ``w`` value. If wmajority is set, this would be ``MONGOC_WRITE_CONCERN_W_MAJORITY``.
 
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_set_fsync.rst 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_set_fsync.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_set_fsync.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_set_fsync.rst	1970-01-01 00:00:00.000000000 +0000
@@ -1,34 +0,0 @@
-:man_page: mongoc_write_concern_set_fsync
-
-mongoc_write_concern_set_fsync()
-================================
-
-.. warning::
-   .. deprecated:: 1.4.0
-
-      Use :symbol:`mongoc_write_concern_set_journal()` instead.
-
-Synopsis
---------
-
-.. code-block:: c
-
-  void
-  mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern,
-                                  bool fsync_);
-
-Parameters
-----------
-
-* ``write_concern``: A :symbol:`mongoc_write_concern_t`.
-* ``fsync_``: A boolean.
-
-Description
------------
-
-Sets if a fsync must be performed before indicating write success.
-
-Beginning in version 1.9.0, this function can now alter the write concern after
-it has been used in an operation. Previously, using the struct with an operation
-would mark it as "frozen" and calling this function would log a warning instead
-instead of altering the write concern.
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_set_w.rst 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_set_w.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_set_w.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_set_w.rst	2025-06-19 15:42:22.000000000 +0000
@@ -15,14 +15,14 @@ Parameters
 ----------
 
 * ``write_concern``: A :symbol:`mongoc_write_concern_t`.
-* ``w``: A positive ``int32_t`` or zero.
+* ``w``: Use ``MONGOC_WRITE_CONCERN_W_DEFAULT``, ``MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED``, ``MONGOC_WRITE_CONCERN_W_MAJORITY``, or a positive integer.
 
 Description
 -----------
 
 Sets the ``w`` value for the write concern. See :symbol:`mongoc_write_concern_t` for more information on this setting.
 
-Unacknowledged writes are not causally consistent. If you execute a write operation with a :symbol:`mongoc_write_concern_t` on which you have called :symbol:`mongoc_write_concern_set_w` with a value of 0, the write does not participate in causal consistency, even when executed with a :symbol:`mongoc_client_session_t`.
+Unacknowledged writes are not causally consistent. If you execute a write operation with a :symbol:`mongoc_write_concern_t` on which you have called :symbol:`mongoc_write_concern_set_w` with a value of ``MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED``, the write does not participate in causal consistency, even when executed with a :symbol:`mongoc_client_session_t`.
 
 Beginning in version 1.9.0, this function can now alter the write concern after
 it has been used in an operation. Previously, using the struct with an operation
diff -pruN 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_t.rst 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_t.rst
--- 1.30.4-1/src/libmongoc/doc/mongoc_write_concern_t.rst	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/doc/mongoc_write_concern_t.rst	2025-06-19 15:42:22.000000000 +0000
@@ -14,11 +14,8 @@ You can specify a write concern on conne
 
 Exceptions to this principle are the generic command functions:
 
-* :symbol:`mongoc_client_command`
 * :symbol:`mongoc_client_command_simple`
-* :symbol:`mongoc_database_command`
 * :symbol:`mongoc_database_command_simple`
-* :symbol:`mongoc_collection_command`
 * :symbol:`mongoc_collection_command_simple`
 
 These generic command functions do not automatically apply a write concern, and they do not check the server response for a write concern error or write concern timeout.
@@ -37,13 +34,6 @@ MONGOC_WRITE_CONCERN_W_MAJORITY (majorit
 n                                           Block until a write has been propagated to at least ``n`` nodes in the replica set.
 ==========================================  ===============================================================================================================================================================================================================
 
-Deprecations
-------------
-
-The write concern ``MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED`` (value -1) is a deprecated synonym for ``MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED`` (value 0), and will be removed in the next major release.
-
-:symbol:`mongoc_write_concern_set_fsync` is deprecated.
-
 .. only:: html
 
   Functions
@@ -56,7 +46,6 @@ The write concern ``MONGOC_WRITE_CONCERN
     mongoc_write_concern_append
     mongoc_write_concern_copy
     mongoc_write_concern_destroy
-    mongoc_write_concern_get_fsync
     mongoc_write_concern_get_journal
     mongoc_write_concern_get_w
     mongoc_write_concern_get_wmajority
@@ -68,7 +57,6 @@ The write concern ``MONGOC_WRITE_CONCERN
     mongoc_write_concern_is_valid
     mongoc_write_concern_journal_is_set
     mongoc_write_concern_new
-    mongoc_write_concern_set_fsync
     mongoc_write_concern_set_journal
     mongoc_write_concern_set_w
     mongoc_write_concern_set_wmajority
diff -pruN 1.30.4-1/src/libmongoc/etc/mongocConfig.cmake 2.0.2-1/src/libmongoc/etc/mongocConfig.cmake
--- 1.30.4-1/src/libmongoc/etc/mongocConfig.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/etc/mongocConfig.cmake	1970-01-01 00:00:00.000000000 +0000
@@ -1,67 +0,0 @@
-#[[
-    This is a transitional CMake package config file to allow compatibility
-    between libmongoc 1.x and libmongoc 2.x CMake packages.
-
-    When distributed with libmongoc 1.x, this file is mostly just a shim for
-    the `mongoc-1.0` CMake packages.
-
-    This file imports "mongoc-1.0" and generates alias targets for it:
-
-    • `mongoc::shared` → `mongo::mongoc_shared`
-    • `mongoc::static` → `mongo::mongoc_static`
-    • `mongoc::mongoc` → Points to either `mongoc::shared` or `mongoc::static`,
-        controlled by `MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE`
-]]
-
-# Check for missing components before proceeding. We don't provide any, so we
-# should generate an error if the caller requests any *required* components.
-set(missing_required_components)
-foreach(comp IN LISTS mongoc_FIND_COMPONENTS)
-    if(mongoc_FIND_REQUIRED_${comp})
-        list(APPEND missing_required_components "${comp}")
-    endif()
-endforeach()
-
-if(missing_required_components)
-    list(JOIN missing_required_components ", " components)
-    set(mongoc_FOUND FALSE)
-    set(mongoc_NOT_FOUND_MESSAGE "The package version is compatible, but is missing required components: ${components}")
-    # Stop now. Don't generate any imported targets
-    return()
-endif()
-
-include(CMakeFindDependencyMacro)
-
-# We are installed alongside the `mongoc-1.0` packages. Forcibly prevent find_package
-# from considering any other `mongoc-1.0` package that might live elsewhere on the system
-# by setting HINTS and NO_DEFAULT_PATH
-get_filename_component(parent_dir "${CMAKE_CURRENT_LIST_DIR}" DIRECTORY)
-find_dependency(mongoc-1.0 HINTS ${parent_dir} NO_DEFAULT_PATH)
-# Also import the `bson` package, to ensure its targets are also available
-find_dependency(bson ${mongoc_FIND_VERSION} HINTS ${parent_dir} NO_DEFAULT_PATH)
-
-# The library type that is linked with `mongoc::mongoc`
-set(_default_lib_type)
-# Add compat targets for the mongoc-1.0 package targets
-if(TARGET mongo::mongoc_shared AND NOT TARGET mongoc::shared)
-    add_library(mongoc::shared IMPORTED INTERFACE)
-    set_property(TARGET mongoc::shared APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongo::mongoc_shared)
-    set(_default_lib_type SHARED)
-endif()
-if(TARGET mongo::mongoc_static AND NOT TARGET mongoc::static)
-    add_library(mongoc::static IMPORTED INTERFACE)
-    set_property(TARGET mongoc::static APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongo::mongoc_static)
-    # If static is available, set it as the default library type
-    set(_default_lib_type STATIC)
-endif()
-
-# Allow the user to tweak what library type is linked for `mongoc::mongoc`
-set(MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE "${_default_lib_type}"
-    CACHE STRING "The default library type that is used when linking against 'mongoc::mongoc' (either SHARED or STATIC, requires that the package was built with the appropriate library type)")
-set_property(CACHE MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE PROPERTY STRINGS SHARED STATIC)
-
-if(NOT TARGET mongoc::mongoc)  # Don't redefine the target if we were already included
-    string(TOLOWER "${MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE}" _type)
-    add_library(mongoc::mongoc IMPORTED INTERFACE)
-    set_property(TARGET mongoc::mongoc APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongoc::${_type})
-endif()
diff -pruN 1.30.4-1/src/libmongoc/etc/mongocConfig.cmake.in 2.0.2-1/src/libmongoc/etc/mongocConfig.cmake.in
--- 1.30.4-1/src/libmongoc/etc/mongocConfig.cmake.in	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/etc/mongocConfig.cmake.in	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,112 @@
+#[[
+    CMake package file for the mongoc library.
+
+    This file globs and includes all "*-targets.cmake" files in the containing
+    directory, and intends that those files define the actual mongoc targets.
+
+    This file also defines a `mongoc::mongoc` target, which redirects to either
+    `mongoc::static` or `mongoc::shared` depending on what type of library is
+    available and can be controlled with an import-time CMake setting.
+
+    If the installation has a static library, it is named `mongoc::static`. If
+    the installation has a shared (dynamic) library, it is named `mongoc::shared`.
+]]
+
+# The version of the mongoc package (comes from the project() call in the orginal project)
+set(__mongoc_package_version [[@PROJECT_VERSION@]])
+set(__mongoc_sasl_backend [[@SASL_BACKEND@]])
+set(__mongoc_tls_package [[@TLS_IMPORT_PACKAGE@]])
+set(__mongoc_uses_bundled_utf8proc "@USE_BUNDLED_UTF8PROC@")
+# Announce this one as a public var:
+set(MONGOC_TLS_BACKEND [[@TLS_BACKEND@]])
+
+# Check for missing components before proceeding. We don't provide any, so we
+# should generate an error if the caller requests any *required* components.
+set(missing_required_components)
+foreach(comp IN LISTS mongoc_FIND_COMPONENTS)
+    if(mongoc_FIND_REQUIRED_${comp})
+        list(APPEND missing_required_components "${comp}")
+    endif()
+endforeach()
+
+if(missing_required_components)
+    list(JOIN missing_required_components ", " components)
+    set(mongoc_FOUND FALSE)
+    set(mongoc_NOT_FOUND_MESSAGE "The package version is compatible, but is missing required components: ${components}")
+    # Stop now. Don't generate any imported targets
+    return()
+endif()
+
+# d8888b. d88888b d8888b. d88888b d8b   db d8888b. d88888b d8b   db  .o88b. d888888b d88888b .d8888.
+# 88  `8D 88'     88  `8D 88'     888o  88 88  `8D 88'     888o  88 d8P  Y8   `88'   88'     88'  YP
+# 88   88 88ooooo 88oodD' 88ooooo 88V8o 88 88   88 88ooooo 88V8o 88 8P         88    88ooooo `8bo.
+# 88   88 88~~~~~ 88~~~   88~~~~~ 88 V8o88 88   88 88~~~~~ 88 V8o88 8b         88    88~~~~~   `Y8b.
+# 88  .8D 88.     88      88.     88  V888 88  .8D 88.     88  V888 Y8b  d8   .88.   88.     db   8D
+# Y8888D' Y88888P 88      Y88888P VP   V8P Y8888D' Y88888P VP   V8P  `Y88P' Y888888P Y88888P `8888Y'
+# Import dependencies
+include(CMakeFindDependencyMacro)
+get_filename_component(__parent_dir "${CMAKE_CURRENT_LIST_DIR}" DIRECTORY)
+# Also import the `bson` package, to ensure its targets are also available
+find_dependency(bson "${__mongoc_package_version}" HINTS ${__parent_dir})
+
+# QUIET arg for finding dependencies:
+unset(__quiet)
+if(${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY)
+  set(__quiet QUIET)
+endif()
+
+# Find libutf8proc (if we linked to an external library)
+if(NOT __mongoc_uses_bundled_utf8proc AND NOT TARGET PkgConfig::PC_UTF8PROC)
+    # libmongoc was compiled against an external utf8proc and links against a
+    # FindPkgConfig-generated IMPORTED target. Find that package and generate that
+    # imported target here:
+    find_dependency(PkgConfig)
+    pkg_check_modules(PC_UTF8PROC ${__quiet} libutf8proc IMPORTED_TARGET GLOBAL)
+    if(NOT PC_UTF8PROC_FOUND)
+        # Handle if it wasn't found (find_dependency would usually do this for us,
+        # but pkg_check_modules() does not)
+        set(mongoc_FOUND FALSE)
+        set(mongoc_NOT_FOUND_MESSAGE "We were unable to find the required libutf8proc package with pkg-config")
+        return()
+    endif()
+endif()
+
+# If we need to import a TLS package for our imported targets, do that now:
+if(__mongoc_tls_package)
+    find_dependency("${__mongoc_tls_package}")
+endif()
+
+# Find dependencies for SASL
+if(__mongoc_sasl_backend STREQUAL "Cyrus")
+    # We need libsasl2. The find-module should be installed within this package.
+    # temporarily place it on the module search path:
+    set(__prev_path "${CMAKE_MODULE_PATH}")
+    list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/3rdParty")
+    find_dependency(SASL2 2.0)
+    set(CMAKE_MODULE_PATH "${__prev_path}")
+endif()
+
+# Import the target files that will be installed alongside this file. Only the
+# targets of libraries that were actually installed alongside this file will be imported
+file(GLOB __targets_files "${CMAKE_CURRENT_LIST_DIR}/*-targets.cmake")
+foreach(__file IN LISTS __targets_files)
+    include("${__file}")
+endforeach()
+
+# The library type that is linked with `mongoc::mongoc`
+set(__default_lib_type SHARED)
+if(TARGET mongoc::static)
+    # If static is available, set it as the default library type
+    set(__default_lib_type STATIC)
+endif()
+
+# Allow the user to tweak what library type is linked for `mongoc::mongoc`
+set(MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE "${__default_lib_type}"
+    CACHE STRING "The default library type that is used when linking against 'mongoc::mongoc' (either SHARED or STATIC, requires that the package was built with the appropriate library type)")
+set_property(CACHE MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE PROPERTY STRINGS SHARED STATIC)
+
+if(NOT TARGET mongoc::mongoc)  # Don't redefine the target if we were already included
+    string(TOLOWER "${MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE}" __type)
+    add_library(mongoc::mongoc IMPORTED INTERFACE)
+    set_property(TARGET mongoc::mongoc APPEND PROPERTY INTERFACE_LINK_LIBRARIES mongoc::${__type})
+endif()
diff -pruN 1.30.4-1/src/libmongoc/examples/client-side-encryption-helpers.c 2.0.2-1/src/libmongoc/examples/client-side-encryption-helpers.c
--- 1.30.4-1/src/libmongoc/examples/client-side-encryption-helpers.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/client-side-encryption-helpers.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,7 +15,7 @@ hex_to_bin (const char *hex, uint32_t *l
 
    size_t num_bytes = hex_len / 2u;
    if (num_bytes >= UINT32_MAX) {
-      return false;
+      return NULL;
    }
 
    *len = (uint32_t) (hex_len / 2u);
diff -pruN 1.30.4-1/src/libmongoc/examples/cmake/find_package/CMakeLists.txt 2.0.2-1/src/libmongoc/examples/cmake/find_package/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/examples/cmake/find_package/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/cmake/find_package/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@ project (hello_mongoc LANGUAGES C)
 # building libmongoc.
 # -- sphinx-include-start --
 # Specify the minimum version you require.
-find_package (mongoc 1.7 REQUIRED)
+find_package (mongoc 2.0 REQUIRED)
 
 # The "hello_mongoc.c" sample program is shared among four tests.
 add_executable (hello_mongoc ../../hello_mongoc.c)
diff -pruN 1.30.4-1/src/libmongoc/examples/cmake/find_package_static/CMakeLists.txt 2.0.2-1/src/libmongoc/examples/cmake/find_package_static/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/examples/cmake/find_package_static/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/cmake/find_package_static/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@ project (hello_mongoc LANGUAGES C)
 # building libmongoc.
 # -- sphinx-include-start --
 # Specify the minimum version you require.
-find_package (mongoc 1.7 REQUIRED)
+find_package (mongoc 2.0 REQUIRED)
 
 # The "hello_mongoc.c" sample program is shared among four tests.
 add_executable (hello_mongoc ../../hello_mongoc.c)
diff -pruN 1.30.4-1/src/libmongoc/examples/cmake-deprecated/find_package/CMakeLists.txt 2.0.2-1/src/libmongoc/examples/cmake-deprecated/find_package/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/examples/cmake-deprecated/find_package/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/cmake-deprecated/find_package/CMakeLists.txt	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Demonstrates how to use the CMake 'find_package' mechanism to locate
-# and build against libmongoc.
-
-cmake_minimum_required (VERSION 2.8)
-
-project (hello_mongoc LANGUAGES C)
-
-# NOTE: For this to work, the CMAKE_PREFIX_PATH variable must be set to point to
-# the directory that was used as the argument to CMAKE_INSTALL_PREFIX when
-# building libmongoc.
-# -- sphinx-include-start --
-# Specify the minimum version you require.
-find_package (libmongoc-1.0 1.7 REQUIRED)
-
-message (STATUS "   mongoc found version \"${MONGOC_VERSION}\"")
-message (STATUS "   mongoc include path \"${MONGOC_INCLUDE_DIRS}\"")
-message (STATUS "   mongoc libraries \"${MONGOC_LIBRARIES}\"")
-
-# The "hello_mongoc.c" sample program is shared among four tests.
-add_executable (hello_mongoc ../../hello_mongoc.c)
-target_include_directories (hello_mongoc PRIVATE "${MONGOC_INCLUDE_DIRS}")
-target_link_libraries (hello_mongoc PRIVATE "${MONGOC_LIBRARIES}")
-target_compile_definitions (hello_mongoc PRIVATE "${MONGOC_DEFINITIONS}")
diff -pruN 1.30.4-1/src/libmongoc/examples/cmake-deprecated/find_package_static/CMakeLists.txt 2.0.2-1/src/libmongoc/examples/cmake-deprecated/find_package_static/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/examples/cmake-deprecated/find_package_static/CMakeLists.txt	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/cmake-deprecated/find_package_static/CMakeLists.txt	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-# Copyright 2009-present MongoDB, Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Demonstrates how to use the CMake 'find_package' mechanism to locate
-# and build against libmongoc.
-
-cmake_minimum_required (VERSION 2.8)
-
-project (hello_mongoc LANGUAGES C)
-
-# NOTE: For this to work, the CMAKE_PREFIX_PATH variable must be set to point to
-# the directory that was used as the argument to CMAKE_INSTALL_PREFIX when
-# building libmongoc.
-# -- sphinx-include-start --
-# Specify the minimum version you require.
-find_package (libmongoc-static-1.0 1.7 REQUIRED)
-
-message (STATUS "   mongoc found version \"${MONGOC_STATIC_VERSION}\"")
-message (STATUS "   mongoc include path \"${MONGOC_STATIC_INCLUDE_DIRS}\"")
-message (STATUS "   mongoc libraries \"${MONGOC_STATIC_LIBRARIES}\"")
-
-# The "hello_mongoc.c" sample program is shared among four tests.
-add_executable (hello_mongoc ../../hello_mongoc.c)
-target_include_directories (hello_mongoc PRIVATE "${MONGOC_STATIC_INCLUDE_DIRS}")
-target_link_libraries (hello_mongoc PRIVATE "${MONGOC_STATIC_LIBRARIES}")
-target_compile_definitions (hello_mongoc PRIVATE "${MONGOC_STATIC_DEFINITIONS}")
diff -pruN 1.30.4-1/src/libmongoc/examples/compile-with-pkg-config-static.sh 2.0.2-1/src/libmongoc/examples/compile-with-pkg-config-static.sh
--- 1.30.4-1/src/libmongoc/examples/compile-with-pkg-config-static.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/compile-with-pkg-config-static.sh	2025-06-19 15:42:22.000000000 +0000
@@ -1,4 +1,4 @@
 #!/usr/bin/env bash
 
 # -- sphinx-include-start --
-gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)
+gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags mongoc$major-static)
diff -pruN 1.30.4-1/src/libmongoc/examples/compile-with-pkg-config.sh 2.0.2-1/src/libmongoc/examples/compile-with-pkg-config.sh
--- 1.30.4-1/src/libmongoc/examples/compile-with-pkg-config.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/compile-with-pkg-config.sh	2025-06-19 15:42:22.000000000 +0000
@@ -1,4 +1,4 @@
 #!/usr/bin/env bash
 
 # -- sphinx-include-start --
-gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)
+gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags mongoc$major)
diff -pruN 1.30.4-1/src/libmongoc/examples/example-gridfs.c 2.0.2-1/src/libmongoc/examples/example-gridfs.c
--- 1.30.4-1/src/libmongoc/examples/example-gridfs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/example-gridfs.c	2025-06-19 15:42:22.000000000 +0000
@@ -78,7 +78,7 @@ main (int argc, char *argv[])
             break;
          }
 
-         if (fwrite (iov.iov_base, 1, r, stdout) != r) {
+         if (fwrite (iov.iov_base, 1, r, stdout) != (size_t) r) {
             MONGOC_ERROR ("Failed to write to stdout. Exiting.\n");
             exit (1);
          }
diff -pruN 1.30.4-1/src/libmongoc/examples/example-resume.c 2.0.2-1/src/libmongoc/examples/example-resume.c
--- 1.30.4-1/src/libmongoc/examples/example-resume.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/example-resume.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,6 @@ _save_resume_token (const bson_t *doc)
    bson_t resume_token_doc;
    char *as_json = NULL;
    size_t as_json_len;
-   ssize_t r, n_written;
    const bson_value_t *resume_token;
 
    if (!bson_iter_init_find (&iter, doc, "_id")) {
@@ -39,9 +38,9 @@ _save_resume_token (const bson_t *doc)
    BSON_APPEND_VALUE (&resume_token_doc, "resumeAfter", resume_token);
    as_json = bson_as_canonical_extended_json (&resume_token_doc, &as_json_len);
    bson_destroy (&resume_token_doc);
-   n_written = 0;
+   size_t n_written = 0;
    while (n_written < as_json_len) {
-      r = fwrite ((void *) (as_json + n_written), sizeof (char), as_json_len - n_written, file_stream);
+      ssize_t r = fwrite ((void *) (as_json + n_written), sizeof (char), as_json_len - n_written, file_stream);
       if (r == -1) {
          fprintf (stderr, "failed to write to %s\n", RESUME_TOKEN_PATH);
          bson_free (as_json);
diff -pruN 1.30.4-1/src/libmongoc/examples/example-structured-log.c 2.0.2-1/src/libmongoc/examples/example-structured-log.c
--- 1.30.4-1/src/libmongoc/examples/example-structured-log.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/example-structured-log.c	2025-06-19 15:42:22.000000000 +0000
@@ -11,6 +11,8 @@ static pthread_mutex_t handler_mutex;
 static void
 example_handler (const mongoc_structured_log_entry_t *entry, void *user_data)
 {
+   (void) user_data;
+
    mongoc_structured_log_component_t component = mongoc_structured_log_entry_get_component (entry);
    mongoc_structured_log_level_t level = mongoc_structured_log_entry_get_level (entry);
    const char *message_string = mongoc_structured_log_entry_get_message_string (entry);
diff -pruN 1.30.4-1/src/libmongoc/examples/migrating.c 2.0.2-1/src/libmongoc/examples/migrating.c
--- 1.30.4-1/src/libmongoc/examples/migrating.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/migrating.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,201 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc.h>
-
-// `migrating.c` shows examples of migrating from deprecated API to alternatives.
-
-#define FAIL(...)                                                       \
-   if (1) {                                                             \
-      fprintf (stderr, "[%s:%d] failed: ", __FILE__, (int) (__LINE__)); \
-      fprintf (stderr, __VA_ARGS__);                                    \
-      fprintf (stderr, "\n");                                           \
-      abort ();                                                         \
-   } else                                                               \
-      (void) 0
-
-
-#define EXPECT(Cond)                           \
-   if (1) {                                    \
-      if (!(Cond)) {                           \
-         FAIL ("condition failed: %s", #Cond); \
-      }                                        \
-   } else                                      \
-      (void) 0
-
-int
-main (void)
-{
-   mongoc_init ();
-
-   mongoc_client_t *client = mongoc_client_new ("mongodb://localhost:27017");
-   mongoc_database_t *db = mongoc_client_get_database (client, "db");
-   mongoc_collection_t *coll = mongoc_database_get_collection (db, "coll");
-
-   {
-      // mongoc_client_command ... before ... begin
-      const bson_t *reply;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      mongoc_cursor_t *cursor = mongoc_client_command (client,
-                                                       "db",
-                                                       MONGOC_QUERY_NONE /* unused */,
-                                                       0 /* unused */,
-                                                       0 /* unused */,
-                                                       0 /* unused */,
-                                                       cmd,
-                                                       NULL /* unused */,
-                                                       NULL /* read prefs */);
-      // Expect cursor to return exactly one document for the command reply.
-      EXPECT (mongoc_cursor_next (cursor, &reply));
-
-      bson_error_t error;
-      if (mongoc_cursor_error (cursor, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      // Expect cursor to return no other documents.
-      EXPECT (!mongoc_cursor_next (cursor, &reply));
-      mongoc_cursor_destroy (cursor);
-      bson_destroy (cmd);
-      // mongoc_client_command ... before ... end
-   }
-
-   {
-      // mongoc_client_command ... after ... begin
-      bson_t reply;
-      bson_error_t error;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      if (!mongoc_client_command_simple (client, "db", cmd, NULL /* read prefs */, &reply, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, &reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      bson_destroy (&reply);
-      bson_destroy (cmd);
-      // mongoc_client_command ... after ... end
-   }
-
-   {
-      // mongoc_database_command ... before ... begin
-      const bson_t *reply;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      mongoc_cursor_t *cursor = mongoc_database_command (db,
-                                                         MONGOC_QUERY_NONE /* unused */,
-                                                         0 /* unused */,
-                                                         0 /* unused */,
-                                                         0 /* unused */,
-                                                         cmd,
-                                                         NULL /* unused */,
-                                                         NULL /* read prefs */);
-      // Expect cursor to return exactly one document for the command reply.
-      EXPECT (mongoc_cursor_next (cursor, &reply));
-
-      bson_error_t error;
-      if (mongoc_cursor_error (cursor, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      // Expect cursor to return no other documents.
-      EXPECT (!mongoc_cursor_next (cursor, &reply));
-      mongoc_cursor_destroy (cursor);
-      bson_destroy (cmd);
-      // mongoc_database_command ... before ... end
-   }
-
-   {
-      // mongoc_database_command ... after ... begin
-      bson_t reply;
-      bson_error_t error;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      if (!mongoc_database_command_simple (db, cmd, NULL /* read prefs */, &reply, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, &reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      bson_destroy (&reply);
-      bson_destroy (cmd);
-      // mongoc_database_command ... after ... end
-   }
-
-   {
-      // mongoc_collection_command ... before ... begin
-      const bson_t *reply;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      mongoc_cursor_t *cursor = mongoc_collection_command (coll,
-                                                           MONGOC_QUERY_NONE /* unused */,
-                                                           0 /* unused */,
-                                                           0 /* unused */,
-                                                           0 /* unused */,
-                                                           cmd,
-                                                           NULL /* unused */,
-                                                           NULL /* read prefs */);
-      // Expect cursor to return exactly one document for the command reply.
-      EXPECT (mongoc_cursor_next (cursor, &reply));
-
-      bson_error_t error;
-      if (mongoc_cursor_error (cursor, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      // Expect cursor to return no other documents.
-      EXPECT (!mongoc_cursor_next (cursor, &reply));
-      mongoc_cursor_destroy (cursor);
-      bson_destroy (cmd);
-      // mongoc_collection_command ... before ... end
-   }
-
-   {
-      // mongoc_collection_command ... after ... begin
-      bson_t reply;
-      bson_error_t error;
-      bson_t *cmd = BCON_NEW ("find", "foo", "filter", "{", "}");
-      if (!mongoc_collection_command_simple (coll, cmd, NULL /* read prefs */, &reply, &error)) {
-         FAIL ("Expected no error, got: %s\n", error.message);
-      }
-
-      // Expect successful reply to contain "ok": 1
-      bson_iter_t iter;
-      EXPECT (bson_iter_init_find (&iter, &reply, "ok") && bson_iter_as_int64 (&iter) == 1);
-
-      bson_destroy (&reply);
-      bson_destroy (cmd);
-      // mongoc_collection_command ... after ... end
-   }
-
-   mongoc_collection_destroy (coll);
-   mongoc_database_destroy (db);
-   mongoc_client_destroy (client);
-
-   mongoc_cleanup ();
-}
diff -pruN 1.30.4-1/src/libmongoc/examples/parse_handshake_cfg.py 2.0.2-1/src/libmongoc/examples/parse_handshake_cfg.py
--- 1.30.4-1/src/libmongoc/examples/parse_handshake_cfg.py	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/examples/parse_handshake_cfg.py	2025-06-19 15:42:22.000000000 +0000
@@ -16,8 +16,8 @@ MD_FLAGS = {
     "MONGOC_MD_FLAG_EXPERIMENTAL_FEATURES": 10,
     "MONGOC_MD_FLAG_HAVE_SASL_CLIENT_DONE": 11,
     "MONGOC_MD_FLAG_HAVE_WEAK_SYMBOLS": 12,
-    "MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS": 13,
-    "MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL": 14,
+    "MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS": 13, # Removed in CDRIVER-1330.
+    "MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL": 14, # Removed in CDRIVER-5693.
     "MONGOC_MD_FLAG_ENABLE_SASL_CYRUS": 15,
     "MONGOC_MD_FLAG_ENABLE_SASL_SSPI": 16,
     "MONGOC_MD_FLAG_HAVE_SOCKLEN": 17,
diff -pruN 1.30.4-1/src/libmongoc/libmongoc.rc.in 2.0.2-1/src/libmongoc/libmongoc.rc.in
--- 1.30.4-1/src/libmongoc/libmongoc.rc.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/libmongoc.rc.in	2025-06-19 15:42:22.000000000 +0000
@@ -5,7 +5,6 @@
 #include <mongoc/mongoc-version.h> // Defines MONGOC_MAJOR_VERSION and other version macros.
 
 #define MONGOC_OUTPUT_BASENAME "@MONGOC_OUTPUT_BASENAME@"
-#define MONGOC_API_VERSION "@MONGOC_API_VERSION@"
 
 VS_VERSION_INFO VERSIONINFO
  FILEVERSION MONGOC_MAJOR_VERSION,MONGOC_MINOR_VERSION,MONGOC_MICRO_VERSION,0
@@ -30,8 +29,8 @@ BEGIN
             VALUE "CompanyName", "MongoDB, Inc"
             VALUE "FileDescription", "MongoDB Client Library for C"
             VALUE "FileVersion", MONGOC_VERSION_S
-            VALUE "InternalName", MONGOC_OUTPUT_BASENAME "-" MONGOC_API_VERSION
-            VALUE "OriginalFilename", MONGOC_OUTPUT_BASENAME "-" MONGOC_API_VERSION ".dll"
+            VALUE "InternalName", MONGOC_OUTPUT_BASENAME "@PROJECT_VERSION_MAJOR@"
+            VALUE "OriginalFilename", MONGOC_OUTPUT_BASENAME "@PROJECT_VERSION_MAJOR@.dll"
             VALUE "ProductName", "MongoDB C Driver"
             VALUE "ProductVersion", MONGOC_VERSION_S
             VALUE "LegalCopyright", "Copyright 2009-present MongoDB, Inc."
diff -pruN 1.30.4-1/src/libmongoc/src/libmongoc-ssl-1.0.pc.in 2.0.2-1/src/libmongoc/src/libmongoc-ssl-1.0.pc.in
--- 1.30.4-1/src/libmongoc/src/libmongoc-ssl-1.0.pc.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/libmongoc-ssl-1.0.pc.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,11 +0,0 @@
-prefix=@prefix@
-exec_prefix=${prefix}
-libdir=@libdir@
-includedir=${exec_prefix}/include
-
-Name: libmongoc-@MONGOC_API_VERSION@
-Description: SSL support for the libmongoc-@MONGOC_API_VERSION@ library.
-Version: @MONGOC_VERSION@
-Requires: libmongoc-1.0
-Libs:
-Cflags:
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/forwarding/mongoc.h 2.0.2-1/src/libmongoc/src/mongoc/forwarding/mongoc.h
--- 1.30.4-1/src/libmongoc/src/mongoc/forwarding/mongoc.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/forwarding/mongoc.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,18 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Including mongoc.h is superseded. Use mongoc/mongoc.h instead. */
-#include <mongoc/mongoc.h>
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mcd-azure.c 2.0.2-1/src/libmongoc/src/mongoc/mcd-azure.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mcd-azure.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mcd-azure.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,8 +16,9 @@
 
 #include <mongoc/mcd-azure.h>
 
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #define AZURE_API_VERSION "2018-02-01"
 
@@ -103,12 +104,12 @@ mcd_azure_access_token_try_init_from_jso
    const char *const expires_in_str = !found ? NULL : bson_iter_utf8 (&iter, &expires_in_len);
 
    if (!(access_token && resource && token_type && expires_in_str)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_AZURE,
-                      MONGOC_ERROR_KMS_SERVER_BAD_JSON,
-                      "One or more required JSON properties are missing/invalid: data: %.*s",
-                      len,
-                      json);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_AZURE,
+                         MONGOC_ERROR_KMS_SERVER_BAD_JSON,
+                         "One or more required JSON properties are missing/invalid: data: %.*s",
+                         len,
+                         json);
    } else {
       // Set the output, duplicate each string
       *out = (mcd_azure_access_token){
@@ -123,12 +124,12 @@ mcd_azure_access_token_try_init_from_jso
       long long s = strtoll (expires_in_str, &parse_end, 0);
       if (parse_end != expires_in_str + expires_in_len) {
          // Did not parse the entire string. Bad
-         bson_set_error (error,
-                         MONGOC_ERROR_AZURE,
-                         MONGOC_ERROR_KMS_SERVER_BAD_JSON,
-                         "Invalid 'expires_in' string \"%.*s\" from IMDS server",
-                         mcommon_in_range_unsigned (int, expires_in_len) ? (int) expires_in_len : INT_MAX,
-                         expires_in_str);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_AZURE,
+                            MONGOC_ERROR_KMS_SERVER_BAD_JSON,
+                            "Invalid 'expires_in' string \"%.*s\" from IMDS server",
+                            mlib_in_range (int, expires_in_len) ? (int) expires_in_len : INT_MAX,
+                            expires_in_str);
       } else {
          out->expires_in = mcd_seconds (s);
          okay = true;
@@ -178,13 +179,13 @@ mcd_azure_access_token_from_imds (mcd_az
 
    // We only accept an HTTP 200 as a success
    if (resp.status != 200) {
-      bson_set_error (error,
-                      MONGOC_ERROR_AZURE,
-                      MONGOC_ERROR_KMS_SERVER_HTTP,
-                      "Error from Azure IMDS server while looking for "
-                      "Managed Identity access token: %.*s",
-                      resp.body_len,
-                      resp.body);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_AZURE,
+                         MONGOC_ERROR_KMS_SERVER_HTTP,
+                         "Error from Azure IMDS server while looking for "
+                         "Managed Identity access token: %.*s",
+                         resp.body_len,
+                         resp.body);
       goto fail;
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mcd-nsinfo.c 2.0.2-1/src/libmongoc/src/mongoc/mcd-nsinfo.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mcd-nsinfo.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mcd-nsinfo.c	2025-06-19 15:42:22.000000000 +0000
@@ -17,7 +17,7 @@
 #include <mongoc/mcd-nsinfo.h>
 
 #include <mongoc/mongoc-buffer-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/uthash.h>
 
 typedef struct {
@@ -67,11 +67,11 @@ mcd_nsinfo_append (mcd_nsinfo_t *self, c
 
    const int32_t ns_index = self->count;
    if (self->count == INT32_MAX) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Only %" PRId32 " distinct collections may be used",
-                      INT32_MAX);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Only %" PRId32 " distinct collections may be used",
+                         INT32_MAX);
       return -1;
    }
    self->count++;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mcd-rpc.c 2.0.2-1/src/libmongoc/src/mongoc/mcd-rpc.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mcd-rpc.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mcd-rpc.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,3 +1,4 @@
+#include <mlib/intencode.h>
 #include <mongoc/mcd-rpc.h>
 
 // Header-only dependency. Does NOT require linking with libmongoc.
@@ -6,7 +7,7 @@
 #undef MONGOC_INSIDE
 
 #include <bson/bson.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 typedef struct _mcd_rpc_message_header mcd_rpc_message_header;
@@ -175,15 +176,6 @@ union _mcd_rpc_message {
    } else                                                \
       (void) 0
 
-
-static int32_t
-_int32_from_le (const void *data)
-{
-   BSON_ASSERT_PARAM (data);
-   return bson_iter_int32_unsafe (&(bson_iter_t){.raw = data});
-}
-
-
 // In addition to validating expected size against remaining bytes, ensure
 // proper conversion from little endian format.
 #define MONGOC_RPC_CONSUME(type, raw_type, from_le)                                         \
@@ -282,8 +274,7 @@ _consume_bson_objects (const uint8_t **p
          return false;
       }
 
-      if (doc_len < MONGOC_RPC_MINIMUM_BSON_LENGTH ||
-          mcommon_cmp_greater_su (doc_len, *remaining_bytes + sizeof (int32_t))) {
+      if (doc_len < MONGOC_RPC_MINIMUM_BSON_LENGTH || mlib_cmp (doc_len, >, *remaining_bytes + sizeof (int32_t))) {
          *ptr -= sizeof (int32_t); // Revert so *data_end points to start of
                                    // document as invalid input.
          return false;
@@ -365,7 +356,7 @@ _consume_op_msg_section (
 
    switch (section.kind) {
    case 0: { // Body
-      section.payload.body.section_len = _int32_from_le (*ptr);
+      section.payload.body.section_len = mlib_read_i32le (*ptr);
       section.payload.body.bson = *ptr;
 
       int32_t num_parsed = 0;
@@ -386,7 +377,7 @@ _consume_op_msg_section (
       // identifier field, but 4 bytes is sufficient to avoid unsigned integer
       // overflow when computing `remaining_section_bytes` and to encourage as
       // much progress is made parsing input data as able.
-      if (mcommon_cmp_less_su (section.payload.document_sequence.section_len, sizeof (int32_t))) {
+      if (mlib_cmp (section.payload.document_sequence.section_len, <, sizeof (int32_t))) {
          *ptr -= sizeof (int32_t); // Revert so *data_end points to start of
                                    // document sequence as invalid input.
          return false;
@@ -786,7 +777,7 @@ _consume_op_kill_cursors (mcd_rpc_messag
    if (op_kill_cursors->number_of_cursor_ids < 0 ||
        // Truncation may (deliberately) leave unparsed bytes that will later
        // trigger validation failure due to unexpected remaining bytes.
-       mcommon_cmp_greater_su (op_kill_cursors->number_of_cursor_ids, *remaining_bytes / sizeof (int64_t))) {
+       mlib_cmp (op_kill_cursors->number_of_cursor_ids, >, *remaining_bytes / sizeof (int64_t))) {
       *ptr -= sizeof (int32_t); // Revert so *data_len points to start of
                                 // numberOfCursorIds as invalid input.
       return false;
@@ -852,7 +843,7 @@ mcd_rpc_message_from_data_in_place (mcd_
    }
 
    if (rpc->msg_header.message_length < MONGOC_RPC_MINIMUM_MESSAGE_LENGTH ||
-       mcommon_cmp_greater_su (rpc->msg_header.message_length, remaining_bytes + sizeof (int32_t))) {
+       mlib_cmp (rpc->msg_header.message_length, >, remaining_bytes + sizeof (int32_t))) {
       ptr -= sizeof (int32_t); // Revert so *data_end points to start of
                                // messageLength as invalid input.
       goto fail;
@@ -1245,12 +1236,11 @@ _append_iovec_op_update (mongoc_iovec_t
       return false;
    }
 
-   if (!_append_iovec_data (
-          *iovecs, capacity, count, op_update->selector, (size_t) _int32_from_le (op_update->selector))) {
+   if (!_append_iovec_data (*iovecs, capacity, count, op_update->selector, mlib_read_u32le (op_update->selector))) {
       return false;
    }
 
-   if (!_append_iovec_data (*iovecs, capacity, count, op_update->update, (size_t) _int32_from_le (op_update->update))) {
+   if (!_append_iovec_data (*iovecs, capacity, count, op_update->update, mlib_read_u32le (op_update->update))) {
       return false;
    }
 
@@ -1322,7 +1312,7 @@ _append_iovec_op_query (mongoc_iovec_t *
       return false;
    }
 
-   if (!_append_iovec_data (*iovecs, capacity, count, op_query->query, (size_t) _int32_from_le (op_query->query))) {
+   if (!_append_iovec_data (*iovecs, capacity, count, op_query->query, mlib_read_u32le (op_query->query))) {
       return false;
    }
 
@@ -1331,7 +1321,7 @@ _append_iovec_op_query (mongoc_iovec_t *
                                capacity,
                                count,
                                op_query->return_fields_selector,
-                               (size_t) _int32_from_le (op_query->return_fields_selector))) {
+                               mlib_read_u32le (op_query->return_fields_selector))) {
          return false;
       }
    }
@@ -1402,8 +1392,7 @@ _append_iovec_op_delete (mongoc_iovec_t
       return false;
    }
 
-   if (!_append_iovec_data (
-          *iovecs, capacity, count, op_delete->selector, (size_t) _int32_from_le (op_delete->selector))) {
+   if (!_append_iovec_data (*iovecs, capacity, count, op_delete->selector, mlib_read_u32le (op_delete->selector))) {
       return false;
    }
 
@@ -1580,7 +1569,7 @@ _mcd_rpc_header_get_op_code_maybe_le (co
 
    default:
       // May be in little endian.
-      op_code = _int32_from_le (&op_code);
+      op_code = mlib_read_i32le (&op_code);
 
       switch (op_code) {
       case MONGOC_OP_CODE_COMPRESSED:
@@ -1800,7 +1789,7 @@ mcd_rpc_op_compressed_set_compressed_mes
 {
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_COMPRESSED);
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, compressed_message_length));
+   BSON_ASSERT (mlib_in_range (int32_t, compressed_message_length));
    rpc->op_compressed.compressed_message = compressed_message;
    rpc->op_compressed.compressed_message_len = compressed_message_length;
    return (int32_t) compressed_message_length;
@@ -1827,7 +1816,7 @@ mcd_rpc_op_msg_section_get_length (const
 
    switch (section->kind) {
    case 0: { // Body
-      return _int32_from_le (section->payload.body.bson);
+      return mlib_read_i32le (section->payload.body.bson);
    }
 
    case 1: { // Document Sequence
@@ -1921,7 +1910,7 @@ mcd_rpc_op_msg_section_set_identifier (m
    rpc->op_msg.sections[index].payload.document_sequence.identifier = identifier;
    rpc->op_msg.sections[index].payload.document_sequence.identifier_len = identifier_len;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, identifier_len));
+   BSON_ASSERT (mlib_in_range (int32_t, identifier_len));
    return (int32_t) identifier_len;
 }
 
@@ -1933,7 +1922,7 @@ mcd_rpc_op_msg_section_set_body (mcd_rpc
    BSON_ASSERT (index < rpc->op_msg.sections_count);
    BSON_ASSERT (rpc->op_msg.sections[index].kind == 0);
 
-   const int32_t section_len = body ? _int32_from_le (body) : 0;
+   const int32_t section_len = body ? mlib_read_i32le (body) : 0;
 
    rpc->op_msg.sections[index].payload.body.bson = body;
    rpc->op_msg.sections[index].payload.body.section_len = section_len;
@@ -1957,7 +1946,7 @@ mcd_rpc_op_msg_section_set_document_sequ
    rpc->op_msg.sections[index].payload.document_sequence.bson_objects = document_sequence;
    rpc->op_msg.sections[index].payload.document_sequence.bson_objects_len = bson_objects_len;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, document_sequence_length));
+   BSON_ASSERT (mlib_in_range (int32_t, document_sequence_length));
    return (int32_t) bson_objects_len;
 }
 
@@ -2104,7 +2093,7 @@ mcd_rpc_op_reply_set_documents (mcd_rpc_
    rpc->op_reply.documents = documents;
    rpc->op_reply.documents_len = documents_len;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, documents_len));
+   BSON_ASSERT (mlib_in_range (int32_t, documents_len));
    return (int32_t) documents_len;
 }
 
@@ -2152,7 +2141,7 @@ mcd_rpc_op_update_set_full_collection_na
    rpc->op_update.full_collection_name = full_collection_name;
    rpc->op_update.full_collection_name_len = length;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, length));
+   BSON_ASSERT (mlib_in_range (int32_t, length));
    return (int32_t) length;
 }
 
@@ -2169,7 +2158,7 @@ mcd_rpc_op_update_set_selector (mcd_rpc_
 {
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    rpc->op_update.selector = selector;
-   return selector ? _int32_from_le (selector) : 0;
+   return selector ? mlib_read_i32le (selector) : 0;
 }
 
 int32_t
@@ -2177,7 +2166,7 @@ mcd_rpc_op_update_set_update (mcd_rpc_me
 {
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    rpc->op_update.update = update;
-   return update ? _int32_from_le (update) : 0;
+   return update ? mlib_read_i32le (update) : 0;
 }
 
 
@@ -2233,7 +2222,7 @@ mcd_rpc_op_insert_set_full_collection_na
    rpc->op_insert.full_collection_name = full_collection_name;
    rpc->op_insert.full_collection_name_len = length;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, length));
+   BSON_ASSERT (mlib_in_range (int32_t, length));
    return (int32_t) length;
 }
 
@@ -2246,7 +2235,7 @@ mcd_rpc_op_insert_set_documents (mcd_rpc
    rpc->op_insert.documents = documents;
    rpc->op_insert.documents_len = documents_len;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, documents_len));
+   BSON_ASSERT (mlib_in_range (int32_t, documents_len));
    return (int32_t) documents_len;
 }
 
@@ -2319,7 +2308,7 @@ mcd_rpc_op_query_set_full_collection_nam
    rpc->op_query.full_collection_name = full_collection_name;
    rpc->op_query.full_collection_name_len = length;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, length));
+   BSON_ASSERT (mlib_in_range (int32_t, length));
    return (int32_t) length;
 }
 
@@ -2347,7 +2336,7 @@ mcd_rpc_op_query_set_query (mcd_rpc_mess
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY);
    rpc->op_query.query = query;
-   return _int32_from_le (query);
+   return mlib_read_i32le (query);
 }
 
 int32_t
@@ -2356,7 +2345,7 @@ mcd_rpc_op_query_set_return_fields_selec
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY);
    rpc->op_query.return_fields_selector = return_fields_selector;
-   return return_fields_selector ? _int32_from_le (return_fields_selector) : 0;
+   return return_fields_selector ? mlib_read_i32le (return_fields_selector) : 0;
 }
 
 
@@ -2395,7 +2384,7 @@ mcd_rpc_op_get_more_set_full_collection_
    rpc->op_get_more.full_collection_name = full_collection_name;
    rpc->op_get_more.full_collection_name_len = length;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, length));
+   BSON_ASSERT (mlib_in_range (int32_t, length));
    return (int32_t) length;
 }
 
@@ -2453,7 +2442,7 @@ mcd_rpc_op_delete_set_full_collection_na
    rpc->op_delete.full_collection_name = full_collection_name;
    rpc->op_delete.full_collection_name_len = length;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, length));
+   BSON_ASSERT (mlib_in_range (int32_t, length));
    return (int32_t) length;
 }
 
@@ -2472,7 +2461,7 @@ mcd_rpc_op_delete_set_selector (mcd_rpc_
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_DELETE);
    rpc->op_delete.selector = selector;
-   return selector ? _int32_from_le (selector) : 0;
+   return selector ? mlib_read_i32le (selector) : 0;
 }
 
 
@@ -2497,7 +2486,7 @@ mcd_rpc_op_kill_cursors_set_cursor_ids (
 {
    ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS;
    BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_KILL_CURSORS);
-   BSON_ASSERT (mcommon_cmp_less_su (number_of_cursor_ids, (size_t) INT32_MAX / sizeof (int64_t)));
+   BSON_ASSERT (mlib_cmp (number_of_cursor_ids, <, (size_t) INT32_MAX / sizeof (int64_t)));
 
    const size_t cursor_ids_length = (size_t) number_of_cursor_ids * sizeof (int64_t);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/modules/module.modulemap.in 2.0.2-1/src/libmongoc/src/mongoc/modules/module.modulemap.in
--- 1.30.4-1/src/libmongoc/src/mongoc/modules/module.modulemap.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/modules/module.modulemap.in	1970-01-01 00:00:00.000000000 +0000
@@ -1,5 +0,0 @@
-framework module mongoc {
-    umbrella header "mongoc.h"
-    
-    export *
-}
\ No newline at end of file
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-aggregate.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-aggregate.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-aggregate.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-aggregate.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <mongoc/mongoc-aggregate-private.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-cursor-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-read-prefs-private.h>
 #include <mongoc/mongoc-server-stream-private.h>
 #include <mongoc/mongoc-trace-private.h>
@@ -119,7 +120,7 @@ _make_agg_cmd (
                     append (*command, kv ("pipeline", iterValue (bsonVisitIter)))),
               else ( // We did not find a "pipeline" array. copy the pipeline as
                      // an array into the command
-                 append (*command, kv ("pipeline", array (insert (*pipeline, true))))));
+                 append (*command, kv ("pipeline", array (insert (*pipeline, always))))));
    if ((error = bsonParseError)) {
       error_hint = "append-pipeline";
       goto fail;
@@ -158,12 +159,12 @@ _make_agg_cmd (
    return true;
 
 fail:
-   bson_set_error (err,
-                   MONGOC_ERROR_COMMAND,
-                   MONGOC_ERROR_COMMAND_INVALID_ARG,
-                   "Error while building aggregate command [%s]: %s",
-                   error_hint,
-                   error);
+   _mongoc_set_error (err,
+                      MONGOC_ERROR_COMMAND,
+                      MONGOC_ERROR_COMMAND_INVALID_ARG,
+                      "Error while building aggregate command [%s]: %s",
+                      error_hint,
+                      error);
    return false;
 }
 
@@ -284,7 +285,7 @@ _mongoc_aggregate (mongoc_client_t *clie
       has_write_key = _has_write_key (&ar);
    } else {
       if (!bson_iter_init (&iter, pipeline)) {
-         bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Pipeline is invalid BSON");
+         _mongoc_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Pipeline is invalid BSON");
          GOTO (done);
       }
       has_write_key = _has_write_key (&iter);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-apm.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-apm.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-apm.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-apm.c	2025-06-19 15:42:22.000000000 +0000
@@ -378,20 +378,6 @@ mongoc_apm_command_started_get_service_i
 }
 
 
-int32_t
-mongoc_apm_command_started_get_server_connection_id (const mongoc_apm_command_started_t *event)
-{
-   if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) {
-      MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use "
-                      "mongoc_apm_command_started_get_server_connection_id_int64.",
-                      event->server_connection_id);
-      return MONGOC_NO_SERVER_CONNECTION_ID;
-   }
-
-   return (int32_t) event->server_connection_id;
-}
-
-
 int64_t
 mongoc_apm_command_started_get_server_connection_id_int64 (const mongoc_apm_command_started_t *event)
 {
@@ -474,20 +460,6 @@ mongoc_apm_command_succeeded_get_service
 }
 
 
-int32_t
-mongoc_apm_command_succeeded_get_server_connection_id (const mongoc_apm_command_succeeded_t *event)
-{
-   if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) {
-      MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use "
-                      "mongoc_apm_command_succeeded_get_server_connection_id_int64.",
-                      event->server_connection_id);
-      return MONGOC_NO_SERVER_CONNECTION_ID;
-   }
-
-   return (int32_t) event->server_connection_id;
-}
-
-
 int64_t
 mongoc_apm_command_succeeded_get_server_connection_id_int64 (const mongoc_apm_command_succeeded_t *event)
 {
@@ -570,20 +542,6 @@ mongoc_apm_command_failed_get_service_id
 }
 
 
-int32_t
-mongoc_apm_command_failed_get_server_connection_id (const mongoc_apm_command_failed_t *event)
-{
-   if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) {
-      MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use "
-                      "mongoc_apm_command_failed_get_server_connection_id_int64.",
-                      event->server_connection_id);
-      return MONGOC_NO_SERVER_CONNECTION_ID;
-   }
-
-   return (int32_t) event->server_connection_id;
-}
-
-
 int64_t
 mongoc_apm_command_failed_get_server_connection_id_int64 (const mongoc_apm_command_failed_t *event)
 {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-apm.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-apm.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-apm.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-apm.h	2025-06-19 15:42:22.000000000 +0000
@@ -76,177 +76,233 @@ typedef struct _mongoc_apm_server_heartb
 
 /* command-started event fields */
 
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_apm_command_started_get_command (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_started_get_database_name (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_started_get_command_name (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_started_get_request_id (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_started_get_operation_id (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_command_started_get_host (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_apm_command_started_get_server_id (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (const bson_oid_t *)
 mongoc_apm_command_started_get_service_id (const mongoc_apm_command_started_t *event);
-MONGOC_EXPORT (int32_t)
-mongoc_apm_command_started_get_server_connection_id (const mongoc_apm_command_started_t *event)
-   BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_started_get_server_connection_id_int64");
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_started_get_server_connection_id_int64 (const mongoc_apm_command_started_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_command_started_get_context (const mongoc_apm_command_started_t *event);
 
 /* command-succeeded event fields */
 
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_succeeded_get_duration (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_apm_command_succeeded_get_reply (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_succeeded_get_command_name (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_succeeded_get_database_name (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_succeeded_get_request_id (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_succeeded_get_operation_id (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_command_succeeded_get_host (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_apm_command_succeeded_get_server_id (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (const bson_oid_t *)
 mongoc_apm_command_succeeded_get_service_id (const mongoc_apm_command_succeeded_t *event);
-MONGOC_EXPORT (int32_t)
-mongoc_apm_command_succeeded_get_server_connection_id (const mongoc_apm_command_succeeded_t *event)
-   BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_succeeded_get_server_connection_id_int64");
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_succeeded_get_server_connection_id_int64 (const mongoc_apm_command_succeeded_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_command_succeeded_get_context (const mongoc_apm_command_succeeded_t *event);
 
 /* command-failed event fields */
 
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_failed_get_duration (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_failed_get_command_name (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (const char *)
 mongoc_apm_command_failed_get_database_name (const mongoc_apm_command_failed_t *event);
 /* retrieve the error by filling out the passed-in "error" struct */
+
 MONGOC_EXPORT (void)
 mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event, bson_error_t *error);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_apm_command_failed_get_reply (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_failed_get_request_id (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_failed_get_operation_id (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_command_failed_get_host (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_apm_command_failed_get_server_id (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (const bson_oid_t *)
 mongoc_apm_command_failed_get_service_id (const mongoc_apm_command_failed_t *event);
-MONGOC_EXPORT (int32_t)
-mongoc_apm_command_failed_get_server_connection_id (const mongoc_apm_command_failed_t *event)
-   BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_failed_get_server_connection_id_int64");
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_command_failed_get_server_connection_id_int64 (const mongoc_apm_command_failed_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_command_failed_get_context (const mongoc_apm_command_failed_t *event);
 
 /* server-changed event fields */
 
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_changed_get_host (const mongoc_apm_server_changed_t *event);
+
 MONGOC_EXPORT (void)
 mongoc_apm_server_changed_get_topology_id (const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (const mongoc_server_description_t *)
 mongoc_apm_server_changed_get_previous_description (const mongoc_apm_server_changed_t *event);
+
 MONGOC_EXPORT (const mongoc_server_description_t *)
 mongoc_apm_server_changed_get_new_description (const mongoc_apm_server_changed_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_changed_get_context (const mongoc_apm_server_changed_t *event);
 
 /* server-opening event fields */
 
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_opening_get_host (const mongoc_apm_server_opening_t *event);
+
 MONGOC_EXPORT (void)
 mongoc_apm_server_opening_get_topology_id (const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_opening_get_context (const mongoc_apm_server_opening_t *event);
 
 /* server-closed event fields */
 
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_closed_get_host (const mongoc_apm_server_closed_t *event);
+
 MONGOC_EXPORT (void)
 mongoc_apm_server_closed_get_topology_id (const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_closed_get_context (const mongoc_apm_server_closed_t *event);
 
 /* topology-changed event fields */
 
+
 MONGOC_EXPORT (void)
 mongoc_apm_topology_changed_get_topology_id (const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (const mongoc_topology_description_t *)
 mongoc_apm_topology_changed_get_previous_description (const mongoc_apm_topology_changed_t *event);
+
 MONGOC_EXPORT (const mongoc_topology_description_t *)
 mongoc_apm_topology_changed_get_new_description (const mongoc_apm_topology_changed_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_topology_changed_get_context (const mongoc_apm_topology_changed_t *event);
 
 /* topology-opening event field */
 
+
 MONGOC_EXPORT (void)
 mongoc_apm_topology_opening_get_topology_id (const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_topology_opening_get_context (const mongoc_apm_topology_opening_t *event);
 
 /* topology-closed event field */
 
+
 MONGOC_EXPORT (void)
 mongoc_apm_topology_closed_get_topology_id (const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_topology_closed_get_context (const mongoc_apm_topology_closed_t *event);
 
 /* heartbeat-started event field */
 
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_heartbeat_started_get_host (const mongoc_apm_server_heartbeat_started_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_heartbeat_started_get_context (const mongoc_apm_server_heartbeat_started_t *event);
+
 MONGOC_EXPORT (bool)
 mongoc_apm_server_heartbeat_started_get_awaited (const mongoc_apm_server_heartbeat_started_t *event);
 
 /* heartbeat-succeeded event fields */
 
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_server_heartbeat_succeeded_get_duration (const mongoc_apm_server_heartbeat_succeeded_t *event);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_apm_server_heartbeat_succeeded_get_reply (const mongoc_apm_server_heartbeat_succeeded_t *event);
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_heartbeat_succeeded_get_host (const mongoc_apm_server_heartbeat_succeeded_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_heartbeat_succeeded_get_context (const mongoc_apm_server_heartbeat_succeeded_t *event);
+
 MONGOC_EXPORT (bool)
 mongoc_apm_server_heartbeat_succeeded_get_awaited (const mongoc_apm_server_heartbeat_succeeded_t *event);
 
 /* heartbeat-failed event fields */
 
+
 MONGOC_EXPORT (int64_t)
 mongoc_apm_server_heartbeat_failed_get_duration (const mongoc_apm_server_heartbeat_failed_t *event);
+
 MONGOC_EXPORT (void)
 mongoc_apm_server_heartbeat_failed_get_error (const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error);
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_apm_server_heartbeat_failed_get_host (const mongoc_apm_server_heartbeat_failed_t *event);
+
 MONGOC_EXPORT (void *)
 mongoc_apm_server_heartbeat_failed_get_context (const mongoc_apm_server_heartbeat_failed_t *event);
+
 MONGOC_EXPORT (bool)
 mongoc_apm_server_heartbeat_failed_get_awaited (const mongoc_apm_server_heartbeat_failed_t *event);
 
@@ -255,51 +311,66 @@ mongoc_apm_server_heartbeat_failed_get_a
  * callbacks
  */
 
-typedef void (*mongoc_apm_command_started_cb_t) (const mongoc_apm_command_started_t *event);
-typedef void (*mongoc_apm_command_succeeded_cb_t) (const mongoc_apm_command_succeeded_t *event);
-typedef void (*mongoc_apm_command_failed_cb_t) (const mongoc_apm_command_failed_t *event);
-typedef void (*mongoc_apm_server_changed_cb_t) (const mongoc_apm_server_changed_t *event);
-typedef void (*mongoc_apm_server_opening_cb_t) (const mongoc_apm_server_opening_t *event);
-typedef void (*mongoc_apm_server_closed_cb_t) (const mongoc_apm_server_closed_t *event);
-typedef void (*mongoc_apm_topology_changed_cb_t) (const mongoc_apm_topology_changed_t *event);
-typedef void (*mongoc_apm_topology_opening_cb_t) (const mongoc_apm_topology_opening_t *event);
-typedef void (*mongoc_apm_topology_closed_cb_t) (const mongoc_apm_topology_closed_t *event);
-typedef void (*mongoc_apm_server_heartbeat_started_cb_t) (const mongoc_apm_server_heartbeat_started_t *event);
-typedef void (*mongoc_apm_server_heartbeat_succeeded_cb_t) (const mongoc_apm_server_heartbeat_succeeded_t *event);
-typedef void (*mongoc_apm_server_heartbeat_failed_cb_t) (const mongoc_apm_server_heartbeat_failed_t *event);
+typedef void (BSON_CALL *mongoc_apm_command_started_cb_t) (const mongoc_apm_command_started_t *event);
+typedef void (BSON_CALL *mongoc_apm_command_succeeded_cb_t) (const mongoc_apm_command_succeeded_t *event);
+typedef void (BSON_CALL *mongoc_apm_command_failed_cb_t) (const mongoc_apm_command_failed_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_changed_cb_t) (const mongoc_apm_server_changed_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_opening_cb_t) (const mongoc_apm_server_opening_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_closed_cb_t) (const mongoc_apm_server_closed_t *event);
+typedef void (BSON_CALL *mongoc_apm_topology_changed_cb_t) (const mongoc_apm_topology_changed_t *event);
+typedef void (BSON_CALL *mongoc_apm_topology_opening_cb_t) (const mongoc_apm_topology_opening_t *event);
+typedef void (BSON_CALL *mongoc_apm_topology_closed_cb_t) (const mongoc_apm_topology_closed_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_heartbeat_started_cb_t) (const mongoc_apm_server_heartbeat_started_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_heartbeat_succeeded_cb_t) (
+   const mongoc_apm_server_heartbeat_succeeded_t *event);
+typedef void (BSON_CALL *mongoc_apm_server_heartbeat_failed_cb_t) (const mongoc_apm_server_heartbeat_failed_t *event);
 
 /*
  * registering callbacks
  */
 
+
 MONGOC_EXPORT (mongoc_apm_callbacks_t *)
 mongoc_apm_callbacks_new (void) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_apm_callbacks_destroy (mongoc_apm_callbacks_t *callbacks);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_started_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_succeeded_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_failed_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_changed_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_opening_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_closed_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_changed_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_opening_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_closed_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_heartbeat_started_cb (mongoc_apm_callbacks_t *callbacks,
                                             mongoc_apm_server_heartbeat_started_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_heartbeat_succeeded_cb (mongoc_apm_callbacks_t *callbacks,
                                               mongoc_apm_server_heartbeat_succeeded_cb_t cb);
+
 MONGOC_EXPORT (void)
 mongoc_apm_set_server_heartbeat_failed_cb (mongoc_apm_callbacks_t *callbacks,
                                            mongoc_apm_server_heartbeat_failed_cb_t cb);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-async-cmd.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-async-cmd.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-async-cmd.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-async-cmd.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,28 +15,25 @@
  */
 
 
+#include <mlib/intencode.h>
 #include <bson/bson.h>
 
 #include <mongoc/mongoc-client.h>
 #include <mongoc/mongoc-async-cmd-private.h>
 #include <mongoc/mongoc-async-private.h>
 #include <mongoc/mongoc-cluster-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-opcode.h>
 #include <mongoc/mongoc-rpc-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-server-description-private.h>
 #include <mongoc/mongoc-topology-scanner-private.h>
-#include <mongoc/mongoc-log.h>
 #include <mongoc/utlist.h>
 
 #ifdef MONGOC_ENABLE_SSL
 #include <mongoc/mongoc-stream-tls.h>
 #endif
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "async"
-
 typedef mongoc_async_cmd_result_t (*_mongoc_async_cmd_phase_t) (mongoc_async_cmd_t *cmd);
 
 mongoc_async_cmd_result_t
@@ -345,7 +342,7 @@ _mongoc_async_cmd_phase_send (mongoc_asy
    }
 
    if (bytes < 0) {
-      bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to write rpc bytes.");
+      _mongoc_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to write rpc bytes.");
       return MONGOC_ASYNC_CMD_ERROR;
    }
 
@@ -368,31 +365,28 @@ mongoc_async_cmd_result_t
 _mongoc_async_cmd_phase_recv_len (mongoc_async_cmd_t *acmd)
 {
    ssize_t bytes = _mongoc_buffer_try_append_from_stream (&acmd->buffer, acmd->stream, acmd->bytes_to_read, 0);
-   uint32_t msg_len;
-
    if (bytes <= 0 && mongoc_stream_should_retry (acmd->stream)) {
       return MONGOC_ASYNC_CMD_IN_PROGRESS;
    }
 
    if (bytes < 0) {
-      bson_set_error (
+      _mongoc_set_error (
          &acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to receive length header from server.");
       return MONGOC_ASYNC_CMD_ERROR;
    }
 
    if (bytes == 0) {
-      bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection.");
+      _mongoc_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection.");
       return MONGOC_ASYNC_CMD_ERROR;
    }
 
    acmd->bytes_to_read = (size_t) (acmd->bytes_to_read - bytes);
 
    if (!acmd->bytes_to_read) {
-      memcpy (&msg_len, acmd->buffer.data, 4);
-      msg_len = BSON_UINT32_FROM_LE (msg_len);
+      const uint32_t msg_len = mlib_read_u32le (acmd->buffer.data);
 
       if (msg_len < 16 || msg_len > MONGOC_DEFAULT_MAX_MSG_SIZE || msg_len < acmd->buffer.len) {
-         bson_set_error (
+         _mongoc_set_error (
             &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server.");
          return MONGOC_ASYNC_CMD_ERROR;
       }
@@ -416,13 +410,13 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc
    }
 
    if (bytes < 0) {
-      bson_set_error (
+      _mongoc_set_error (
          &acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to receive rpc bytes from server.");
       return MONGOC_ASYNC_CMD_ERROR;
    }
 
    if (bytes == 0) {
-      bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection.");
+      _mongoc_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection.");
       return MONGOC_ASYNC_CMD_ERROR;
    }
 
@@ -431,7 +425,7 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc
    if (!acmd->bytes_to_read) {
       mcd_rpc_message_reset (acmd->rpc);
       if (!mcd_rpc_message_from_data_in_place (acmd->rpc, acmd->buffer.data, acmd->buffer.len, NULL)) {
-         bson_set_error (
+         _mongoc_set_error (
             &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server.");
          return MONGOC_ASYNC_CMD_ERROR;
       }
@@ -441,10 +435,10 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc
       size_t decompressed_data_len;
 
       if (!mcd_rpc_message_decompress_if_necessary (acmd->rpc, &decompressed_data, &decompressed_data_len)) {
-         bson_set_error (&acmd->error,
-                         MONGOC_ERROR_PROTOCOL,
-                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                         "Could not decompress server reply");
+         _mongoc_set_error (&acmd->error,
+                            MONGOC_ERROR_PROTOCOL,
+                            MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                            "Could not decompress server reply");
          return MONGOC_ASYNC_CMD_ERROR;
       }
 
@@ -454,7 +448,7 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc
       }
 
       if (!mcd_rpc_message_get_body (acmd->rpc, &acmd->reply)) {
-         bson_set_error (
+         _mongoc_set_error (
             &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server");
          return MONGOC_ASYNC_CMD_ERROR;
       }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-async.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-async.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-async.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-async.c	2025-06-19 15:42:22.000000000 +0000
@@ -21,12 +21,10 @@
 #include <mongoc/mongoc-async-cmd-private.h>
 #include <mongoc/utlist.h>
 #include <mongoc/mongoc.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-socket-private.h>
 #include <mongoc/mongoc-util-private.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "async"
-
 
 mongoc_async_t *
 mongoc_async_new (void)
@@ -134,15 +132,15 @@ mongoc_async_run (mongoc_async_t *async)
             if (poller[i].revents & (POLLERR | POLLHUP)) {
                int hup = poller[i].revents & POLLHUP;
                if (iter->state == MONGOC_ASYNC_CMD_SEND) {
-                  bson_set_error (&iter->error,
-                                  MONGOC_ERROR_STREAM,
-                                  MONGOC_ERROR_STREAM_CONNECT,
-                                  hup ? "connection refused" : "unknown connection error");
+                  _mongoc_set_error (&iter->error,
+                                     MONGOC_ERROR_STREAM,
+                                     MONGOC_ERROR_STREAM_CONNECT,
+                                     hup ? "connection refused" : "unknown connection error");
                } else {
-                  bson_set_error (&iter->error,
-                                  MONGOC_ERROR_STREAM,
-                                  MONGOC_ERROR_STREAM_SOCKET,
-                                  hup ? "connection closed" : "unknown socket error");
+                  _mongoc_set_error (&iter->error,
+                                     MONGOC_ERROR_STREAM,
+                                     MONGOC_ERROR_STREAM_SOCKET,
+                                     hup ? "connection closed" : "unknown socket error");
                }
 
                iter->state = MONGOC_ASYNC_CMD_ERROR_STATE;
@@ -163,10 +161,10 @@ mongoc_async_run (mongoc_async_t *async)
       {
          /* check if an initiated cmd has passed the connection timeout.  */
          if (acmd->state != MONGOC_ASYNC_CMD_INITIATE && now > acmd->connect_started + acmd->timeout_msec * 1000) {
-            bson_set_error (&acmd->error,
-                            MONGOC_ERROR_STREAM,
-                            MONGOC_ERROR_STREAM_CONNECT,
-                            acmd->state == MONGOC_ASYNC_CMD_SEND ? "connection timeout" : "socket timeout");
+            _mongoc_set_error (&acmd->error,
+                               MONGOC_ERROR_STREAM,
+                               MONGOC_ERROR_STREAM_CONNECT,
+                               acmd->state == MONGOC_ASYNC_CMD_SEND ? "connection timeout" : "socket timeout");
 
             acmd->cb (acmd, MONGOC_ASYNC_CMD_TIMEOUT, NULL, (now - acmd->connect_started) / 1000);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-buffer.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-buffer.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-buffer.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-buffer.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,12 +16,13 @@
 
 
 #include <bson/bson.h>
-#include <stdarg.h>
 
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-buffer-private.h>
 #include <mongoc/mongoc-trace-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+
+#include <stdarg.h>
 
 
 #undef MONGOC_LOG_DOMAIN
@@ -186,23 +187,23 @@ _mongoc_buffer_append_from_stream (
 
    BSON_ASSERT ((buffer->len + size) <= buffer->datalen);
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, timeout_msec))) {
       // CDRIVER-4589
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
-                      timeout_msec);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
+                         timeout_msec);
       RETURN (false);
    }
 
    ret = mongoc_stream_read (stream, buf, size, size, (int32_t) timeout_msec);
-   if (mcommon_cmp_not_equal_su (ret, size)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Failed to read %zu bytes: socket error or timeout",
-                      size);
+   if (mlib_cmp (ret, !=, size)) {
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Failed to read %zu bytes: socket error or timeout",
+                         size);
       RETURN (false);
    }
 
@@ -239,7 +240,7 @@ _mongoc_buffer_fill (
    BSON_ASSERT (buffer->datalen);
 
    if (min_bytes <= buffer->len) {
-      BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, buffer->len));
+      BSON_ASSERT (mlib_in_range (ssize_t, buffer->len));
       RETURN ((ssize_t) buffer->len);
    }
 
@@ -249,36 +250,37 @@ _mongoc_buffer_fill (
 
    avail_bytes = buffer->datalen - buffer->len;
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, timeout_msec))) {
       // CDRIVER-4589
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
-                      timeout_msec);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
+                         timeout_msec);
       RETURN (false);
    }
 
    ret = mongoc_stream_read (stream, &buffer->data[buffer->len], avail_bytes, min_bytes, (int32_t) timeout_msec);
 
    if (ret < 0) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to buffer %zu bytes", min_bytes);
+      _mongoc_set_error (
+         error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to buffer %zu bytes", min_bytes);
       RETURN (-1);
    }
 
    buffer->len += (size_t) ret;
 
    if (buffer->len < min_bytes) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Could only buffer %zu of %zu bytes",
-                      buffer->len,
-                      min_bytes);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Could only buffer %zu of %zu bytes",
+                         buffer->len,
+                         min_bytes);
       RETURN (-1);
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, buffer->len));
+   BSON_ASSERT (mlib_in_range (ssize_t, buffer->len));
    RETURN ((ssize_t) buffer->len);
 }
 
@@ -319,7 +321,7 @@ _mongoc_buffer_try_append_from_stream (m
 
    BSON_ASSERT ((buffer->len + size) <= buffer->datalen);
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, timeout_msec))) {
       // CDRIVER-4589
       MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", timeout_msec);
       RETURN (-1);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <mongoc/mongoc-bulk-operation.h>
 #include <mongoc/mongoc-bulk-operation-private.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-write-concern-private.h>
 #include <mongoc/mongoc-util-private.h>
@@ -121,18 +122,18 @@ mongoc_bulk_operation_destroy (mongoc_bu
       }                                \
    } while (0)
 
-#define BULK_RETURN_IF_PRIOR_ERROR                                            \
-   do {                                                                       \
-      if (bulk->result.error.domain) {                                        \
-         if (error != &bulk->result.error) {                                  \
-            bson_set_error (error,                                            \
-                            MONGOC_ERROR_COMMAND,                             \
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,                 \
-                            "Bulk operation is invalid from prior error: %s", \
-                            bulk->result.error.message);                      \
-         };                                                                   \
-         return false;                                                        \
-      };                                                                      \
+#define BULK_RETURN_IF_PRIOR_ERROR                                               \
+   do {                                                                          \
+      if (bulk->result.error.domain) {                                           \
+         if (error != &bulk->result.error) {                                     \
+            _mongoc_set_error (error,                                            \
+                               MONGOC_ERROR_COMMAND,                             \
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,                 \
+                               "Bulk operation is invalid from prior error: %s", \
+                               bulk->result.error.message);                      \
+         };                                                                      \
+         return false;                                                           \
+      };                                                                         \
    } while (0)
 
 
@@ -160,13 +161,13 @@ _mongoc_bulk_operation_remove_with_opts
 
    /* allow "limit" in opts, but it must be the correct limit */
    if (remove_opts->limit != limit) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Invalid \"limit\" in opts: %" PRId32 "."
-                      " The value must be %" PRId32 ", or omitted.",
-                      remove_opts->limit,
-                      limit);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Invalid \"limit\" in opts: %" PRId32 "."
+                         " The value must be %" PRId32 ", or omitted.",
+                         remove_opts->limit,
+                         limit);
       GOTO (done);
    }
 
@@ -311,26 +312,6 @@ mongoc_bulk_operation_remove_one (mongoc
 }
 
 void
-mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, const bson_t *selector)
-{
-   ENTRY;
-
-   mongoc_bulk_operation_remove (bulk, selector);
-
-   EXIT;
-}
-
-void
-mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, const bson_t *selector)
-{
-   ENTRY;
-
-   mongoc_bulk_operation_remove_one (bulk, selector);
-
-   EXIT;
-}
-
-void
 mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, const bson_t *document)
 {
    ENTRY;
@@ -503,13 +484,13 @@ _mongoc_bulk_operation_update_with_opts
 
    /* allow "multi" in opts, but it must be the correct multi */
    if (update_opts->multi != multi) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Invalid \"multi\" in opts: %s."
-                      " The value must be %s, or omitted.",
-                      update_opts->multi ? "true" : "false",
-                      multi ? "true" : "false");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Invalid \"multi\" in opts: %s."
+                         " The value must be %s, or omitted.",
+                         update_opts->multi ? "true" : "false",
+                         multi ? "true" : "false");
       RETURN (false);
    }
 
@@ -673,12 +654,12 @@ mongoc_bulk_operation_replace_one_with_o
 
    /* allow "multi" in opts, but it must be the correct multi */
    if (update_opts->multi) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Invalid \"multi\": true in opts for"
-                      " mongoc_bulk_operation_replace_one_with_opts."
-                      " The value must be true, or omitted.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Invalid \"multi\": true in opts for"
+                         " mongoc_bulk_operation_replace_one_with_opts."
+                         " The value must be true, or omitted.");
       GOTO (done);
    }
 
@@ -729,35 +710,35 @@ mongoc_bulk_operation_execute (mongoc_bu
    BSON_ASSERT_PARAM (bulk);
 
    if (!bulk->client) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "mongoc_bulk_operation_execute() requires a client "
-                      "and one has not been set.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "mongoc_bulk_operation_execute() requires a client "
+                         "and one has not been set.");
       GOTO (err);
    }
    cluster = &bulk->client->cluster;
 
    if (bulk->executed) {
-      _mongoc_write_result_destroy (&bulk->result);
-      _mongoc_write_result_init (&bulk->result);
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed");
+      GOTO (err);
    }
 
    bulk->executed = true;
 
    if (!bulk->database) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "mongoc_bulk_operation_execute() requires a database "
-                      "and one has not been set.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "mongoc_bulk_operation_execute() requires a database "
+                         "and one has not been set.");
       GOTO (err);
    } else if (!bulk->collection) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "mongoc_bulk_operation_execute() requires a collection "
-                      "and one has not been set.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "mongoc_bulk_operation_execute() requires a collection "
+                         "and one has not been set.");
       GOTO (err);
    }
 
@@ -772,7 +753,8 @@ mongoc_bulk_operation_execute (mongoc_bu
    }
 
    if (!bulk->commands.len) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Cannot do an empty bulk write");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Cannot do an empty bulk write");
       GOTO (err);
    }
 
@@ -924,12 +906,6 @@ mongoc_bulk_operation_set_client_session
 
 
 uint32_t
-mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk)
-{
-   return mongoc_bulk_operation_get_server_id (bulk);
-}
-
-uint32_t
 mongoc_bulk_operation_get_server_id (const mongoc_bulk_operation_t *bulk)
 {
    BSON_ASSERT_PARAM (bulk);
@@ -937,11 +913,6 @@ mongoc_bulk_operation_get_server_id (con
    return bulk->server_id;
 }
 
-void
-mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id)
-{
-   mongoc_bulk_operation_set_server_id (bulk, server_id);
-}
 
 void
 mongoc_bulk_operation_set_server_id (mongoc_bulk_operation_t *bulk, uint32_t server_id)
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulk-operation.h	2025-06-19 15:42:22.000000000 +0000
@@ -43,72 +43,82 @@ typedef struct _mongoc_bulk_write_flags_
 
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, bson_t *reply, bson_error_t *error);
-MONGOC_EXPORT (void)
-mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, const bson_t *selector)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove);
-MONGOC_EXPORT (void)
-mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, const bson_t *selector)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove_one);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, const bson_t *document);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk,
                                         const bson_t *document,
                                         const bson_t *opts,
                                         bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk, const bson_t *selector);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_remove_many_with_opts (mongoc_bulk_operation_t *bulk,
                                              const bson_t *selector,
                                              const bson_t *opts,
                                              bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, const bson_t *selector);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_remove_one_with_opts (mongoc_bulk_operation_t *bulk,
                                             const bson_t *selector,
                                             const bson_t *opts,
                                             bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_replace_one (mongoc_bulk_operation_t *bulk,
                                    const bson_t *selector,
                                    const bson_t *document,
                                    bool upsert);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_replace_one_with_opts (mongoc_bulk_operation_t *bulk,
                                              const bson_t *selector,
                                              const bson_t *document,
                                              const bson_t *opts,
                                              bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_update (mongoc_bulk_operation_t *bulk,
                               const bson_t *selector,
                               const bson_t *document,
                               bool upsert);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_update_many_with_opts (mongoc_bulk_operation_t *bulk,
                                              const bson_t *selector,
                                              const bson_t *document,
                                              const bson_t *opts,
                                              bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_update_one (mongoc_bulk_operation_t *bulk,
                                   const bson_t *selector,
                                   const bson_t *document,
                                   bool upsert);
+
 MONGOC_EXPORT (bool)
 mongoc_bulk_operation_update_one_with_opts (mongoc_bulk_operation_t *bulk,
                                             const bson_t *selector,
                                             const bson_t *document,
                                             const bson_t *opts,
                                             bson_error_t *error); /* OUT */
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_bypass_document_validation (mongoc_bulk_operation_t *bulk, bool bypass);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_comment (mongoc_bulk_operation_t *bulk, const bson_value_t *comment);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_let (mongoc_bulk_operation_t *bulk, const bson_t *let);
 
@@ -118,33 +128,35 @@ mongoc_bulk_operation_set_let (mongoc_bu
  * those wanting to replay a bulk operation to a number of clients or
  * collections.
  */
+
 MONGOC_EXPORT (mongoc_bulk_operation_t *)
 mongoc_bulk_operation_new (bool ordered) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_write_concern (mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, const char *database);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, const char *collection);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_client (mongoc_bulk_operation_t *bulk, void *client);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_client_session (mongoc_bulk_operation_t *bulk,
                                           struct _mongoc_client_session_t *client_session);
-// `mongoc_bulk_operation_set_hint` is deprecated for the more aptly named `mongoc_bulk_operation_set_server_id`.
-MONGOC_EXPORT (void)
-mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_set_server_id);
+
 MONGOC_EXPORT (void)
 mongoc_bulk_operation_set_server_id (mongoc_bulk_operation_t *bulk, uint32_t server_id);
-// `mongoc_bulk_operation_get_hint` is deprecated for the more aptly named `mongoc_bulk_operation_get_server_id`.
-MONGOC_EXPORT (uint32_t)
-mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_get_server_id);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_bulk_operation_get_server_id (const mongoc_bulk_operation_t *bulk);
+
 MONGOC_EXPORT (const mongoc_write_concern_t *)
 mongoc_bulk_operation_get_write_concern (const mongoc_bulk_operation_t *bulk);
+
 BSON_END_DECLS
 
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulkwrite.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulkwrite.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-bulkwrite.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-bulkwrite.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <mlib/intencode.h>
 #include <mongoc/mongoc-bulkwrite.h>
 
 #include <bson/bson.h>
@@ -23,11 +24,11 @@
 #include <mongoc/mongoc-buffer-private.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-client-side-encryption-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-server-stream-private.h>
 #include <mongoc/mongoc-util-private.h> // _mongoc_iter_document_as_bson
 #include <mongoc/mongoc-optional.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 MC_ENABLE_CONVERSION_WARNING_BEGIN
 
@@ -223,11 +224,12 @@ mongoc_bulkwrite_insertoneopts_destroy (
    bson_free (self);
 }
 
-#define ERROR_IF_EXECUTED                                                                                            \
-   if (self->executed) {                                                                                             \
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed"); \
-      return false;                                                                                                  \
-   } else                                                                                                            \
+#define ERROR_IF_EXECUTED                                                                               \
+   if (self->executed) {                                                                                \
+      _mongoc_set_error (                                                                               \
+         error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed"); \
+      return false;                                                                                     \
+   } else                                                                                               \
       (void) 0
 
 bool
@@ -283,7 +285,7 @@ mongoc_bulkwrite_append_insertone (mongo
    }
 
    size_t op_start = self->ops.len; // Save location of `op` to retrieve `_id` later.
-   BSON_ASSERT (mcommon_in_range_size_t_unsigned (op.len));
+   BSON_ASSERT (mlib_in_range (size_t, op.len));
    BSON_ASSERT (_mongoc_buffer_append (&self->ops, bson_get_data (&op), (size_t) op.len));
 
    self->n_ops++;
@@ -314,12 +316,12 @@ validate_update (const bson_t *update, b
    if (bson_iter_next (&iter)) {
       const char *key = bson_iter_key (&iter);
       if (key[0] != '$') {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid key '%s': update only works with $ operators"
-                         " and pipelines",
-                         key);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid key '%s': update only works with $ operators"
+                            " and pipelines",
+                            key);
 
          return false;
       }
@@ -514,11 +516,11 @@ validate_replace (const bson_t *doc, bso
    if (bson_iter_next (&iter)) {
       const char *key = bson_iter_key (&iter);
       if (key[0] == '$') {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid key '%s': replace prohibits $ operators",
-                         key);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid key '%s': replace prohibits $ operators",
+                            key);
 
          return false;
       }
@@ -1166,18 +1168,18 @@ lookup_int32 (const bson_t *bson, const
    }
    bson_error_t error;
    if (source) {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find int32 `%s` in %s, but did not",
-                      key,
-                      source);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find int32 `%s` in %s, but did not",
+                         key,
+                         source);
    } else {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find int32 `%s`, but did not",
-                      key);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find int32 `%s`, but did not",
+                         key);
    }
    _bulkwriteexception_set_error (exc, &error);
    return false;
@@ -1201,18 +1203,18 @@ lookup_as_int64 (
    }
    bson_error_t error;
    if (source) {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find int32, int64, or double `%s` in %s, but did not",
-                      key,
-                      source);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find int32, int64, or double `%s` in %s, but did not",
+                         key,
+                         source);
    } else {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find int32, int64, or double `%s`, but did not",
-                      key);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find int32, int64, or double `%s`, but did not",
+                         key);
    }
    _bulkwriteexception_set_error (exc, &error);
    return false;
@@ -1235,18 +1237,18 @@ lookup_string (
    }
    bson_error_t error;
    if (source) {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find string `%s` in %s, but did not",
-                      key,
-                      source);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find string `%s` in %s, but did not",
+                         key,
+                         source);
    } else {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected to find string `%s`, but did not",
-                      key);
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected to find string `%s`, but did not",
+                         key);
    }
    _bulkwriteexception_set_error (exc, &error);
    return false;
@@ -1367,17 +1369,17 @@ _bulkwritereturn_apply_result (mongoc_bu
          return false;
       }
       if (idx < 0) {
-         bson_set_error (&error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "expected to find non-negative int64 `idx` in "
-                         "result, but did not");
+         _mongoc_set_error (&error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "expected to find non-negative int64 `idx` in "
+                            "result, but did not");
          _bulkwriteexception_set_error (self->exc, &error);
          return false;
       }
    }
 
-   BSON_ASSERT (mcommon_in_range_size_t_signed (idx));
+   BSON_ASSERT (mlib_in_range (size_t, idx));
    // `models_idx` is the index of the model that produced this result.
    size_t models_idx = (size_t) idx + ops_doc_offset;
    if (ok == 0) {
@@ -1439,11 +1441,11 @@ _bulkwritereturn_apply_result (mongoc_bu
          if (bson_iter_init_find (&result_iter, result, "upserted")) {
             BSON_ASSERT (bson_iter_init (&result_iter, result));
             if (!bson_iter_find_descendant (&result_iter, "upserted._id", &id_iter)) {
-               bson_set_error (&error,
-                               MONGOC_ERROR_COMMAND,
-                               MONGOC_ERROR_COMMAND_INVALID_ARG,
-                               "expected `upserted` to be a document "
-                               "containing `_id`, but did not find `_id`");
+               _mongoc_set_error (&error,
+                                  MONGOC_ERROR_COMMAND,
+                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                  "expected `upserted` to be a document "
+                                  "containing `_id`, but did not find `_id`");
                _bulkwriteexception_set_error (self->exc, &error);
                return false;
             }
@@ -1537,33 +1539,33 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
    ret.exc = _bulkwriteexception_new ();
 
    if (!self->client) {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "bulk write requires a client and one has not been set");
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "bulk write requires a client and one has not been set");
       _bulkwriteexception_set_error (ret.exc, &error);
       goto fail;
    }
 
    if (self->executed) {
-      bson_set_error (&error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed");
+      _mongoc_set_error (&error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed");
       _bulkwriteexception_set_error (ret.exc, &error);
       goto fail;
    }
    self->executed = true;
 
    if (self->n_ops == 0) {
-      bson_set_error (
+      _mongoc_set_error (
          &error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "cannot do `bulkWrite` with no models");
       _bulkwriteexception_set_error (ret.exc, &error);
       goto fail;
    }
 
    if (_mongoc_cse_is_enabled (self->client)) {
-      bson_set_error (&error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "bulkWrite does not currently support automatic encryption");
+      _mongoc_set_error (&error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "bulkWrite does not currently support automatic encryption");
       _bulkwriteexception_set_error (ret.exc, &error);
       goto fail;
    }
@@ -1642,10 +1644,10 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
          const mongoc_write_concern_t *wc = self->client->write_concern; // Default to client.
          if (opts->writeconcern) {
             if (_mongoc_client_session_in_txn (self->session)) {
-               bson_set_error (&error,
-                               MONGOC_ERROR_COMMAND,
-                               MONGOC_ERROR_COMMAND_INVALID_ARG,
-                               "Cannot set write concern after starting a transaction.");
+               _mongoc_set_error (&error,
+                                  MONGOC_ERROR_COMMAND,
+                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                  "Cannot set write concern after starting a transaction.");
                _bulkwriteexception_set_error (ret.exc, &error);
                goto fail;
             }
@@ -1655,15 +1657,14 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
             _bulkwriteexception_set_error (ret.exc, &error);
             goto fail;
          }
-         if (!mongoc_write_concern_is_acknowledged (wc) &&
-             mcommon_cmp_greater_us (self->max_insert_len, maxBsonObjectSize)) {
-            bson_set_error (&error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "Unacknowledged `bulkWrite` includes insert of size: %" PRIu32
-                            ", exceeding maxBsonObjectSize: %" PRId32,
-                            self->max_insert_len,
-                            maxBsonObjectSize);
+         if (!mongoc_write_concern_is_acknowledged (wc) && mlib_cmp (self->max_insert_len, >, maxBsonObjectSize)) {
+            _mongoc_set_error (&error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "Unacknowledged `bulkWrite` includes insert of size: %" PRIu32
+                               ", exceeding maxBsonObjectSize: %" PRId32,
+                               self->max_insert_len,
+                               maxBsonObjectSize);
             _bulkwriteexception_set_error (ret.exc, &error);
             goto fail;
          }
@@ -1671,19 +1672,19 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
       }
 
       if (verboseresults && !is_acknowledged) {
-         bson_set_error (&error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot request unacknowledged write concern and verbose results.");
+         _mongoc_set_error (&error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot request unacknowledged write concern and verbose results.");
          _bulkwriteexception_set_error (ret.exc, &error);
          goto fail;
       }
 
       if (is_ordered && !is_acknowledged) {
-         bson_set_error (&error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot request unacknowledged write concern and ordered writes.");
+         _mongoc_set_error (&error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot request unacknowledged write concern and ordered writes.");
          _bulkwriteexception_set_error (ret.exc, &error);
          goto fail;
       }
@@ -1735,15 +1736,13 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
             break;
          }
 
-         if (ops_doc_len >= maxWriteBatchSize) {
+         if (mlib_cmp (ops_doc_len, >=, maxWriteBatchSize)) {
             // Maximum number of operations are readied.
             break;
          }
 
          // Read length of next document.
-         uint32_t doc_len;
-         memcpy (&doc_len, self->ops.data + ops_byte_offset + ops_byte_len, 4);
-         doc_len = BSON_UINT32_FROM_LE (doc_len);
+         const uint32_t doc_len = mlib_read_u32le (self->ops.data + ops_byte_offset + ops_byte_len);
 
          // Check if adding this operation requires adding an `nsInfo` entry.
          // `models_idx` is the index of the model that produced this result.
@@ -1756,16 +1755,16 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
             nsinfo_bson_size = mcd_nsinfo_get_bson_size (md->ns);
          }
 
-         if (opmsg_overhead + ops_byte_len + doc_len + nsinfo_bson_size > maxMessageSizeBytes) {
+         if (mlib_cmp (opmsg_overhead + ops_byte_len + doc_len + nsinfo_bson_size, >, maxMessageSizeBytes)) {
             if (ops_byte_len == 0) {
                // Could not even fit one document within an OP_MSG.
-               bson_set_error (&error,
-                               MONGOC_ERROR_COMMAND,
-                               MONGOC_ERROR_COMMAND_INVALID_ARG,
-                               "unable to send document at index %zu. Sending "
-                               "would exceed maxMessageSizeBytes=%" PRId32,
-                               ops_doc_len,
-                               maxMessageSizeBytes);
+               _mongoc_set_error (&error,
+                                  MONGOC_ERROR_COMMAND,
+                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                  "unable to send document at index %zu. Sending "
+                                  "would exceed maxMessageSizeBytes=%" PRId32,
+                                  ops_doc_len,
+                                  maxMessageSizeBytes);
                _bulkwriteexception_set_error (ret.exc, &error);
                goto batch_fail;
             }
@@ -1808,7 +1807,7 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
             mongoc_cmd_payload_t *payload = &parts.assembled.payloads[0];
             const mongoc_buffer_t *nsinfo_docseq = mcd_nsinfo_as_document_sequence (nsinfo);
             payload->documents = nsinfo_docseq->data;
-            BSON_ASSERT (mcommon_in_range_int32_t_unsigned (nsinfo_docseq->len));
+            BSON_ASSERT (mlib_in_range (int32_t, nsinfo_docseq->len));
             payload->size = (int32_t) nsinfo_docseq->len;
             payload->identifier = "nsInfo";
          }
@@ -1818,7 +1817,7 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
             mongoc_cmd_payload_t *payload = &parts.assembled.payloads[1];
             payload->identifier = "ops";
             payload->documents = self->ops.data + ops_byte_offset;
-            BSON_ASSERT (mcommon_in_range_int32_t_unsigned (ops_byte_len));
+            BSON_ASSERT (mlib_in_range (int32_t, ops_byte_len));
             payload->size = (int32_t) ops_byte_len;
          }
 
@@ -1880,7 +1879,7 @@ mongoc_bulkwrite_execute (mongoc_bulkwri
                bson_t cursor_opts = BSON_INITIALIZER;
                {
                   uint32_t serverid = parts.assembled.server_stream->sd->id;
-                  BSON_ASSERT (mcommon_in_range_int32_t_unsigned (serverid));
+                  BSON_ASSERT (mlib_in_range (int32_t, serverid));
                   int32_t serverid_i32 = (int32_t) serverid;
                   BSON_ASSERT (BSON_APPEND_INT32 (&cursor_opts, "serverId", serverid_i32));
                   // Use same session if one was applied.
@@ -1959,7 +1958,7 @@ fail:
             has_successful_results = true;
          }
       } else {
-         BSON_ASSERT (mcommon_in_range_size_t_signed (ret.res->errorscount));
+         BSON_ASSERT (mlib_in_range (size_t, ret.res->errorscount));
          size_t errorscount_sz = (size_t) ret.res->errorscount;
          if (errorscount_sz < self->n_ops) {
             has_successful_results = true;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-change-stream.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-change-stream.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-change-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-change-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,11 +22,10 @@
 #include <mongoc/mongoc-client-session-private.h>
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-database-private.h>
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-error-private.h>
 
 #define CHANGE_STREAM_ERR(_str) \
-   bson_set_error (&stream->err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_BSON, "Could not set " _str)
+   _mongoc_set_error (&stream->err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_BSON, "Could not set " _str)
 
 /* the caller knows either a client or server error has occurred.
  * `reply` contains the server reply or an empty document. */
@@ -193,7 +192,10 @@ _make_command (mongoc_change_stream_t *s
 
    /* Add batch size if needed */
    bson_append_document_begin (command, "cursor", 6, &cursor_doc);
-   if (stream->batch_size > 0) {
+   if (stream->batch_size >= 0) {
+      // `batchSize:0` is supported and applied to `aggregate`. `batchSize:0` requests an immediate cursor. This is
+      // useful to avoid a long-running server-side aggregate. Once created, `mongoc_change_stream_destroy` can use
+      // `killCursors` to kill the server-side cursor.
       bson_append_int32 (&cursor_doc, "batchSize", 9, stream->batch_size);
    }
    bson_append_document_end (command, &cursor_doc);
@@ -378,7 +380,7 @@ _change_stream_init (mongoc_change_strea
 
    _mongoc_timestamp_set (&stream->operation_time, &stream->opts.startAtOperationTime);
 
-   stream->batch_size = stream->opts.batchSize;
+   stream->batch_size = stream->opts.batchSize; // `stream->opts.batchSize` is -1 if not present in `opts`.
    stream->max_await_time_ms = stream->opts.maxAwaitTimeMS;
    stream->show_expanded_events = stream->opts.showExpandedEvents;
 
@@ -531,11 +533,11 @@ mongoc_change_stream_next (mongoc_change
    stream->has_returned_results = true;
 
    if (!bson_iter_init_find (&iter, *bson, "_id") || !BSON_ITER_HOLDS_DOCUMENT (&iter)) {
-      bson_set_error (&stream->err,
-                      MONGOC_ERROR_CURSOR,
-                      MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN,
-                      "Cannot provide resume functionality when the resume "
-                      "token is missing");
+      _mongoc_set_error (&stream->err,
+                         MONGOC_ERROR_CURSOR,
+                         MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN,
+                         "Cannot provide resume functionality when the resume "
+                         "token is missing");
       goto end;
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-pool.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-pool.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-pool.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-pool.c	2025-06-19 15:42:22.000000000 +0000
@@ -23,6 +23,7 @@
 #include <mongoc/mongoc-client-pool.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-client-side-encryption-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log-and-monitor-private.h>
 #include <mongoc/mongoc-queue-private.h>
 #include <mongoc/mongoc-thread-private.h>
@@ -44,7 +45,6 @@ struct _mongoc_client_pool_t {
    mongoc_queue_t queue;
    mongoc_topology_t *topology;
    mongoc_uri_t *uri;
-   uint32_t min_pool_size;
    uint32_t max_pool_size;
    uint32_t size;
 #ifdef MONGOC_ENABLE_SSL
@@ -136,13 +136,22 @@ mongoc_client_pool_new_with_error (const
 
    BSON_ASSERT (uri);
 
+   extern bool mongoc_get_init_called (void);
+   if (!mongoc_get_init_called ()) {
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_NOT_READY,
+                         "Attempting to create client pool, but libmongoc not initialized. Call mongoc_init");
+      return NULL;
+   }
+
 #ifndef MONGOC_ENABLE_SSL
    if (mongoc_uri_get_tls (uri)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Can't create SSL client pool, SSL not enabled in this "
-                      "build.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Can't create SSL client pool, SSL not enabled in this "
+                         "build.");
       return NULL;
    }
 #endif
@@ -165,7 +174,6 @@ mongoc_client_pool_new_with_error (const
    mongoc_cond_init (&pool->cond);
    _mongoc_queue_init (&pool->queue);
    pool->uri = mongoc_uri_copy (uri);
-   pool->min_pool_size = 0;
    pool->max_pool_size = 100;
    pool->size = 0;
    pool->topology = topology;
@@ -173,15 +181,6 @@ mongoc_client_pool_new_with_error (const
 
    b = mongoc_uri_get_options (pool->uri);
 
-   if (bson_iter_init_find_case (&iter, b, MONGOC_URI_MINPOOLSIZE)) {
-      MONGOC_WARNING (MONGOC_URI_MINPOOLSIZE " is deprecated; its behavior does not match its name, and its actual"
-                                             " behavior will likely hurt performance.");
-
-      if (BSON_ITER_HOLDS_INT32 (&iter)) {
-         pool->min_pool_size = BSON_MAX (0, bson_iter_int32 (&iter));
-      }
-   }
-
    if (bson_iter_init_find_case (&iter, b, MONGOC_URI_MAXPOOLSIZE)) {
       if (BSON_ITER_HOLDS_INT32 (&iter)) {
          pool->max_pool_size = BSON_MAX (1, bson_iter_int32 (&iter));
@@ -277,7 +276,7 @@ _initialize_new_client (mongoc_client_po
    BSON_ASSERT_PARAM (client);
 
    /* for tests */
-   mongoc_client_set_stream_initiator (
+   _mongoc_client_set_stream_initiator_single_or_pooled (
       client, pool->topology->scanner->initiator, pool->topology->scanner->initiator_context);
 
    pool->client_initialized = true;
@@ -287,7 +286,7 @@ _initialize_new_client (mongoc_client_po
 
 #ifdef MONGOC_ENABLE_SSL
    if (pool->ssl_opts_set) {
-      mongoc_client_set_ssl_opts (client, &pool->ssl_opts);
+      _mongoc_client_set_ssl_opts_for_single_or_pooled (client, &pool->ssl_opts);
    }
 #endif
 }
@@ -476,15 +475,6 @@ mongoc_client_pool_push (mongoc_client_p
    // Push client back into pool.
    _mongoc_queue_push_head (&pool->queue, client);
 
-   if (pool->min_pool_size && _mongoc_queue_get_length (&pool->queue) > pool->min_pool_size) {
-      mongoc_client_t *old_client;
-      old_client = (mongoc_client_t *) _mongoc_queue_pop_tail (&pool->queue);
-      if (old_client) {
-         mongoc_client_destroy (old_client);
-         pool->size--;
-      }
-   }
-
    mongoc_cond_signal (&pool->cond);
    bson_mutex_unlock (&pool->mutex);
 
@@ -555,22 +545,6 @@ mongoc_client_pool_max_size (mongoc_clie
    EXIT;
 }
 
-void
-mongoc_client_pool_min_size (mongoc_client_pool_t *pool, uint32_t min_pool_size)
-{
-   ENTRY;
-   BSON_ASSERT_PARAM (pool);
-
-   MONGOC_WARNING ("mongoc_client_pool_min_size is deprecated; its behavior does not match"
-                   " its name, and its actual behavior will likely hurt performance.");
-
-   bson_mutex_lock (&pool->mutex);
-   pool->min_pool_size = min_pool_size;
-   bson_mutex_unlock (&pool->mutex);
-
-   EXIT;
-}
-
 bool
 mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, mongoc_apm_callbacks_t *callbacks, void *context)
 {
@@ -674,16 +648,16 @@ mongoc_client_pool_set_server_api (mongo
    BSON_ASSERT_PARAM (api);
 
    if (pool->api) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_POOL, MONGOC_ERROR_POOL_API_ALREADY_SET, "Cannot set server api more than once per pool");
       return false;
    }
 
    if (pool->client_initialized) {
-      bson_set_error (error,
-                      MONGOC_ERROR_POOL,
-                      MONGOC_ERROR_POOL_API_TOO_LATE,
-                      "Cannot set server api after a client has been created");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_POOL,
+                         MONGOC_ERROR_POOL_API_TOO_LATE,
+                         "Cannot set server api after a client has been created");
       return false;
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-pool.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-pool.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-pool.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-pool.h	2025-06-19 15:42:22.000000000 +0000
@@ -40,36 +40,47 @@ typedef struct _mongoc_client_pool_t mon
 
 MONGOC_EXPORT (mongoc_client_pool_t *)
 mongoc_client_pool_new (const mongoc_uri_t *uri) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_client_pool_t *)
 mongoc_client_pool_new_with_error (const mongoc_uri_t *uri, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_client_pool_destroy (mongoc_client_pool_t *pool);
+
 MONGOC_EXPORT (mongoc_client_t *)
 mongoc_client_pool_pop (mongoc_client_pool_t *pool) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_client_pool_push (mongoc_client_pool_t *pool, mongoc_client_t *client);
+
 MONGOC_EXPORT (mongoc_client_t *)
 mongoc_client_pool_try_pop (mongoc_client_pool_t *pool) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_client_pool_max_size (mongoc_client_pool_t *pool, uint32_t max_pool_size);
-MONGOC_EXPORT (void)
-mongoc_client_pool_min_size (mongoc_client_pool_t *pool, uint32_t min_pool_size) BSON_GNUC_DEPRECATED;
+
 #ifdef MONGOC_ENABLE_SSL
 MONGOC_EXPORT (void)
 mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool, const mongoc_ssl_opt_t *opts);
 #endif
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, mongoc_apm_callbacks_t *callbacks, void *context);
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_set_error_api (mongoc_client_pool_t *pool, int32_t version);
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_set_appname (mongoc_client_pool_t *pool, const char *appname);
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_enable_auto_encryption (mongoc_client_pool_t *pool,
                                            mongoc_auto_encryption_opts_t *opts,
                                            bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool, const mongoc_server_api_t *api, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_pool_set_structured_log_opts (mongoc_client_pool_t *pool, const mongoc_structured_log_opts_t *opts);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -229,6 +229,14 @@ mongoc_client_uses_server_api (const mon
 bool
 mongoc_client_uses_loadbalanced (const mongoc_client_t *client);
 
+void
+_mongoc_client_set_ssl_opts_for_single_or_pooled (mongoc_client_t *client, const mongoc_ssl_opt_t *opts);
+
+void
+_mongoc_client_set_stream_initiator_single_or_pooled (mongoc_client_t *client,
+                                                      mongoc_stream_initiator_t initiator,
+                                                      void *user_data);
+
 BSON_END_DECLS
 
 #endif /* MONGOC_CLIENT_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-session.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-session.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-session.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-session.c	2025-06-19 15:42:22.000000000 +0000
@@ -99,10 +99,10 @@ txn_abort (mongoc_client_session_t *sess
 
    if (session->txn.opts.write_concern) {
       if (!mongoc_write_concern_append (session->txn.opts.write_concern, &opts)) {
-         bson_set_error (err_ptr,
-                         MONGOC_ERROR_TRANSACTION,
-                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                         "Invalid transaction write concern");
+         _mongoc_set_error (err_ptr,
+                            MONGOC_ERROR_TRANSACTION,
+                            MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                            "Invalid transaction write concern");
          GOTO (done);
       }
    }
@@ -191,7 +191,7 @@ retry:
 
    if (session->txn.opts.max_commit_time_ms != DEFAULT_MAX_COMMIT_TIME_MS) {
       if (!bson_append_int64 (&opts, "maxTimeMS", -1, session->txn.opts.max_commit_time_ms)) {
-         bson_set_error (err_ptr, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "error appending maxCommitTimeMS");
+         _mongoc_set_error (err_ptr, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "error appending maxCommitTimeMS");
          GOTO (done);
       }
    }
@@ -207,10 +207,10 @@ retry:
 
    if (retry_wc || session->txn.opts.write_concern) {
       if (!mongoc_write_concern_append (retry_wc ? retry_wc : session->txn.opts.write_concern, &opts)) {
-         bson_set_error (err_ptr,
-                         MONGOC_ERROR_TRANSACTION,
-                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                         "Invalid transaction write concern");
+         _mongoc_set_error (err_ptr,
+                            MONGOC_ERROR_TRANSACTION,
+                            MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                            "Invalid transaction write concern");
          GOTO (done);
       }
    }
@@ -535,10 +535,10 @@ _mongoc_server_session_uuid (uint8_t *da
     */
 
    if (!_mongoc_rand_bytes (data, 16)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_SESSION_FAILURE,
-                      "Could not generate UUID for logical session id");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_SESSION_FAILURE,
+                         "Could not generate UUID for logical session id");
 
       return false;
    }
@@ -549,12 +549,12 @@ _mongoc_server_session_uuid (uint8_t *da
    return true;
 #else
    /* no _mongoc_rand_bytes without a crypto library */
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_SESSION_FAILURE,
-                   "Could not generate UUID for logical session id, we need a"
-                   " cryptography library like libcrypto, Common Crypto, or"
-                   " CNG");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_SESSION_FAILURE,
+                      "Could not generate UUID for logical session id, we need a"
+                      " cryptography library like libcrypto, Common Crypto, or"
+                      " CNG");
 
    return false;
 #endif
@@ -1045,21 +1045,21 @@ mongoc_client_session_start_transaction
    }
 
    if (mongoc_session_opts_get_snapshot (&session->opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_TRANSACTION,
-                      MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                      "Transactions are not supported in snapshot sessions");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_TRANSACTION,
+                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                         "Transactions are not supported in snapshot sessions");
       ret = false;
       GOTO (done);
    }
 
    if (server_stream->sd->max_wire_version < 7 ||
        (server_stream->sd->max_wire_version < 8 && server_stream->sd->type == MONGOC_SERVER_MONGOS)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_TRANSACTION,
-                      MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                      "Multi-document transactions are not supported by this "
-                      "server version");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_TRANSACTION,
+                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                         "Multi-document transactions are not supported by this "
+                         "server version");
       ret = false;
       GOTO (done);
    }
@@ -1068,7 +1068,7 @@ mongoc_client_session_start_transaction
    switch (session->txn.state) {
    case MONGOC_INTERNAL_TRANSACTION_STARTING:
    case MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS:
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "Transaction already in progress");
       ret = false;
       GOTO (done);
@@ -1097,10 +1097,10 @@ mongoc_client_session_start_transaction
    }
 
    if (!mongoc_write_concern_is_acknowledged (session->txn.opts.write_concern)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_TRANSACTION,
-                      MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                      "Transactions do not support unacknowledged write concern");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_TRANSACTION,
+                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                         "Transactions do not support unacknowledged write concern");
       ret = false;
       GOTO (done);
    }
@@ -1195,7 +1195,7 @@ mongoc_client_session_commit_transaction
 
    switch (session->txn.state) {
    case MONGOC_INTERNAL_TRANSACTION_NONE:
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "No transaction started");
       _mongoc_bson_init_if_set (reply);
       break;
@@ -1223,10 +1223,10 @@ mongoc_client_session_commit_transaction
       abort ();
    case MONGOC_INTERNAL_TRANSACTION_ABORTED:
    default:
-      bson_set_error (error,
-                      MONGOC_ERROR_TRANSACTION,
-                      MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                      "Cannot call commitTransaction after calling abortTransaction");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_TRANSACTION,
+                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                         "Cannot call commitTransaction after calling abortTransaction");
       _mongoc_bson_init_if_set (reply);
       break;
    }
@@ -1262,13 +1262,13 @@ mongoc_client_session_abort_transaction
       RETURN (true);
    case MONGOC_INTERNAL_TRANSACTION_COMMITTED:
    case MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY:
-      bson_set_error (error,
-                      MONGOC_ERROR_TRANSACTION,
-                      MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                      "Cannot call abortTransaction after calling commitTransaction");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_TRANSACTION,
+                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                         "Cannot call abortTransaction after calling commitTransaction");
       RETURN (false);
    case MONGOC_INTERNAL_TRANSACTION_ABORTED:
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "Cannot call abortTransaction twice");
       RETURN (false);
    case MONGOC_INTERNAL_TRANSACTION_ENDING:
@@ -1276,7 +1276,7 @@ mongoc_client_session_abort_transaction
       abort ();
    case MONGOC_INTERNAL_TRANSACTION_NONE:
    default:
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "No transaction started");
       RETURN (false);
    }
@@ -1294,7 +1294,7 @@ _mongoc_client_session_from_iter (mongoc
 
    /* must be int64 that fits in uint32 */
    if (!BSON_ITER_HOLDS_INT64 (iter) || bson_iter_int64 (iter) > 0xffffffff) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId");
       RETURN (false);
    }
 
@@ -1390,7 +1390,7 @@ _mongoc_client_session_append_txn (mongo
    }
 
    if (bson_empty0 (cmd)) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command in transaction");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command in transaction");
       RETURN (false);
    }
 
@@ -1528,7 +1528,7 @@ mongoc_client_session_append (const mong
    BSON_ASSERT (opts);
 
    if (!bson_append_int64 (opts, "sessionId", 9, client_session->client_session_id)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid opts");
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid opts");
 
       RETURN (false);
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-session.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-session.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-session.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-session.h	2025-06-19 15:42:22.000000000 +0000
@@ -27,10 +27,10 @@
 
 BSON_BEGIN_DECLS
 
-typedef bool (*mongoc_client_session_with_transaction_cb_t) (mongoc_client_session_t *session,
-                                                             void *ctx,
-                                                             bson_t **reply,
-                                                             bson_error_t *error);
+typedef bool (BSON_CALL *mongoc_client_session_with_transaction_cb_t) (mongoc_client_session_t *session,
+                                                                       void *ctx,
+                                                                       bson_t **reply,
+                                                                       bson_error_t *error);
 
 typedef enum {
    MONGOC_TRANSACTION_NONE = 0,
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,6 +24,7 @@
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-client-side-encryption-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-topology-private.h>
@@ -723,12 +724,12 @@ mongoc_client_encryption_rewrap_many_dat
 static bool
 _disabled_error (bson_error_t *error)
 {
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                   "libmongoc is not built with support for Client-Side Field "
-                   "Level Encryption. Configure with "
-                   "ENABLE_CLIENT_SIDE_ENCRYPTION=ON.");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                      "libmongoc is not built with support for Client-Side Field "
+                      "Level Encryption. Configure with "
+                      "ENABLE_CLIENT_SIDE_ENCRYPTION=ON.");
    return false;
 }
 
@@ -1217,11 +1218,11 @@ _mongoc_cse_auto_encrypt (mongoc_client_
    }
 
    if (cmd->server_stream->sd->max_wire_version < WIRE_VERSION_CSE) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                      "%s",
-                      "Auto-encryption requires a minimum MongoDB version of 4.2");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                         "%s",
+                         "Auto-encryption requires a minimum MongoDB version of 4.2");
       GOTO (fail);
    }
 
@@ -1329,10 +1330,10 @@ fail:
 static void
 _uri_construction_error (bson_error_t *error)
 {
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                   "Error constructing URI to mongocryptd");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                      "Error constructing URI to mongocryptd");
 }
 
 
@@ -1377,24 +1378,14 @@ _do_spawn (const char *path, char **args
                         NULL /* current directory */,
                         &startup_info,
                         &process_information)) {
-      long lastError = GetLastError ();
-      LPSTR message = NULL;
-
-      FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_SYSTEM |
-                         FORMAT_MESSAGE_IGNORE_INSERTS,
-                      NULL,
-                      lastError,
-                      0,
-                      (LPSTR) &message,
-                      0,
-                      NULL);
+      char *message = mongoc_winerr_to_string (GetLastError ());
 
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "failed to spawn mongocryptd: %s",
-                      message);
-      LocalFree (message);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "failed to spawn mongocryptd: %s",
+                         message);
+      bson_free (message);
       mcommon_string_from_append_destroy (&command);
       return false;
    }
@@ -1457,12 +1448,12 @@ _do_spawn (const char *path, char **args
     * child. */
    pid = fork ();
    if (pid < 0) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "failed to fork (errno=%d) '%s'",
-                      errno,
-                      strerror (errno));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "failed to fork (errno=%d) '%s'",
+                         errno,
+                         strerror (errno));
       bson_free (to_exec);
       return false;
    } else if (pid > 0) {
@@ -1471,12 +1462,12 @@ _do_spawn (const char *path, char **args
       /* Child will spawn mongocryptd and immediately terminate to turn
        * mongocryptd into an orphan. */
       if (waitpid (pid, &child_status, 0 /* options */) < 0) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "failed to wait for child (errno=%d) '%s'",
-                         errno,
-                         strerror (errno));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "failed to wait for child (errno=%d) '%s'",
+                            errno,
+                            strerror (errno));
          bson_free (to_exec);
          return false;
       }
@@ -1589,10 +1580,10 @@ _spawn_mongocryptd (const char *mongocry
       bson_iter_init (&iter, mongocryptd_spawn_args);
       while (bson_iter_next (&iter)) {
          if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "invalid argument for mongocryptd, must be string");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "invalid argument for mongocryptd, must be string");
             return false;
          }
          /* Check if the arg starts with --idleShutdownTimeoutSecs= or is equal
@@ -1645,20 +1636,20 @@ _parse_extra (const bson_t *extra, mongo
    if (extra) {
       if (bson_iter_init_find (&iter, extra, "mongocryptdBypassSpawn")) {
          if (!BSON_ITER_HOLDS_BOOL (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected bool for option 'mongocryptdBypassSpawn'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected bool for option 'mongocryptdBypassSpawn'");
             GOTO (fail);
          }
          topology->mongocryptd_bypass_spawn = bson_iter_bool (&iter);
       }
       if (bson_iter_init_find (&iter, extra, "mongocryptdSpawnPath")) {
          if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected string for option 'mongocryptdSpawnPath'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected string for option 'mongocryptdSpawnPath'");
             GOTO (fail);
          }
          topology->mongocryptd_spawn_path = bson_strdup (bson_iter_utf8 (&iter, NULL));
@@ -1668,10 +1659,10 @@ _parse_extra (const bson_t *extra, mongo
          const uint8_t *array_data;
 
          if (!BSON_ITER_HOLDS_ARRAY (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected array for option 'mongocryptdSpawnArgs'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected array for option 'mongocryptdSpawnArgs'");
             GOTO (fail);
          }
          bson_iter_array (&iter, &array_len, &array_data);
@@ -1680,10 +1671,10 @@ _parse_extra (const bson_t *extra, mongo
 
       if (bson_iter_init_find (&iter, extra, "mongocryptdURI")) {
          if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected string for option 'mongocryptdURI'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected string for option 'mongocryptdURI'");
             GOTO (fail);
          }
          *uri = mongoc_uri_new_with_error (bson_iter_utf8 (&iter, NULL), error);
@@ -1694,10 +1685,10 @@ _parse_extra (const bson_t *extra, mongo
 
       if (bson_iter_init_find (&iter, extra, "cryptSharedLibPath")) {
          if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected a string for 'cryptSharedLibPath'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected a string for 'cryptSharedLibPath'");
             GOTO (fail);
          }
          size_t len;
@@ -1708,10 +1699,10 @@ _parse_extra (const bson_t *extra, mongo
 
       if (bson_iter_init_find (&iter, extra, "cryptSharedLibRequired")) {
          if (!BSON_ITER_HOLDS_BOOL (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Expected a bool for 'cryptSharedLibRequired'");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Expected a bool for 'cryptSharedLibRequired'");
             GOTO (fail);
          }
          topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibRequired = bson_iter_bool_unsafe (&iter);
@@ -1749,52 +1740,52 @@ _mongoc_cse_client_enable_auto_encryptio
 
    BSON_ASSERT (client);
    if (!client->topology->single_threaded) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Automatic encryption on pooled clients must be set on the pool");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Automatic encryption on pooled clients must be set on the pool");
       GOTO (fail);
    }
 
    if (!opts) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Auto encryption options required");
       GOTO (fail);
    }
 
    if (opts->keyvault_client_pool) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "The key vault client pool only applies to a client "
-                      "pool, not a single threaded client");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "The key vault client pool only applies to a client "
+                         "pool, not a single threaded client");
       GOTO (fail);
    }
 
    if (opts->keyvault_client && !opts->keyvault_client->topology->single_threaded) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "The key vault client must be single threaded, not be "
-                      "from a client pool");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "The key vault client must be single threaded, not be "
+                         "from a client pool");
       GOTO (fail);
    }
 
    /* Check for required options */
    if (!opts->keyvault_db || !opts->keyvault_coll) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Key vault namespace option required");
       GOTO (fail);
    }
 
    if (!opts->kms_providers) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required");
       GOTO (fail);
    }
 
    if (client->topology->cse_state != MONGOC_CSE_DISABLED) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set");
       GOTO (fail);
    } else {
@@ -1848,10 +1839,10 @@ _mongoc_cse_client_enable_auto_encryptio
       client->topology->mongocryptd_client = mongoc_client_new_from_uri (mongocryptd_uri);
 
       if (!client->topology->mongocryptd_client) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "Unable to create client to mongocryptd");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "Unable to create client to mongocryptd");
          GOTO (fail);
       }
       /* Similarly, single threaded clients will by default wait for 5 second
@@ -1897,29 +1888,29 @@ _mongoc_cse_client_pool_enable_auto_encr
 
    BSON_ASSERT (topology);
    if (!opts) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Auto encryption options required");
       GOTO (fail);
    }
 
    if (opts->keyvault_client) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "The key vault client only applies to a single threaded "
-                      "client not a client pool. Set a key vault client pool");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "The key vault client only applies to a single threaded "
+                         "client not a client pool. Set a key vault client pool");
       GOTO (fail);
    }
 
    /* Check for required options */
    if (!opts->keyvault_db || !opts->keyvault_coll) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Key vault namespace option required");
       GOTO (fail);
    }
 
    if (!opts->kms_providers) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required");
       GOTO (fail);
    }
@@ -1929,13 +1920,13 @@ _mongoc_cse_client_pool_enable_auto_encr
    while (prev_cse_state == MONGOC_CSE_STARTING) {
       /* Another thread is starting client-side encryption. It may take some
        * time to start, but don't continue until it is finished. */
-      bson_thrd_yield ();
+      mcommon_thrd_yield ();
       prev_cse_state = mcommon_atomic_int_compare_exchange_strong (
          (int *) &topology->cse_state, MONGOC_CSE_DISABLED, MONGOC_CSE_STARTING, mcommon_memory_order_acquire);
    }
 
    if (prev_cse_state == MONGOC_CSE_ENABLED) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set");
       GOTO (fail);
    }
@@ -1974,10 +1965,10 @@ _mongoc_cse_client_pool_enable_auto_encr
       topology->mongocryptd_client_pool = mongoc_client_pool_new (mongocryptd_uri);
 
       if (!topology->mongocryptd_client_pool) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "Unable to create client pool to mongocryptd");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "Unable to create client pool to mongocryptd");
          GOTO (fail);
       }
    }
@@ -2020,15 +2011,15 @@ mongoc_client_encryption_new (mongoc_cli
 
    /* Check for required options */
    if (!opts || !opts->keyvault_client || !opts->keyvault_db || !opts->keyvault_coll) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Key vault client and namespace option required");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Key vault client and namespace option required");
       goto fail;
    }
 
    if (!opts->kms_providers) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required");
       goto fail;
    }
@@ -2117,7 +2108,8 @@ mongoc_client_encryption_create_datakey
    BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll));
 
    if (!opts) {
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset");
       GOTO (fail);
    }
 
@@ -2150,16 +2142,16 @@ mongoc_client_encryption_create_datakey
       const bson_value_t *id_value;
 
       if (!bson_iter_init_find (&iter, &datakey, "_id")) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "data key not did not contain _id");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "data key not did not contain _id");
          GOTO (fail);
       } else if (!BSON_ITER_HOLDS_BINARY (&iter)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "data key _id does not contain binary");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "data key _id does not contain binary");
          GOTO (fail);
       } else {
          id_value = bson_iter_value (&iter);
@@ -2201,10 +2193,10 @@ mongoc_client_encryption_rewrap_many_dat
    bson_reinit (bulk_write_result);
 
    if (master_key && !provider) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "expected 'provider' to be set to identify type of 'master_key'");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "expected 'provider' to be set to identify type of 'master_key'");
       GOTO (fail);
    }
 
@@ -2225,18 +2217,18 @@ mongoc_client_encryption_rewrap_many_dat
    BSON_ASSERT (bulk);
 
    if (!bson_iter_init_find (&iter, &keys, "v")) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "result did not contain expected field 'v'");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "result did not contain expected field 'v'");
       GOTO (fail);
    }
 
    if (!BSON_ITER_HOLDS_ARRAY (&iter)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "result did not return an array as expected");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "result did not return an array as expected");
       GOTO (fail);
    }
 
@@ -2255,30 +2247,30 @@ mongoc_client_encryption_rewrap_many_dat
       bson_iter_document (&iter, &len, &data);
 
       if (!data || !bson_init_static (&key, data, len)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "element is not a valid BSON document");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "element is not a valid BSON document");
          goto doc_done;
       }
 
       /* Find _id and use as selector. */
       {
          if (!bson_iter_init_find (&key_iter, &key, "_id")) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                            "could not find _id in key document");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                               "could not find _id in key document");
             goto doc_done;
          }
 
          bson_iter_binary (&key_iter, &subtype, &len, &data);
 
          if (!data || subtype != BSON_SUBTYPE_UUID) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                            "expected _id in key document to be a UUID");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                               "expected _id in key document to be a UUID");
             goto doc_done;
          }
 
@@ -2488,10 +2480,10 @@ mongoc_client_encryption_add_key_alt_nam
             bson_copy_to (&bson, key_doc);
             bson_destroy (&bson);
          } else {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                            "expected field value to be a document or null");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                               "expected field value to be a document or null");
             ret = false;
          }
       }
@@ -2585,10 +2577,10 @@ mongoc_client_encryption_remove_key_alt_
             bson_copy_to (&bson, key_doc);
             bson_destroy (&bson);
          } else {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                            "expected field value to be a document or null");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                               "expected field value to be a document or null");
             ret = false;
          }
       }
@@ -2656,7 +2648,7 @@ mongoc_client_encryption_encrypt (mongoc
    BSON_ASSERT (client_encryption);
 
    if (!ciphertext) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'ciphertext' unset");
       GOTO (fail);
    }
@@ -2665,7 +2657,8 @@ mongoc_client_encryption_encrypt (mongoc
    ciphertext->value_type = BSON_TYPE_EOD;
 
    if (!opts) {
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset");
       GOTO (fail);
    }
 
@@ -2749,7 +2742,8 @@ mongoc_client_encryption_decrypt (mongoc
    BSON_ASSERT (client_encryption);
 
    if (!value) {
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'value' unset");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'value' unset");
       GOTO (fail);
    }
 
@@ -2758,10 +2752,10 @@ mongoc_client_encryption_decrypt (mongoc
    value->value_type = BSON_TYPE_EOD;
 
    if (ciphertext->value_type != BSON_TYPE_BINARY || ciphertext->value.v_binary.subtype != BSON_SUBTYPE_ENCRYPTED) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "ciphertext must be BSON binary subtype 6");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "ciphertext must be BSON binary subtype 6");
       GOTO (fail);
    }
 
@@ -2787,7 +2781,7 @@ _mongoc_cse_is_enabled (mongoc_client_t
          return state == MONGOC_CSE_ENABLED;
       }
       /* CSE is starting up. Wait until that succeeds or fails. */
-      bson_thrd_yield ();
+      mcommon_thrd_yield ();
    }
 }
 
@@ -2858,12 +2852,12 @@ mongoc_client_encryption_create_encrypte
    }
 
    if (bson_empty (&in_encryptedFields)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "No 'encryptedFields' are defined for the creation of "
-                      "the '%s' collection",
-                      name);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "No 'encryptedFields' are defined for the creation of "
+                         "the '%s' collection",
+                         name);
       goto done;
    }
 
@@ -2905,11 +2899,11 @@ mongoc_client_encryption_create_encrypte
               kv ("encryptedFields", bson (new_encryptedFields)));
    if (bsonBuildError) {
       // Error while building the new options.
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Error while building new createCollection options: %s",
-                      bsonBuildError);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Error while building new createCollection options: %s",
+                         bsonBuildError);
       goto done;
    }
 
@@ -2987,11 +2981,11 @@ _init_encryptedFields (
       // The factory/internal code did not set error, so we may have to set it
       // for an error while BSON parsing/generating.
       if (bsonParseError) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while generating datakeys: %s", bsonParseError);
       }
       if (bsonBuildError) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while generating datakeys: %s", bsonBuildError);
       }
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h	2025-06-19 15:42:22.000000000 +0000
@@ -45,10 +45,10 @@ BSON_BEGIN_DECLS
 
 typedef struct _mongoc_auto_encryption_opts_t mongoc_auto_encryption_opts_t;
 
-typedef bool (*mongoc_kms_credentials_provider_callback_fn) (void *userdata,
-                                                             const bson_t *params,
-                                                             bson_t *out,
-                                                             bson_error_t *error);
+typedef bool (BSON_CALL *mongoc_kms_credentials_provider_callback_fn) (void *userdata,
+                                                                       const bson_t *params,
+                                                                       bson_t *out,
+                                                                       bson_error_t *error);
 
 MONGOC_EXPORT (mongoc_auto_encryption_opts_t *)
 mongoc_auto_encryption_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client.c	2025-06-19 15:42:22.000000000 +0000
@@ -37,7 +37,6 @@
 #include <mongoc/mongoc-counters-private.h>
 #include <mongoc/mongoc-database-private.h>
 #include <mongoc/mongoc-gridfs-private.h>
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-queue-private.h>
@@ -72,7 +71,7 @@
 #endif
 
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <inttypes.h>
 
@@ -81,14 +80,6 @@
 
 
 static void
-_mongoc_client_op_killcursors (mongoc_cluster_t *cluster,
-                               mongoc_server_stream_t *server_stream,
-                               int64_t cursor_id,
-                               int64_t operation_id,
-                               const char *db,
-                               const char *collection);
-
-static void
 _mongoc_client_killcursors_command (mongoc_cluster_t *cluster,
                                     mongoc_server_stream_t *server_stream,
                                     int64_t cursor_id,
@@ -96,10 +87,10 @@ _mongoc_client_killcursors_command (mong
                                     const char *collection,
                                     mongoc_client_session_t *cs);
 
-#define DNS_ERROR(_msg, ...)                                                                               \
-   do {                                                                                                    \
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, _msg, __VA_ARGS__); \
-      GOTO (done);                                                                                         \
+#define DNS_ERROR(_msg, ...)                                                                                  \
+   do {                                                                                                       \
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, _msg, __VA_ARGS__); \
+      GOTO (done);                                                                                            \
    } while (0)
 
 
@@ -211,13 +202,10 @@ _mongoc_get_rr_dnsapi (
    res = DnsQuery_UTF8 (hostname, nst, options, NULL /* IP Address */, &pdns, 0 /* reserved */);
 
    if (res) {
-      DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
-
-      if (FormatMessage (flags, 0, res, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, 0)) {
-         DNS_ERROR ("Failed to look up %s record \"%s\": %s", rr_type_name, hostname, (char *) lpMsgBuf);
-      }
-
-      DNS_ERROR ("Failed to look up %s record \"%s\": Unknown error", rr_type_name, hostname);
+      // Cast signed DNS_STATUS to unsigned DWORD. FormatMessage expects DWORD.
+      char *msg = mongoc_winerr_to_string ((DWORD) res);
+      DNS_ERROR ("Failed to look up %s record \"%s\": %s", rr_type_name, hostname, msg);
+      bson_free (msg);
    }
 
    if (!pdns) {
@@ -460,7 +448,7 @@ _mongoc_get_rr_search (const char *hostn
       if (size < 0) {
          DNS_ERROR ("Failed to look up %s record \"%s\": %s", rr_type_name, hostname, _mongoc_hstrerror (h_errno));
       }
-   } while (size >= buffer_size);
+   } while (mlib_cmp (size, >=, buffer_size));
 
    if (ns_initparse (search_buf, size, &ns_answer)) {
       DNS_ERROR ("Invalid %s answer for \"%s\"", rr_type_name, hostname);
@@ -572,10 +560,10 @@ _mongoc_client_get_rr (const char *hostn
 
 #if MONGOC_ENABLE_SRV == 0
    // Disabled
-   bson_set_error (error,
-                   MONGOC_ERROR_STREAM,
-                   MONGOC_ERROR_STREAM_NAME_RESOLUTION,
-                   "libresolv unavailable, cannot use mongodb+srv URI");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_STREAM,
+                      MONGOC_ERROR_STREAM_NAME_RESOLUTION,
+                      "libresolv unavailable, cannot use mongodb+srv URI");
    return false;
 #elif defined(MONGOC_HAVE_DNSAPI)
    return _mongoc_get_rr_dnsapi (hostname, rr_type, rr_data, prefer_tcp, error);
@@ -625,7 +613,7 @@ mongoc_client_connect_tcp (int32_t conne
 
    // Expect no truncation.
    int req = bson_snprintf (portstr, sizeof portstr, "%hu", host->port);
-   BSON_ASSERT (mcommon_cmp_less_su (req, sizeof portstr));
+   BSON_ASSERT (mlib_cmp (req, <, sizeof portstr));
 
    memset (&hints, 0, sizeof hints);
    hints.ai_family = host->family;
@@ -639,7 +627,7 @@ mongoc_client_connect_tcp (int32_t conne
    if (s != 0) {
       mongoc_counter_dns_failure_inc ();
       TRACE ("Failed to resolve %s", host->host);
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve %s", host->host);
       RETURN (NULL);
    }
@@ -668,11 +656,11 @@ mongoc_client_connect_tcp (int32_t conne
    }
 
    if (!sock) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_CONNECT,
-                      "Failed to connect to target host: %s",
-                      host->host_and_port);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_CONNECT,
+                         "Failed to connect to target host: %s",
+                         host->host_and_port);
       freeaddrinfo (result);
       RETURN (NULL);
    }
@@ -705,7 +693,7 @@ mongoc_client_connect_unix (const mongoc
 {
 #ifdef _WIN32
    ENTRY;
-   bson_set_error (
+   _mongoc_set_error (
       error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "UNIX domain sockets not supported on win32.");
    RETURN (NULL);
 #else
@@ -722,21 +710,22 @@ mongoc_client_connect_unix (const mongoc
    // Expect no truncation.
    int req = bson_snprintf (saddr.sun_path, sizeof saddr.sun_path - 1, "%s", host->host);
 
-   if (mcommon_cmp_greater_equal_su (req, sizeof saddr.sun_path - 1)) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to define socket address path.");
+   if (mlib_cmp (req, >=, sizeof saddr.sun_path - 1)) {
+      _mongoc_set_error (
+         error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to define socket address path.");
       RETURN (NULL);
    }
 
    sock = mongoc_socket_new (AF_UNIX, SOCK_STREAM, 0);
 
    if (sock == NULL) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket.");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket.");
       RETURN (NULL);
    }
 
    if (-1 == mongoc_socket_connect (sock, (struct sockaddr *) &saddr, sizeof saddr, -1)) {
       mongoc_socket_destroy (sock);
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to connect to UNIX domain socket.");
       RETURN (NULL);
    }
@@ -764,10 +753,10 @@ mongoc_client_connect (bool buffered,
 
 #ifndef MONGOC_ENABLE_SSL
    if (ssl_opts_void || mongoc_uri_get_tls (uri)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_NO_ACCEPTABLE_PEER,
-                      "TLS is not enabled in this build of mongo-c-driver.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_NO_ACCEPTABLE_PEER,
+                         "TLS is not enabled in this build of mongo-c-driver.");
       return NULL;
    }
 #endif
@@ -787,11 +776,11 @@ mongoc_client_connect (bool buffered,
       base_stream = mongoc_client_connect_unix (host, error);
       break;
    default:
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_INVALID_TYPE,
-                      "Invalid address family: 0x%02x",
-                      (unsigned int) host->family);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_INVALID_TYPE,
+                         "Invalid address family: 0x%02x",
+                         (unsigned int) host->family);
       break;
    }
 
@@ -816,7 +805,7 @@ mongoc_client_connect (bool buffered,
 
          if (!base_stream) {
             mongoc_stream_destroy (original);
-            bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed initialize TLS state.");
+            _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed initialize TLS state.");
             return NULL;
          }
 
@@ -993,7 +982,22 @@ void
 mongoc_client_set_ssl_opts (mongoc_client_t *client, const mongoc_ssl_opt_t *opts)
 {
    BSON_ASSERT_PARAM (client);
-   BSON_ASSERT (opts);
+   BSON_ASSERT_PARAM (opts);
+
+   if (!client->topology->single_threaded) {
+      MONGOC_ERROR (
+         "mongoc_client_set_ssl_opts cannot be called on a pooled client. Use mongoc_client_pool_set_ssl_opts.");
+      return;
+   }
+
+   _mongoc_client_set_ssl_opts_for_single_or_pooled (client, opts);
+}
+
+void
+_mongoc_client_set_ssl_opts_for_single_or_pooled (mongoc_client_t *client, const mongoc_ssl_opt_t *opts)
+{
+   BSON_ASSERT_PARAM (client);
+   BSON_ASSERT_PARAM (opts);
 
    _mongoc_ssl_opts_cleanup (&client->ssl_opts, false /* don't free internal opts */);
 
@@ -1011,7 +1015,7 @@ mongoc_client_set_ssl_opts (mongoc_clien
 #endif
    }
 }
-#endif
+#endif // MONGOC_ENABLE_SSL
 
 
 mongoc_client_t *
@@ -1039,12 +1043,21 @@ mongoc_client_new_from_uri_with_error (c
 
    BSON_ASSERT (uri);
 
+   extern bool mongoc_get_init_called (void);
+   if (!mongoc_get_init_called ()) {
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_NOT_READY,
+                         "Attempting to create client, but libmongoc not initialized. Call mongoc_init");
+      return NULL;
+   }
+
 #ifndef MONGOC_ENABLE_SSL
    if (mongoc_uri_get_tls (uri)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Can't create SSL client, SSL not enabled in this build.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Can't create SSL client, SSL not enabled in this build.");
       RETURN (NULL);
    }
 #endif
@@ -1117,7 +1130,7 @@ _mongoc_client_new_from_topology (mongoc
       _mongoc_ssl_opts_from_uri (&ssl_opt, &internal_tls_opts, client->uri);
       /* sets use_ssl = true */
       /* this call creates an ssl ctx only if single-threaded, otherwise client inherits from pool */
-      mongoc_client_set_ssl_opts (client, &ssl_opt);
+      _mongoc_client_set_ssl_opts_for_single_or_pooled (client, &ssl_opt);
       _mongoc_client_set_internal_tls_opts (client, &internal_tls_opts);
    }
 #endif
@@ -1252,10 +1265,10 @@ mongoc_client_start_session (mongoc_clie
 
    /* causal consistency and snapshot cannot both be set. */
    if (opts && mongoc_session_opts_get_causal_consistency (opts) && mongoc_session_opts_get_snapshot (opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_SESSION_FAILURE,
-                      "Only one of causal consistency and snapshot can be enabled.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_SESSION_FAILURE,
+                         "Only one of causal consistency and snapshot can be enabled.");
       _mongoc_client_push_server_session (client, ss);
       RETURN (NULL);
    }
@@ -1576,45 +1589,6 @@ mongoc_client_set_read_prefs (mongoc_cli
    }
 }
 
-mongoc_cursor_t *
-mongoc_client_command (mongoc_client_t *client,
-                       const char *db_name,
-                       mongoc_query_flags_t flags,
-                       uint32_t skip,
-                       uint32_t limit,
-                       uint32_t batch_size,
-                       const bson_t *query,
-                       const bson_t *fields,
-                       const mongoc_read_prefs_t *read_prefs)
-{
-   char *ns = NULL;
-   mongoc_cursor_t *cursor;
-
-   BSON_UNUSED (flags);
-   BSON_UNUSED (skip);
-   BSON_UNUSED (limit);
-   BSON_UNUSED (batch_size);
-   BSON_UNUSED (fields);
-
-   BSON_ASSERT_PARAM (client);
-   BSON_ASSERT (db_name);
-   BSON_ASSERT (query);
-
-   /*
-    * Allow a caller to provide a fully qualified namespace
-    */
-   if (NULL == strstr (db_name, "$cmd")) {
-      ns = bson_strdup_printf ("%s.$cmd", db_name);
-      db_name = ns;
-   }
-
-   cursor = _mongoc_cursor_cmd_deprecated_new (client, db_name, query, read_prefs);
-
-   bson_free (ns);
-   return cursor;
-}
-
-
 static bool
 _mongoc_client_retryable_read_command_with_stream (mongoc_client_t *client,
                                                    mongoc_cmd_parts_t *parts,
@@ -1862,33 +1836,33 @@ _mongoc_client_command_with_opts (mongoc
    cs = read_write_opts.client_session;
 
    if (!command_name) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document");
       GOTO (done);
    }
 
    if (_mongoc_client_session_in_txn (read_write_opts.client_session)) {
       if ((mode == MONGOC_CMD_READ || mode == MONGOC_CMD_RAW) && !IS_PREF_PRIMARY (user_prefs)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Read preference in a transaction must be primary");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Read preference in a transaction must be primary");
          GOTO (done);
       }
 
       if (!bson_empty (&read_write_opts.readConcern)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot set read concern after starting transaction");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot set read concern after starting transaction");
          GOTO (done);
       }
 
       if (read_write_opts.writeConcern && strcmp (command_name, "commitTransaction") != 0 &&
           strcmp (command_name, "abortTransaction") != 0) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot set write concern after starting transaction");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot set write concern after starting transaction");
          GOTO (done);
       }
    }
@@ -2137,6 +2111,8 @@ _mongoc_client_kill_cursor (mongoc_clien
    ENTRY;
 
    BSON_ASSERT_PARAM (client);
+   BSON_ASSERT_PARAM (db);
+   BSON_ASSERT_PARAM (collection);
    BSON_ASSERT (cursor_id);
 
    /* don't attempt reconnect if server unavailable, and ignore errors */
@@ -2147,11 +2123,7 @@ _mongoc_client_kill_cursor (mongoc_clien
       return;
    }
 
-   if (db && collection) {
-      _mongoc_client_killcursors_command (&client->cluster, server_stream, cursor_id, db, collection, cs);
-   } else {
-      _mongoc_client_op_killcursors (&client->cluster, server_stream, cursor_id, operation_id, db, collection);
-   }
+   _mongoc_client_killcursors_command (&client->cluster, server_stream, cursor_id, db, collection, cs);
 
    mongoc_server_stream_cleanup (server_stream);
 
@@ -2160,197 +2132,6 @@ _mongoc_client_kill_cursor (mongoc_clien
 
 
 static void
-_mongoc_client_monitor_op_killcursors (mongoc_cluster_t *cluster,
-                                       mongoc_server_stream_t *server_stream,
-                                       int64_t cursor_id,
-                                       int64_t operation_id,
-                                       const char *db,
-                                       const char *collection)
-{
-   bson_t doc;
-   mongoc_apm_command_started_t event;
-
-   ENTRY;
-
-   mongoc_client_t *client = cluster->client;
-   const mongoc_log_and_monitor_instance_t *log_and_monitor = &client->topology->log_and_monitor;
-
-   if (!log_and_monitor->apm_callbacks.started) {
-      return;
-   }
-
-   bson_init (&doc);
-   _mongoc_client_prepare_killcursors_command (cursor_id, collection, &doc);
-   mongoc_apm_command_started_init (&event,
-                                    &doc,
-                                    db,
-                                    "killCursors",
-                                    cluster->request_id,
-                                    operation_id,
-                                    &server_stream->sd->host,
-                                    server_stream->sd->id,
-                                    &server_stream->sd->service_id,
-                                    server_stream->sd->server_connection_id,
-                                    NULL,
-                                    log_and_monitor->apm_context);
-
-   log_and_monitor->apm_callbacks.started (&event);
-   mongoc_apm_command_started_cleanup (&event);
-   bson_destroy (&doc);
-
-   EXIT;
-}
-
-
-static void
-_mongoc_client_monitor_op_killcursors_succeeded (mongoc_cluster_t *cluster,
-                                                 int64_t duration,
-                                                 mongoc_server_stream_t *server_stream,
-                                                 int64_t cursor_id,
-                                                 int64_t operation_id,
-                                                 const char *db)
-{
-   bson_t doc;
-   bson_array_builder_t *cursors_unknown;
-   mongoc_apm_command_succeeded_t event;
-
-   ENTRY;
-
-   mongoc_client_t *client = cluster->client;
-   const mongoc_log_and_monitor_instance_t *log_and_monitor = &client->topology->log_and_monitor;
-
-   if (!log_and_monitor->apm_callbacks.succeeded) {
-      EXIT;
-   }
-
-   /* fake server reply to killCursors command: {ok: 1, cursorsUnknown: [42]} */
-   bson_init (&doc);
-   bson_append_int32 (&doc, "ok", 2, 1);
-   bson_append_array_builder_begin (&doc, "cursorsUnknown", 14, &cursors_unknown);
-   bson_array_builder_append_int64 (cursors_unknown, cursor_id);
-   bson_append_array_builder_end (&doc, cursors_unknown);
-
-   mongoc_apm_command_succeeded_init (&event,
-                                      duration,
-                                      &doc,
-                                      "killCursors",
-                                      db,
-                                      cluster->request_id,
-                                      operation_id,
-                                      &server_stream->sd->host,
-                                      server_stream->sd->id,
-                                      &server_stream->sd->service_id,
-                                      server_stream->sd->server_connection_id,
-                                      false,
-                                      log_and_monitor->apm_context);
-
-   log_and_monitor->apm_callbacks.succeeded (&event);
-
-   mongoc_apm_command_succeeded_cleanup (&event);
-   bson_destroy (&doc);
-}
-
-
-static void
-_mongoc_client_monitor_op_killcursors_failed (mongoc_cluster_t *cluster,
-                                              int64_t duration,
-                                              mongoc_server_stream_t *server_stream,
-                                              const bson_error_t *error,
-                                              int64_t operation_id,
-                                              const char *db)
-{
-   bson_t doc;
-   mongoc_apm_command_failed_t event;
-
-   ENTRY;
-
-   mongoc_client_t *client = cluster->client;
-   const mongoc_log_and_monitor_instance_t *log_and_monitor = &client->topology->log_and_monitor;
-
-   if (!log_and_monitor->apm_callbacks.failed) {
-      EXIT;
-   }
-
-   /* fake server reply to killCursors command: {ok: 0} */
-   bson_init (&doc);
-   bson_append_int32 (&doc, "ok", 2, 0);
-
-   mongoc_apm_command_failed_init (&event,
-                                   duration,
-                                   "killCursors",
-                                   db,
-                                   error,
-                                   &doc,
-                                   cluster->request_id,
-                                   operation_id,
-                                   &server_stream->sd->host,
-                                   server_stream->sd->id,
-                                   &server_stream->sd->service_id,
-                                   server_stream->sd->server_connection_id,
-                                   false,
-                                   log_and_monitor->apm_context);
-
-   log_and_monitor->apm_callbacks.failed (&event);
-
-   mongoc_apm_command_failed_cleanup (&event);
-   bson_destroy (&doc);
-}
-
-
-static void
-_mongoc_client_op_killcursors (mongoc_cluster_t *cluster,
-                               mongoc_server_stream_t *server_stream,
-                               int64_t cursor_id,
-                               int64_t operation_id,
-                               const char *db,
-                               const char *collection)
-{
-   BSON_ASSERT_PARAM (cluster);
-   BSON_ASSERT_PARAM (server_stream);
-   BSON_OPTIONAL_PARAM (db);
-   BSON_OPTIONAL_PARAM (collection);
-
-   const bool has_ns = db && collection;
-   const int64_t started = bson_get_monotonic_time ();
-
-   mcd_rpc_message *const rpc = mcd_rpc_message_new ();
-
-   {
-      int32_t message_length = 0;
-
-      message_length += mcd_rpc_header_set_message_length (rpc, 0);
-      message_length += mcd_rpc_header_set_request_id (rpc, ++cluster->request_id);
-      message_length += mcd_rpc_header_set_response_to (rpc, 0);
-      message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_KILL_CURSORS);
-
-      message_length += sizeof (int32_t); // ZERO
-      message_length += mcd_rpc_op_kill_cursors_set_cursor_ids (rpc, &cursor_id, 1);
-
-      mcd_rpc_message_set_length (rpc, message_length);
-   }
-
-   if (has_ns) {
-      _mongoc_client_monitor_op_killcursors (cluster, server_stream, cursor_id, operation_id, db, collection);
-   }
-
-   bson_error_t error;
-   const bool res = mongoc_cluster_legacy_rpc_sendv_to_server (cluster, rpc, server_stream, &error);
-
-   if (has_ns) {
-      if (res) {
-         _mongoc_client_monitor_op_killcursors_succeeded (
-            cluster, bson_get_monotonic_time () - started, server_stream, cursor_id, operation_id, db);
-      } else {
-         _mongoc_client_monitor_op_killcursors_failed (
-            cluster, bson_get_monotonic_time () - started, server_stream, &error, operation_id, db);
-      }
-   }
-
-   mcd_rpc_message_destroy (rpc);
-}
-
-
-static void
 _mongoc_client_killcursors_command (mongoc_cluster_t *cluster,
                                     mongoc_server_stream_t *server_stream,
                                     int64_t cursor_id,
@@ -2382,75 +2163,6 @@ _mongoc_client_killcursors_command (mong
 }
 
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_client_kill_cursor --
- *
- *       Destroy a cursor on the server.
- *
- *       NOTE: this is only reliable when connected to a single mongod or
- *       mongos. If connected to a replica set, the driver attempts to
- *       kill the cursor on the primary. If connected to multiple mongoses
- *       the kill-cursors message is sent to a *random* mongos.
- *
- *       If no primary, mongos, or standalone server is known, return
- *       without attempting to reconnect.
- *
- * Returns:
- *       None.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-void
-mongoc_client_kill_cursor (mongoc_client_t *client, int64_t cursor_id)
-{
-   BSON_ASSERT_PARAM (client);
-
-   mongoc_topology_t *const topology = BSON_ASSERT_PTR_INLINE (client)->topology;
-   mongoc_server_description_t const *selected_server;
-   mongoc_read_prefs_t *read_prefs;
-   bson_error_t error;
-   uint32_t server_id = 0;
-   mc_shared_tpld td = mc_tpld_take_ref (topology);
-
-   read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);
-
-   if (!mongoc_topology_compatible (td.ptr, NULL, &error)) {
-      MONGOC_ERROR ("Could not kill cursor: %s", error.message);
-      mc_tpld_drop_ref (&td);
-      mongoc_read_prefs_destroy (read_prefs);
-      return;
-   }
-
-   /* see if there's a known writable server - do no I/O or retries */
-   selected_server = mongoc_topology_description_select (td.ptr,
-                                                         MONGOC_SS_WRITE,
-                                                         read_prefs,
-                                                         NULL /* chosen read mode */,
-                                                         NULL /* deprioritized servers */,
-                                                         topology->local_threshold_msec);
-
-   if (selected_server) {
-      server_id = selected_server->id;
-   }
-
-   if (server_id) {
-      _mongoc_client_kill_cursor (
-         client, server_id, cursor_id, 0 /* operation_id */, NULL /* db */, NULL /* collection */, NULL /* session */);
-   } else {
-      MONGOC_INFO ("No server available for mongoc_client_kill_cursor");
-   }
-
-   mongoc_read_prefs_destroy (read_prefs);
-   mc_tpld_drop_ref (&td);
-}
-
-
 char **
 mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error)
 {
@@ -2521,45 +2233,23 @@ mongoc_client_find_databases_with_opts (
 }
 
 
-int32_t
-mongoc_client_get_max_message_size (mongoc_client_t *client) /* IN */
-{
-   BSON_ASSERT_PARAM (client);
-
-   return mongoc_cluster_get_max_msg_size (&client->cluster);
-}
-
-
-int32_t
-mongoc_client_get_max_bson_size (mongoc_client_t *client) /* IN */
-{
-   BSON_ASSERT_PARAM (client);
-
-   return mongoc_cluster_get_max_bson_obj_size (&client->cluster);
-}
-
-
-bool
-mongoc_client_get_server_status (mongoc_client_t *client,         /* IN */
-                                 mongoc_read_prefs_t *read_prefs, /* IN */
-                                 bson_t *reply,                   /* OUT */
-                                 bson_error_t *error)             /* OUT */
+void
+mongoc_client_set_stream_initiator (mongoc_client_t *client, mongoc_stream_initiator_t initiator, void *user_data)
 {
-   bson_t cmd = BSON_INITIALIZER;
-   bool ret = false;
-
    BSON_ASSERT_PARAM (client);
 
-   BSON_APPEND_INT32 (&cmd, "serverStatus", 1);
-   ret = mongoc_client_command_simple (client, "admin", &cmd, read_prefs, reply, error);
-   bson_destroy (&cmd);
+   if (!client->topology->single_threaded) {
+      MONGOC_ERROR ("mongoc_client_set_stream_initiator cannot be called on a pooled client.");
+      return;
+   }
 
-   return ret;
+   _mongoc_client_set_stream_initiator_single_or_pooled (client, initiator, user_data);
 }
 
-
 void
-mongoc_client_set_stream_initiator (mongoc_client_t *client, mongoc_stream_initiator_t initiator, void *user_data)
+_mongoc_client_set_stream_initiator_single_or_pooled (mongoc_client_t *client,
+                                                      mongoc_stream_initiator_t initiator,
+                                                      void *user_data)
 {
    BSON_ASSERT_PARAM (client);
 
@@ -2666,10 +2356,10 @@ mongoc_client_select_server (mongoc_clie
    mongoc_server_description_t *sd;
 
    if (for_writes && prefs) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SERVER_SELECTION,
-                      MONGOC_ERROR_SERVER_SELECTION_FAILURE,
-                      "Cannot use read preferences with for_writes = true");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SERVER_SELECTION,
+                         MONGOC_ERROR_SERVER_SELECTION_FAILURE,
+                         "Cannot use read preferences with for_writes = true");
       return NULL;
    }
 
@@ -2782,7 +2472,7 @@ _mongoc_client_lookup_session (const mon
       RETURN (true);
    }
 
-   bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId");
+   _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId");
 
    RETURN (false);
 }
@@ -2923,11 +2613,11 @@ mongoc_client_enable_auto_encryption (mo
    BSON_ASSERT_PARAM (client);
 
    if (!client->topology->single_threaded) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Cannot enable auto encryption on a pooled client, use "
-                      "mongoc_client_pool_enable_auto_encryption");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Cannot enable auto encryption on a pooled client, use "
+                         "mongoc_client_pool_enable_auto_encryption");
       return false;
    }
    return _mongoc_cse_client_enable_auto_encryption (client, opts, error);
@@ -2940,18 +2630,18 @@ mongoc_client_set_server_api (mongoc_cli
    BSON_ASSERT_PARAM (api);
 
    if (!client->topology->single_threaded) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_API_FROM_POOL,
-                      "Cannot set server api on a client checked out from a pool");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_API_FROM_POOL,
+                         "Cannot set server api on a client checked out from a pool");
       return false;
    }
 
    if (mongoc_client_uses_server_api (client)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_API_ALREADY_SET,
-                      "Cannot set server api more than once per client");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_API_ALREADY_SET,
+                         "Cannot set server api more than once per client");
       return false;
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-client.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-client.h	2025-06-19 15:42:22.000000000 +0000
@@ -28,7 +28,6 @@
 #include <mongoc/mongoc-cursor.h>
 #include <mongoc/mongoc-database.h>
 #include <mongoc/mongoc-gridfs.h>
-#include <mongoc/mongoc-index.h>
 #include <mongoc/mongoc-macros.h>
 #include <mongoc/mongoc-read-prefs.h>
 #include <mongoc/mongoc-server-api.h>
@@ -96,37 +95,30 @@ typedef struct _mongoc_transaction_opt_t
  *
  * Returns: A newly allocated mongoc_stream_t or NULL on failure.
  */
-typedef mongoc_stream_t *(*mongoc_stream_initiator_t) (const mongoc_uri_t *uri,
-                                                       const mongoc_host_list_t *host,
-                                                       void *user_data,
-                                                       bson_error_t *error);
+typedef mongoc_stream_t *(BSON_CALL *mongoc_stream_initiator_t) (const mongoc_uri_t *uri,
+                                                                 const mongoc_host_list_t *host,
+                                                                 void *user_data,
+                                                                 bson_error_t *error);
 
 
 MONGOC_EXPORT (mongoc_client_t *)
 mongoc_client_new (const char *uri_string) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_client_t *)
 mongoc_client_new_from_uri (const mongoc_uri_t *uri) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_client_t *)
 mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_client_set_sockettimeoutms (mongoc_client_t *client, int32_t timeoutms);
+
 MONGOC_EXPORT (const mongoc_uri_t *)
 mongoc_client_get_uri (const mongoc_client_t *client);
+
 MONGOC_EXPORT (void)
 mongoc_client_set_stream_initiator (mongoc_client_t *client, mongoc_stream_initiator_t initiator, void *user_data);
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_client_command (mongoc_client_t *client,
-                       const char *db_name,
-                       mongoc_query_flags_t flags,
-                       uint32_t skip,
-                       uint32_t limit,
-                       uint32_t batch_size,
-                       const bson_t *query,
-                       const bson_t *fields,
-                       const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_client_command_simple);
-MONGOC_EXPORT (void)
-mongoc_client_kill_cursor (mongoc_client_t *client, int64_t cursor_id) BSON_GNUC_DEPRECATED;
+
 MONGOC_EXPORT (bool)
 mongoc_client_command_simple (mongoc_client_t *client,
                               const char *db_name,
@@ -134,6 +126,7 @@ mongoc_client_command_simple (mongoc_cli
                               const mongoc_read_prefs_t *read_prefs,
                               bson_t *reply,
                               bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_read_command_with_opts (mongoc_client_t *client,
                                       const char *db_name,
@@ -142,6 +135,7 @@ mongoc_client_read_command_with_opts (mo
                                       const bson_t *opts,
                                       bson_t *reply,
                                       bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_write_command_with_opts (mongoc_client_t *client,
                                        const char *db_name,
@@ -149,6 +143,7 @@ mongoc_client_write_command_with_opts (m
                                        const bson_t *opts,
                                        bson_t *reply,
                                        bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_read_write_command_with_opts (mongoc_client_t *client,
                                             const char *db_name,
@@ -157,6 +152,7 @@ mongoc_client_read_write_command_with_op
                                             const bson_t *opts,
                                             bson_t *reply,
                                             bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_command_with_opts (mongoc_client_t *client,
                                  const char *db_name,
@@ -165,6 +161,7 @@ mongoc_client_command_with_opts (mongoc_
                                  const bson_t *opts,
                                  bson_t *reply,
                                  bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_client_command_simple_with_server_id (mongoc_client_t *client,
                                              const char *db_name,
@@ -173,81 +170,96 @@ mongoc_client_command_simple_with_server
                                              uint32_t server_id,
                                              bson_t *reply,
                                              bson_error_t *error);
+
 MONGOC_EXPORT (void)
 mongoc_client_destroy (mongoc_client_t *client);
+
 MONGOC_EXPORT (mongoc_client_session_t *)
-mongoc_client_start_session (mongoc_client_t *client,
-                             const mongoc_session_opt_t *opts,
-                             bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_client_start_session (mongoc_client_t *client, const mongoc_session_opt_t *opts, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_database_t *)
 mongoc_client_get_database (mongoc_client_t *client, const char *name) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_database_t *)
 mongoc_client_get_default_database (mongoc_client_t *client) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_gridfs_t *)
 mongoc_client_get_gridfs (mongoc_client_t *client, const char *db, const char *prefix, bson_error_t *error)
    BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_collection_t *)
-mongoc_client_get_collection (mongoc_client_t *client,
-                              const char *db,
-                              const char *collection) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (char **)
-mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_client_get_database_names_with_opts);
+mongoc_client_get_collection (mongoc_client_t *client, const char *db, const char *collection)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
+BSON_DEPRECATED_FOR (mongoc_client_get_database_names_with_opts)
+MONGOC_EXPORT (char **) mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (char **)
-mongoc_client_get_database_names_with_opts (mongoc_client_t *client,
-                                            const bson_t *opts,
-                                            bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_client_find_databases (mongoc_client_t *client, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_client_find_databases_with_opts);
+mongoc_client_get_database_names_with_opts (mongoc_client_t *client, const bson_t *opts, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
+BSON_DEPRECATED_FOR (mongoc_client_find_databases_with_opts)
+MONGOC_EXPORT (mongoc_cursor_t *) mongoc_client_find_databases (mongoc_client_t *client, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_cursor_t *)
 mongoc_client_find_databases_with_opts (mongoc_client_t *client, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (bool)
-mongoc_client_get_server_status (mongoc_client_t *client,
-                                 mongoc_read_prefs_t *read_prefs,
-                                 bson_t *reply,
-                                 bson_error_t *error) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (int32_t)
-mongoc_client_get_max_message_size (mongoc_client_t *client) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (int32_t)
-mongoc_client_get_max_bson_size (mongoc_client_t *client) BSON_GNUC_DEPRECATED;
+
 MONGOC_EXPORT (const mongoc_write_concern_t *)
 mongoc_client_get_write_concern (const mongoc_client_t *client);
+
 MONGOC_EXPORT (void)
 mongoc_client_set_write_concern (mongoc_client_t *client, const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (const mongoc_read_concern_t *)
 mongoc_client_get_read_concern (const mongoc_client_t *client);
+
 MONGOC_EXPORT (void)
 mongoc_client_set_read_concern (mongoc_client_t *client, const mongoc_read_concern_t *read_concern);
+
 MONGOC_EXPORT (const mongoc_read_prefs_t *)
 mongoc_client_get_read_prefs (const mongoc_client_t *client);
+
 MONGOC_EXPORT (void)
 mongoc_client_set_read_prefs (mongoc_client_t *client, const mongoc_read_prefs_t *read_prefs);
 #ifdef MONGOC_ENABLE_SSL
+
 MONGOC_EXPORT (void)
 mongoc_client_set_ssl_opts (mongoc_client_t *client, const mongoc_ssl_opt_t *opts);
 #endif
+
 MONGOC_EXPORT (bool)
 mongoc_client_set_apm_callbacks (mongoc_client_t *client, mongoc_apm_callbacks_t *callbacks, void *context);
+
 MONGOC_EXPORT (bool)
 mongoc_client_set_structured_log_opts (mongoc_client_t *client, const mongoc_structured_log_opts_t *opts);
+
 MONGOC_EXPORT (mongoc_server_description_t *)
 mongoc_client_get_server_description (mongoc_client_t *client, uint32_t server_id) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_server_description_t **)
 mongoc_client_get_server_descriptions (const mongoc_client_t *client, size_t *n) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds, size_t n);
+
 MONGOC_EXPORT (mongoc_server_description_t *)
 mongoc_client_select_server (mongoc_client_t *client,
                              bool for_writes,
                              const mongoc_read_prefs_t *prefs,
                              bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (bool)
 mongoc_client_set_error_api (mongoc_client_t *client, int32_t version);
+
 MONGOC_EXPORT (bool)
 mongoc_client_set_appname (mongoc_client_t *client, const char *appname);
+
 MONGOC_EXPORT (mongoc_change_stream_t *)
 mongoc_client_watch (mongoc_client_t *client, const bson_t *pipeline, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_client_reset (mongoc_client_t *client);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-aws.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-aws.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-aws.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-aws.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,6 +20,7 @@
 #include <mongoc/mcd-time.h>
 #include <mongoc/mongoc-cluster-aws-private.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-rand-private.h>
 #include <mongoc/mongoc-stream-private.h>
@@ -34,10 +35,10 @@
 #undef MONGOC_LOG_DOMAIN
 #define MONGOC_LOG_DOMAIN "aws_auth"
 
-#define AUTH_ERROR_AND_FAIL(...)                                                                  \
-   do {                                                                                           \
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, __VA_ARGS__); \
-      goto fail;                                                                                  \
+#define AUTH_ERROR_AND_FAIL(...)                                                                     \
+   do {                                                                                              \
+      _mongoc_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, __VA_ARGS__); \
+      goto fail;                                                                                     \
    } while (0)
 
 
@@ -552,11 +553,11 @@ _obtain_creds_from_assumerolewithwebiden
          goto fail;
       }
       char *Error_json = bson_as_relaxed_extended_json (&Error_bson, NULL);
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                      "Response to AssumeRoleWithWebIdentity contains 'Error': %s",
-                      Error_json);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                         "Response to AssumeRoleWithWebIdentity contains 'Error': %s",
+                         Error_json);
       bson_free (Error_json);
       goto fail;
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,7 @@
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-cyrus-private.h>
 #include <mongoc/mongoc-cluster-cyrus-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-trace-private.h>
 
 bool
@@ -105,10 +105,10 @@ _mongoc_cluster_auth_node_cyrus (mongoc_
       if (!bson_iter_init_find (&iter, &reply, "payload") || !BSON_ITER_HOLDS_UTF8 (&iter)) {
          MONGOC_DEBUG ("SASL: authentication failed");
          bson_destroy (&reply);
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                         "Received invalid SASL reply from MongoDB server.");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                            "Received invalid SASL reply from MongoDB server.");
          goto failure;
       }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c	2025-06-19 15:42:22.000000000 +0000
@@ -23,7 +23,7 @@
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-stream-socket.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 
 #ifdef MONGOC_ENABLE_SASL
@@ -88,11 +88,11 @@ _mongoc_cluster_auth_node_sasl (mongoc_c
                                 bson_error_t *error)
 {
 #ifndef MONGOC_ENABLE_SASL
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                   "The GSSAPI authentication mechanism requires libmongoc "
-                   "built with ENABLE_SASL");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                      "The GSSAPI authentication mechanism requires libmongoc "
+                      "built with ENABLE_SASL");
    return false;
 #elif defined(MONGOC_ENABLE_SASL_CYRUS)
    return _mongoc_cluster_auth_node_cyrus (cluster, stream, sd, error);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,7 +22,7 @@
 #include <mongoc/mongoc-cluster-sasl-private.h>
 #include <mongoc/mongoc-sasl-private.h>
 #include <mongoc/mongoc-sspi-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 
 
@@ -140,7 +140,7 @@ _mongoc_cluster_auth_node_sspi (mongoc_c
    state = _mongoc_cluster_sspi_new (cluster->uri, stream, sd->host.host);
 
    if (!state) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Couldn't initialize SSPI service.");
       goto failure;
    }
@@ -163,7 +163,8 @@ _mongoc_cluster_auth_node_sspi (mongoc_c
       }
 
       if (res == MONGOC_SSPI_AUTH_GSS_ERROR) {
-         bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Received invalid SSPI data.");
+         _mongoc_set_error (
+            error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Received invalid SSPI data.");
 
          mongoc_cmd_parts_cleanup (&parts);
          bson_destroy (&cmd);
@@ -211,10 +212,10 @@ _mongoc_cluster_auth_node_sspi (mongoc_c
 
       if (!bson_iter_init_find (&iter, &reply, "payload") || !BSON_ITER_HOLDS_UTF8 (&iter)) {
          bson_destroy (&reply);
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                         "Received invalid SASL reply from MongoDB server.");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                            "Received invalid SASL reply from MongoDB server.");
          goto failure;
       }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cluster.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cluster.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,7 @@
  */
 
 
+#include <mlib/intencode.h>
 #include <mongoc/mongoc-config.h>
 
 #include <string.h>
@@ -25,7 +26,6 @@
 #include <mongoc/mongoc-client-side-encryption-private.h>
 #include <mongoc/mongoc-counters-private.h>
 #include <mongoc/mongoc-config.h>
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-flags-private.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-log.h>
@@ -59,7 +59,7 @@
 #include <mongoc/mongoc-structured-log-private.h>
 
 #include <common-bson-dsl-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-oid-private.h>
 
 #include <inttypes.h>
@@ -145,15 +145,6 @@ _handle_network_error (mongoc_cluster_t
    EXIT;
 }
 
-
-static int32_t
-_int32_from_le (const void *data)
-{
-   BSON_ASSERT_PARAM (data);
-   return bson_iter_int32_unsafe (&(bson_iter_t) {.raw = data});
-}
-
-
 static int32_t
 _compression_level_from_uri (int32_t compressor_id, const mongoc_uri_t *uri)
 {
@@ -173,7 +164,7 @@ _mongoc_cluster_buffer_iovec (mongoc_iov
    size_t difference = 0;
 
    for (size_t n = 0u; n < iovcnt; n++) {
-      BSON_ASSERT (mcommon_in_range_unsigned (int, iov[n].iov_len));
+      BSON_ASSERT (mlib_in_range (int, iov[n].iov_len));
       const int iov_len = (int) iov[n].iov_len;
 
       total_iov_len += iov_len;
@@ -225,10 +216,10 @@ _bson_error_message_printf (bson_error_t
                                   error->message);                                          \
    } while (0)
 
-#define RUN_CMD_ERR(_domain, _code, ...)                   \
-   do {                                                    \
-      bson_set_error (error, _domain, _code, __VA_ARGS__); \
-      RUN_CMD_ERR_DECORATE;                                \
+#define RUN_CMD_ERR(_domain, _code, ...)                      \
+   do {                                                       \
+      _mongoc_set_error (error, _domain, _code, __VA_ARGS__); \
+      RUN_CMD_ERR_DECORATE;                                   \
    } while (0)
 
 
@@ -298,7 +289,7 @@ _mongoc_cluster_run_command_opquery_send
    }
 
    if (cluster->client->in_exhaust) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_IN_EXHAUST, "a cursor derived from this client is in exhaust");
       goto done;
    }
@@ -346,7 +337,7 @@ _mongoc_cluster_run_command_opquery_recv
       goto done;
    }
 
-   const int32_t message_length = _int32_from_le (buffer.data);
+   const int32_t message_length = mlib_read_i32le (buffer.data);
 
    if (message_length < message_header_length || message_length > MONGOC_DEFAULT_MAX_MSG_SIZE) {
       RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "invalid message length");
@@ -874,6 +865,7 @@ _stream_run_hello (mongoc_cluster_t *clu
                               * treat this an authentication error." */
                              error->domain = MONGOC_ERROR_CLIENT;
                              error->code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+                             _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
                           })));
       }
    } else {
@@ -896,11 +888,11 @@ _stream_run_hello (mongoc_cluster_t *clu
       const bool update_okay = _mongoc_topology_update_from_handshake (cluster->client->topology, ret_handshake_sd);
       if (!update_okay) {
          mongoc_server_description_reset (ret_handshake_sd);
-         bson_set_error (&ret_handshake_sd->error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
-                         "\"%s\" removed from topology",
-                         address);
+         _mongoc_set_error (&ret_handshake_sd->error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
+                            "\"%s\" removed from topology",
+                            address);
       }
    }
 
@@ -1023,7 +1015,8 @@ _mongoc_cluster_auth_node_plain (mongoc_
    bson_free (str);
 
    if (buflen == -1) {
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "failed base64 encoding message");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "failed base64 encoding message");
       return false;
    }
 
@@ -1045,6 +1038,7 @@ _mongoc_cluster_auth_node_plain (mongoc_
       /* error->message is already set */
       error->domain = MONGOC_ERROR_CLIENT;
       error->code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+      _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
    }
 
    bson_destroy (&b);
@@ -1057,11 +1051,11 @@ bool
 _mongoc_cluster_get_auth_cmd_x509 (const mongoc_uri_t *uri, bson_t *cmd /* OUT */, bson_error_t *error /* OUT */)
 {
 #ifndef MONGOC_ENABLE_SSL
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                   "The MONGODB-X509 authentication mechanism requires "
-                   "libmongoc built with ENABLE_SSL");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                      "The MONGODB-X509 authentication mechanism requires "
+                      "libmongoc built with ENABLE_SSL");
    return false;
 #else
    const char *username_from_uri = NULL;
@@ -1093,11 +1087,11 @@ _mongoc_cluster_auth_node_x509 (mongoc_c
                                 bson_error_t *error)
 {
 #ifndef MONGOC_ENABLE_SSL
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                   "The MONGODB-X509 authentication mechanism requires "
-                   "libmongoc built with ENABLE_SSL");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                      "The MONGODB-X509 authentication mechanism requires "
+                      "libmongoc built with ENABLE_SSL");
    return false;
 #else
    mongoc_cmd_parts_t parts;
@@ -1126,6 +1120,7 @@ _mongoc_cluster_auth_node_x509 (mongoc_c
       /* error->message is already set */
       error->domain = MONGOC_ERROR_CLIENT;
       error->code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+      _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
    }
 
    bson_destroy (&cmd);
@@ -1260,6 +1255,7 @@ _mongoc_cluster_run_scram_command (mongo
       /* error->message is already set */
       error->domain = MONGOC_ERROR_CLIENT;
       error->code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+      _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
 
       return false;
    }
@@ -1305,6 +1301,7 @@ _mongoc_cluster_auth_scram_start (mongoc
       /* error->message is already set */
       error->domain = MONGOC_ERROR_CLIENT;
       error->code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+      _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
 
       return false;
    }
@@ -1364,7 +1361,7 @@ _mongoc_cluster_scram_handle_reply (mong
    if (is_done) {
       if (scram->step < 2) {
          /* Prior to step 2, we haven't even received server proof. */
-         bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Incorrect step for 'done'");
+         _mongoc_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Incorrect step for 'done'");
          return false;
       }
       *done = true;
@@ -1384,14 +1381,14 @@ _mongoc_cluster_scram_handle_reply (mong
          errmsg = bson_iter_utf8 (&iter, NULL);
       }
 
-      bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "%s", errmsg);
+      _mongoc_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "%s", errmsg);
       return false;
    }
 
    bson_iter_binary (&iter, &btype, buflen, (const uint8_t **) &tmpstr);
 
    if (*buflen > bufmax) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "SCRAM reply from MongoDB is too large.");
       return false;
    }
@@ -1544,11 +1541,11 @@ _mongoc_cluster_auth_node_scram_sha_1 (m
                                        bson_error_t *error)
 {
 #ifndef MONGOC_ENABLE_CRYPTO
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                   "The SCRAM_SHA_1 authentication mechanism requires "
-                   "libmongoc built with ENABLE_SSL");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                      "The SCRAM_SHA_1 authentication mechanism requires "
+                      "libmongoc built with ENABLE_SSL");
    return false;
 #else
    return _mongoc_cluster_auth_node_scram (cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_1, error);
@@ -1562,11 +1559,11 @@ _mongoc_cluster_auth_node_scram_sha_256
                                          bson_error_t *error)
 {
 #ifndef MONGOC_ENABLE_CRYPTO
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT,
-                   MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                   "The SCRAM_SHA_256 authentication mechanism requires "
-                   "libmongoc built with ENABLE_SSL");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_CLIENT,
+                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                      "The SCRAM_SHA_256 authentication mechanism requires "
+                      "libmongoc built with ENABLE_SSL");
    return false;
 #else
    return _mongoc_cluster_auth_node_scram (cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_256, error);
@@ -1633,11 +1630,11 @@ _mongoc_cluster_auth_node (mongoc_cluste
    } else if (0 == strcasecmp (mechanism, "MONGODB-AWS")) {
       ret = _mongoc_cluster_auth_node_aws (cluster, stream, sd, error);
    } else {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                      "Unknown authentication mechanism \"%s\".",
-                      mechanism);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                         "Unknown authentication mechanism \"%s\".",
+                         mechanism);
    }
 
    if (!ret) {
@@ -1915,11 +1912,11 @@ node_not_found (const mongoc_topology_de
    if (sd->error.code) {
       memcpy (error, &sd->error, sizeof *error);
    } else {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
-                      "Could not find node %s",
-                      sd->host.host_and_port);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
+                         "Could not find node %s",
+                         sd->host.host_and_port);
    }
 }
 
@@ -1938,11 +1935,11 @@ stream_not_found (const mongoc_topology_
       if (sd && sd->error.code) {
          memcpy (error, &sd->error, sizeof *error);
       } else {
-         bson_set_error (error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
-                         "Could not find stream for node %s",
-                         connection_address);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
+                            "Could not find stream for node %s",
+                            connection_address);
       }
    }
 }
@@ -2033,11 +2030,11 @@ _mongoc_cluster_stream_for_server (mongo
     * service id, disconnect and return an error. */
    if (td.ptr->type == MONGOC_TOPOLOGY_LOAD_BALANCED) {
       if (!mongoc_server_description_has_service_id (ret_server_stream->sd)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_LOAD_BALANCER,
-                         "Driver attempted to initialize in load balancing "
-                         "mode, but the server does not support this mode.");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_LOAD_BALANCER,
+                            "Driver attempted to initialize in load balancing "
+                            "mode, but the server does not support this mode.");
          mongoc_server_stream_cleanup (ret_server_stream);
          mongoc_cluster_disconnect_node (cluster, server_id);
          _mongoc_bson_init_if_set (reply);
@@ -2071,10 +2068,10 @@ mongoc_cluster_stream_for_server (mongoc
 
    if (cs && cs->server_id && cs->server_id != server_id) {
       _mongoc_bson_init_if_set (reply);
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_SERVER_SELECTION_INVALID_ID,
-                      "Requested server id does not matched pinned server id");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_SERVER_SELECTION_INVALID_ID,
+                         "Requested server id does not matched pinned server id");
       RETURN (NULL);
    }
 
@@ -2111,22 +2108,22 @@ _cluster_fetch_stream_single (mongoc_clu
    scanner_node = mongoc_topology_scanner_get_node (cluster->client->topology->scanner, server_id);
    /* This could happen if a user explicitly passes a bad server id. */
    if (!scanner_node) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Could not find server with id: %" PRIu32,
-                      server_id);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Could not find server with id: %" PRIu32,
+                         server_id);
       return NULL;
    }
 
    /* Retired scanner nodes are removed at the end of a scan. If the node was
     * retired, that would indicate a bug. */
    if (scanner_node->retired) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Unexpected, selecting server marked for removal: %s",
-                      scanner_node->host.host_and_port);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Unexpected, selecting server marked for removal: %s",
+                         scanner_node->host.host_and_port);
       return NULL;
    }
 
@@ -2825,7 +2822,7 @@ mongoc_cluster_check_interval (mongoc_cl
    if (scanner_node->last_used + (1000 * CHECK_CLOSED_DURATION_MSEC) < now) {
       if (mongoc_stream_check_closed (stream)) {
          mc_tpld_modification tdmod;
-         bson_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed");
+         _mongoc_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed");
          mongoc_cluster_disconnect_node (cluster, server_id);
          tdmod = mc_tpld_modify_begin (topology);
          /* invalidate_server() is okay if 'server_id' was already removed. */
@@ -2891,7 +2888,7 @@ mongoc_cluster_legacy_rpc_sendv_to_serve
    size_t num_iovecs = 0u;
 
    if (cluster->client->in_exhaust) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_IN_EXHAUST, "a cursor derived from this client is in exhaust");
       GOTO (done);
    }
@@ -2913,13 +2910,13 @@ mongoc_cluster_legacy_rpc_sendv_to_serve
    const int32_t message_length = mcd_rpc_header_get_message_length (rpc);
 
    if (message_length > max_msg_size) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_TOO_BIG,
-                      "attempted to send an RPC message with length %" PRId32
-                      " which exceeds the maximum allowed length %" PRId32,
-                      message_length,
-                      max_msg_size);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_TOO_BIG,
+                         "attempted to send an RPC message with length %" PRId32
+                         " which exceeds the maximum allowed length %" PRId32,
+                         message_length,
+                         max_msg_size);
       GOTO (done);
    }
 
@@ -2971,18 +2968,18 @@ mongoc_cluster_try_recv (mongoc_cluster_
       GOTO (done);
    }
 
-   const int32_t message_length = _int32_from_le (buffer->data + offset);
+   const int32_t message_length = mlib_read_i32le (buffer->data + offset);
 
    const int32_t max_msg_size = mongoc_server_stream_max_msg_size (server_stream);
 
    if (message_length < message_header_length || message_length > max_msg_size) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "message length %" PRId32 " is not within valid range of %" PRId32 "-%" PRId32 " bytes",
-                      message_header_length,
-                      message_length,
-                      server_stream->sd->max_msg_size);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "message length %" PRId32 " is not within valid range of %" PRId32 "-%" PRId32 " bytes",
+                         message_header_length,
+                         message_length,
+                         server_stream->sd->max_msg_size);
       _handle_network_error (cluster, server_stream, error);
       mongoc_counter_protocol_ingress_error_inc ();
       GOTO (done);
@@ -2998,7 +2995,7 @@ mongoc_cluster_try_recv (mongoc_cluster_
    }
 
    if (!mcd_rpc_message_from_data_in_place (rpc, buffer->data + offset, (size_t) message_length, NULL)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "failed to decode reply from server");
       _handle_network_error (cluster, server_stream, error);
       mongoc_counter_protocol_ingress_error_inc ();
@@ -3011,7 +3008,7 @@ mongoc_cluster_try_recv (mongoc_cluster_
    size_t decompressed_data_len = 0u;
 
    if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "could not decompress server reply");
       GOTO (done);
    }
@@ -3103,10 +3100,10 @@ _mongoc_cluster_run_opmsg_send (
       for (size_t i = 0; i < cmd->payloads_count; i++) {
          const mongoc_cmd_payload_t payload = cmd->payloads[i];
 
-         BSON_ASSERT (mcommon_in_range_signed (size_t, payload.size));
+         BSON_ASSERT (mlib_in_range (size_t, payload.size));
 
          const size_t section_length = sizeof (int32_t) + strlen (payload.identifier) + 1u + (size_t) payload.size;
-         BSON_ASSERT (mcommon_in_range_unsigned (int32_t, section_length));
+         BSON_ASSERT (mlib_in_range (int32_t, section_length));
 
          size_t section_idx = 1u + i;
          message_length += mcd_rpc_op_msg_section_set_kind (rpc, section_idx, 1);
@@ -3189,7 +3186,7 @@ _mongoc_cluster_run_opmsg_recv (
       goto done;
    }
 
-   const int32_t message_length = _int32_from_le (buffer.data);
+   const int32_t message_length = mlib_read_i32le (buffer.data);
 
    if (message_length < message_header_length || message_length > server_stream->sd->max_msg_size) {
       RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL,
@@ -3228,7 +3225,7 @@ _mongoc_cluster_run_opmsg_recv (
    size_t decompressed_data_len = 0u;
 
    if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "could not decompress message from server");
       _handle_network_error (cluster, server_stream, error);
       server_stream->stream = NULL;
@@ -3295,16 +3292,16 @@ mongoc_cluster_run_opmsg (mongoc_cluster
    BSON_ASSERT_PARAM (error);
 
    if (!cmd->command_name) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty command document");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty command document");
       bson_init (reply);
       return false;
    }
 
    if (!cmd->op_msg_is_exhaust && cluster->client->in_exhaust) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_IN_EXHAUST,
-                      "another cursor derived from this client is in exhaust");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_IN_EXHAUST,
+                         "another cursor derived from this client is in exhaust");
       bson_init (reply);
       return false;
    }
@@ -3365,16 +3362,16 @@ mcd_rpc_message_compress (mcd_rpc_messag
    // compressedMessage does not include msgHeader fields.
    BSON_ASSERT (original_message_length >= message_header_length);
    const size_t uncompressed_size = (size_t) (original_message_length - message_header_length);
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, uncompressed_size));
+   BSON_ASSERT (mlib_in_range (int32_t, uncompressed_size));
 
    const size_t estimated_compressed_size = mongoc_compressor_max_compressed_length (compressor_id, uncompressed_size);
 
    if (estimated_compressed_size == 0u) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Could not determine compression bounds for %s",
-                      mongoc_compressor_id_to_name (compressor_id));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Could not determine compression bounds for %s",
+                         mongoc_compressor_id_to_name (compressor_id));
       goto fail;
    }
 
@@ -3474,25 +3471,11 @@ mcd_rpc_message_decompress (mcd_rpc_mess
    const int32_t op_code = mcd_rpc_op_compressed_get_original_opcode (rpc);
 
    // Populate the msgHeader fields.
-   {
-      uint32_t storage;
-
-      memcpy (&storage, &message_length, sizeof (storage));
-      storage = BSON_UINT32_TO_LE (storage);
-      memcpy (ptr + 0, &storage, sizeof (storage));
-
-      memcpy (&storage, &request_id, sizeof (storage));
-      storage = BSON_UINT32_TO_LE (storage);
-      memcpy (ptr + 4, &storage, sizeof (storage));
-
-      memcpy (&storage, &response_to, sizeof (storage));
-      storage = BSON_UINT32_TO_LE (storage);
-      memcpy (ptr + 8, &storage, sizeof (storage));
-
-      memcpy (&storage, &op_code, sizeof (storage));
-      storage = BSON_UINT32_TO_LE (storage);
-      memcpy (ptr + 12, &storage, sizeof (storage));
-   }
+   uint8_t *out = ptr;
+   out = mlib_write_i32le (out, message_length);
+   out = mlib_write_i32le (out, request_id);
+   out = mlib_write_i32le (out, response_to);
+   mlib_write_i32le (out, op_code);
 
    // This value may be passed as an argument to an in-out parameter depending
    // on the compressor, not just an out-parameter.
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cmd.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cmd.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cmd.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cmd.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,10 +15,12 @@
  */
 
 
+#include <mlib/intencode.h>
 #include <mongoc/mongoc-cmd-private.h>
 #include <mongoc/mongoc-read-prefs-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-read-concern-private.h>
 #include <mongoc/mongoc-server-api-private.h>
 #include <mongoc/mongoc-write-concern-private.h>
@@ -138,7 +140,8 @@ mongoc_cmd_parts_append_opts (mongoc_cmd
          continue;
       } else if (BSON_ITER_IS_KEY (iter, "readConcern")) {
          if (!BSON_ITER_HOLDS_DOCUMENT (iter)) {
-            bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, "Invalid readConcern");
+            _mongoc_set_error (
+               error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, "Invalid readConcern");
             RETURN (false);
          }
 
@@ -164,11 +167,11 @@ mongoc_cmd_parts_append_opts (mongoc_cmd
 
       to_append = bson_iter_key (iter);
       if (!bson_append_iter (&parts->extra, to_append, -1, iter)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Failed to append \"%s\" to create command.",
-                         to_append);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Failed to append \"%s\" to create command.",
+                            to_append);
          RETURN (false);
       }
    }
@@ -177,10 +180,10 @@ mongoc_cmd_parts_append_opts (mongoc_cmd
 }
 
 
-#define OPTS_ERR(_code, ...)                                                           \
-   do {                                                                                \
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_##_code, __VA_ARGS__); \
-      RETURN (false);                                                                  \
+#define OPTS_ERR(_code, ...)                                                              \
+   do {                                                                                   \
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_##_code, __VA_ARGS__); \
+      RETURN (false);                                                                     \
    } while (0)
 
 
@@ -373,7 +376,10 @@ _mongoc_cmd_parts_assemble_mongos (mongo
       max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (parts->read_prefs);
 
       tags = mongoc_read_prefs_get_tags (parts->read_prefs);
+      mlib_diagnostic_push ();
+      mlib_disable_deprecation_warnings ();
       hedge = mongoc_read_prefs_get_hedge (parts->read_prefs);
+      mlib_diagnostic_pop ();
    }
 
    if (server_stream->must_use_primary) {
@@ -717,11 +723,11 @@ mongoc_cmd_parts_assemble (mongoc_cmd_pa
     * been invalidated, error. */
    if (server_type == MONGOC_SERVER_UNKNOWN) {
       if (error) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot assemble command for invalidated server: %s",
-                         server_stream->sd->error.message);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot assemble command for invalidated server: %s",
+                            server_stream->sd->error.message);
       }
       RETURN (false);
    }
@@ -738,7 +744,7 @@ mongoc_cmd_parts_assemble (mongoc_cmd_pa
    cmd_name = parts->assembled.command_name = _mongoc_get_command_name (parts->assembled.command);
 
    if (!parts->assembled.command_name) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document");
       GOTO (done);
    }
 
@@ -771,10 +777,10 @@ mongoc_cmd_parts_assemble (mongoc_cmd_pa
 
       if (cs && _mongoc_client_session_in_txn (cs)) {
          if (!IS_PREF_PRIMARY (cs->txn.opts.read_prefs) && !parts->is_write_command) {
-            bson_set_error (error,
-                            MONGOC_ERROR_TRANSACTION,
-                            MONGOC_ERROR_TRANSACTION_INVALID_STATE,
-                            "Read preference in a transaction must be primary");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_TRANSACTION,
+                               MONGOC_ERROR_TRANSACTION_INVALID_STATE,
+                               "Read preference in a transaction must be primary");
             GOTO (done);
          }
       } else if (mode != MONGOC_READ_PRIMARY && server_type != MONGOC_SERVER_STANDALONE) {
@@ -807,10 +813,10 @@ mongoc_cmd_parts_assemble (mongoc_cmd_pa
        */
       if (cs) {
          if (!parts->assembled.is_acknowledged) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "Cannot use client session with unacknowledged command");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "Cannot use client session with unacknowledged command");
             GOTO (done);
          }
 
@@ -862,10 +868,10 @@ mongoc_cmd_parts_assemble (mongoc_cmd_pa
              * than 13 before potentially appending "snapshot" read concern. */
             if (mongoc_session_opts_get_snapshot (&cs->opts) &&
                 server_stream->sd->max_wire_version < WIRE_VERSION_SNAPSHOT_READS) {
-               bson_set_error (error,
-                               MONGOC_ERROR_CLIENT,
-                               MONGOC_ERROR_CLIENT_SESSION_FAILURE,
-                               "Snapshot reads require MongoDB 5.0 or later");
+               _mongoc_set_error (error,
+                                  MONGOC_ERROR_CLIENT,
+                                  MONGOC_ERROR_CLIENT_SESSION_FAILURE,
+                                  "Snapshot reads require MongoDB 5.0 or later");
                GOTO (done);
             }
 
@@ -951,7 +957,6 @@ mongoc_cmd_is_compressible (const mongoc
 void
 _mongoc_cmd_append_payload_as_array (const mongoc_cmd_t *cmd, bson_t *out)
 {
-   int32_t doc_len;
    bson_t doc;
    const uint8_t *pos;
    const char *field_name;
@@ -970,8 +975,7 @@ _mongoc_cmd_append_payload_as_array (con
 
       pos = cmd->payloads[i].documents;
       while (pos < cmd->payloads[i].documents + cmd->payloads[i].size) {
-         memcpy (&doc_len, pos, sizeof (doc_len));
-         doc_len = BSON_UINT32_FROM_LE (doc_len);
+         const int32_t doc_len = mlib_read_i32le (pos);
          BSON_ASSERT (bson_init_static (&doc, pos, (size_t) doc_len));
          bson_array_builder_append_document (bson, &doc);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-collection.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-collection.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-collection.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-collection.c	2025-06-19 15:42:22.000000000 +0000
@@ -28,8 +28,6 @@
 #include <mongoc/mongoc-collection.h>
 #include <mongoc/mongoc-collection-private.h>
 #include <mongoc/mongoc-cursor-private.h>
-#include <mongoc/mongoc-error.h>
-#include <mongoc/mongoc-index.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-read-concern-private.h>
@@ -112,10 +110,10 @@ _mongoc_collection_write_command_execute
    }
 
    if (_mongoc_client_session_in_txn (crud->client_session) && crud->writeConcern) {
-      bson_set_error (&result->error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Cannot set write concern after starting transaction");
+      _mongoc_set_error (&result->error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Cannot set write concern after starting transaction");
       mongoc_server_stream_cleanup (server_stream);
       EXIT;
    }
@@ -297,111 +295,6 @@ mongoc_collection_aggregate (mongoc_coll
                              collection->write_concern);
 }
 
-
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_find --
- *
- *       DEPRECATED: use mongoc_collection_find_with_opts.
- *
- *       Performs a query against the configured MongoDB server. If @read_prefs
- *       is provided, it will be used to locate a MongoDB node in the cluster
- *       to deliver the query to.
- *
- *       @flags may be bitwise-or'd flags or MONGOC_QUERY_NONE.
- *
- *       @skip may contain the number of documents to skip before returning the
- *       matching document.
- *
- *       @limit may contain the maximum number of documents that may be
- *       returned.
- *
- *       This function will always return a cursor, with the exception of
- *       invalid API use.
- *
- * Parameters:
- *       @collection: A mongoc_collection_t.
- *       @flags: A bitwise or of mongoc_query_flags_t.
- *       @skip: The number of documents to skip.
- *       @limit: The maximum number of items.
- *       @batch_size: The batch size
- *       @query: The query to locate matching documents.
- *       @fields: The fields to return, or NULL for all fields.
- *       @read_prefs: Read preferences to choose cluster node.
- *
- * Returns:
- *       A newly allocated mongoc_cursor_t that should be freed with
- *       mongoc_cursor_destroy().
- *
- *       The client used by mongoc_collection_t must be valid for the
- *       lifetime of the resulting mongoc_cursor_t.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_cursor_t *
-mongoc_collection_find (mongoc_collection_t *collection,       /* IN */
-                        mongoc_query_flags_t flags,            /* IN */
-                        uint32_t skip,                         /* IN */
-                        uint32_t limit,                        /* IN */
-                        uint32_t batch_size,                   /* IN */
-                        const bson_t *query,                   /* IN */
-                        const bson_t *fields,                  /* IN */
-                        const mongoc_read_prefs_t *read_prefs) /* IN */
-{
-   bool has_unwrapped;
-   bson_t unwrapped;
-   bson_error_t error = {0};
-   bson_t opts;
-   bool secondary_ok;
-   mongoc_cursor_t *cursor;
-   BSON_ASSERT_PARAM (collection);
-   BSON_ASSERT_PARAM (query);
-
-   bson_clear (&collection->gle);
-
-   bson_init (&opts);
-   _mongoc_cursor_flags_to_opts (flags, &opts, &secondary_ok);
-   /* check if the query is wrapped in $query */
-   has_unwrapped = _mongoc_cursor_translate_dollar_query_opts (query, &opts, &unwrapped, &error);
-   if (!bson_empty0 (fields)) {
-      bson_append_document (&opts, MONGOC_CURSOR_PROJECTION, MONGOC_CURSOR_PROJECTION_LEN, fields);
-   }
-   cursor = _mongoc_cursor_find_new (collection->client,
-                                     collection->ns,
-                                     has_unwrapped ? &unwrapped : query,
-                                     &opts,
-                                     read_prefs,
-                                     collection->read_prefs,
-                                     collection->read_concern);
-   if (skip) {
-      _mongoc_cursor_set_opt_int64 (cursor, MONGOC_CURSOR_SKIP, skip);
-   }
-   if (limit) {
-      /* limit must be cast to int32_t. Although the argument is a uint32_t,
-       * callers can specify a negative limit by casting to a signed int32_t
-       * value to uint32_t. E.g. to set a limit of -4, the caller passes
-       * UINT32_MAX - 3 */
-      (void) mongoc_cursor_set_limit (cursor, (int32_t) limit);
-   }
-   if (batch_size) {
-      mongoc_cursor_set_batch_size (cursor, batch_size);
-   }
-   bson_destroy (&unwrapped);
-   bson_destroy (&opts);
-
-   if (error.domain) {
-      memcpy (&cursor->error, &error, sizeof (error));
-   }
-
-   return cursor;
-}
-
-
 /*
  *--------------------------------------------------------------------------
  *
@@ -445,83 +338,6 @@ mongoc_collection_find_with_opts (mongoc
 }
 
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_command --
- *
- *       Executes a command on a cluster node matching @read_prefs. If
- *       @read_prefs is not provided, it will be run on the primary node.
- *
- *       This function will always return a mongoc_cursor_t.
- *
- * Parameters:
- *       @collection: A mongoc_collection_t.
- *       @flags: Bitwise-or'd flags for command.
- *       @skip: Number of documents to skip, typically 0.
- *       @limit : Number of documents to return
- *       @batch_size : Batch size
- *       @query: The command to execute.
- *       @fields: The fields to return, or NULL.
- *       @read_prefs: Command read preferences or NULL.
- *
- * Returns:
- *       None.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_cursor_t *
-mongoc_collection_command (mongoc_collection_t *collection,
-                           mongoc_query_flags_t flags,
-                           uint32_t skip,
-                           uint32_t limit,
-                           uint32_t batch_size,
-                           const bson_t *query,
-                           const bson_t *fields,
-                           const mongoc_read_prefs_t *read_prefs)
-{
-   char *ns;
-   mongoc_cursor_t *cursor;
-
-   BSON_UNUSED (flags);
-   BSON_UNUSED (skip);
-   BSON_UNUSED (limit);
-   BSON_UNUSED (batch_size);
-   BSON_UNUSED (fields);
-
-   BSON_ASSERT_PARAM (collection);
-   BSON_ASSERT_PARAM (query);
-
-   if (!read_prefs) {
-      read_prefs = collection->read_prefs;
-   }
-
-   bson_clear (&collection->gle);
-
-   if (NULL == strstr (collection->collection, "$cmd")) {
-      ns = bson_strdup_printf ("%s.$cmd", collection->db);
-   } else {
-      ns = bson_strdup (collection->db);
-   }
-
-   /* Server Selection Spec: "The generic command method has a default read
-    * preference of mode 'primary'. The generic command method MUST ignore any
-    * default read preference from client, database or collection
-    * configuration. The generic command method SHOULD allow an optional read
-    * preference argument."
-    */
-
-   /* flags, skip, limit, batch_size, fields are unused */
-   cursor = _mongoc_cursor_cmd_deprecated_new (collection->client, ns, query, read_prefs);
-   bson_free (ns);
-   return cursor;
-}
-
-
 bool
 mongoc_collection_read_command_with_opts (mongoc_collection_t *collection,
                                           const bson_t *command,
@@ -657,117 +473,6 @@ mongoc_collection_command_simple (mongoc
                                             error);
 }
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_count --
- *
- *       Count the number of documents matching @query.
- *
- * Parameters:
- *       @flags: A mongoc_query_flags_t describing the query flags or 0.
- *       @query: The query to perform or NULL for {}.
- *       @skip: The $skip to perform within the query or 0.
- *       @limit: The $limit to perform within the query or 0.
- *       @read_prefs: desired read preferences or NULL.
- *       @error: A location for an error or NULL.
- *
- * Returns:
- *       -1 on failure; otherwise the number of matching documents.
- *
- * Side effects:
- *       @error is set upon failure if non-NULL.
- *
- *--------------------------------------------------------------------------
- */
-
-int64_t
-mongoc_collection_count (mongoc_collection_t *collection,       /* IN */
-                         mongoc_query_flags_t flags,            /* IN */
-                         const bson_t *query,                   /* IN */
-                         int64_t skip,                          /* IN */
-                         int64_t limit,                         /* IN */
-                         const mongoc_read_prefs_t *read_prefs, /* IN */
-                         bson_error_t *error)                   /* OUT */
-{
-   int64_t ret;
-   bson_t opts = BSON_INITIALIZER;
-
-   /* Complex types must be parts of `opts`, otherwise we can't
-    * follow various specs that require validation etc */
-   if (collection->read_concern->level != NULL) {
-      const bson_t *read_concern_bson;
-
-      read_concern_bson = _mongoc_read_concern_get_bson (collection->read_concern);
-      BSON_APPEND_DOCUMENT (&opts, "readConcern", read_concern_bson);
-   }
-
-   /* Server Selection Spec: "may-use-secondary" commands SHOULD take a read
-    * preference argument and otherwise MUST use the default read preference
-    * from client, database or collection configuration. */
-   BEGIN_IGNORE_DEPRECATIONS
-   ret = mongoc_collection_count_with_opts (collection, flags, query, skip, limit, &opts, read_prefs, error);
-   END_IGNORE_DEPRECATIONS
-
-   bson_destroy (&opts);
-   return ret;
-}
-
-
-int64_t
-mongoc_collection_count_with_opts (mongoc_collection_t *collection,       /* IN */
-                                   mongoc_query_flags_t flags,            /* IN */
-                                   const bson_t *query,                   /* IN */
-                                   int64_t skip,                          /* IN */
-                                   int64_t limit,                         /* IN */
-                                   const bson_t *opts,                    /* IN */
-                                   const mongoc_read_prefs_t *read_prefs, /* IN */
-                                   bson_error_t *error)                   /* OUT */
-{
-   bson_iter_t iter;
-   int64_t ret = -1;
-   bool success;
-   bson_t reply;
-   bson_t cmd = BSON_INITIALIZER;
-
-   ENTRY;
-
-   BSON_ASSERT_PARAM (collection);
-
-   bsonBuildAppend (cmd,
-                    kv ("count", utf8_w_len (collection->collection, collection->collectionlen)),
-                    kv ("query",
-                        if (query,                // If we have a query,
-                            then (bson (*query)), // Copy it
-                            else (doc ()))),      // Otherwise, add an empty doc
-                    if (limit, then (kv ("limit", int64 (limit)))),
-                    if (skip, then (kv ("skip", int64 (skip)))));
-
-
-   success = _mongoc_client_command_with_opts (collection->client,
-                                               collection->db,
-                                               &cmd,
-                                               MONGOC_CMD_READ,
-                                               opts,
-                                               flags,
-                                               read_prefs,
-                                               collection->read_prefs,
-                                               collection->read_concern,
-                                               collection->write_concern,
-                                               &reply,
-                                               error);
-
-   if (success) {
-      if (bson_iter_init_find (&iter, &reply, "n")) {
-         ret = bson_iter_as_int64 (&iter);
-      }
-   }
-
-   bson_destroy (&reply);
-   bson_destroy (&cmd);
-
-   RETURN (ret);
-}
 
 int64_t
 mongoc_collection_estimated_document_count (mongoc_collection_t *coll,
@@ -782,10 +487,10 @@ mongoc_collection_estimated_document_cou
 
    // No sessionId allowed
    if (opts && bson_has_field (opts, "sessionId")) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Collection count must not specify explicit session");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Collection count must not specify explicit session");
       RETURN (-1);
    }
 
@@ -1120,7 +825,7 @@ mongoc_collection_drop_with_opts (mongoc
    // to drop this collection:
    bsonBuildAppend (opts_without_encryptedFields, if (opts, then (insert (*opts, not(key ("encryptedFields"))))));
    if (bsonBuildError) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while updating drop options: %s", bsonBuildError);
       goto done;
    }
@@ -1231,25 +936,6 @@ mongoc_collection_keys_to_index_string (
 }
 
 
-bool
-mongoc_collection_create_index (mongoc_collection_t *collection,
-                                const bson_t *keys,
-                                const mongoc_index_opt_t *opt,
-                                bson_error_t *error)
-{
-   bson_t reply;
-   bool ret;
-
-   BEGIN_IGNORE_DEPRECATIONS
-
-   ret = mongoc_collection_create_index_with_opts (collection, keys, opt, NULL, &reply, error);
-
-   END_IGNORE_DEPRECATIONS
-
-   bson_destroy (&reply);
-   return ret;
-}
-
 static bool
 _mongoc_collection_index_keys_equal (const bson_t *expected, const bson_t *actual)
 {
@@ -1356,10 +1042,10 @@ _mongoc_collection_create_index_if_not_e
       char *alloc_name = mongoc_collection_keys_to_index_string (keys);
 
       if (!alloc_name) {
-         bson_set_error (error,
-                         MONGOC_ERROR_BSON,
-                         MONGOC_ERROR_BSON_INVALID,
-                         "Cannot generate index name from invalid `keys` argument");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_BSON,
+                            MONGOC_ERROR_BSON_INVALID,
+                            "Cannot generate index name from invalid `keys` argument");
          GOTO (done);
       }
 
@@ -1386,209 +1072,6 @@ done:
    return r;
 }
 
-bool
-mongoc_collection_create_index_with_opts (mongoc_collection_t *collection,
-                                          const bson_t *keys,
-                                          const mongoc_index_opt_t *opt,
-                                          const bson_t *opts,
-                                          bson_t *reply,
-                                          bson_error_t *error)
-{
-   mongoc_create_index_opts_t parsed;
-   mongoc_cmd_parts_t parts;
-   const mongoc_index_opt_t *def_opt;
-   const mongoc_index_opt_geo_t *def_geo;
-   const char *name;
-   bson_t cmd = BSON_INITIALIZER;
-   bson_array_builder_t *ar;
-   bson_t doc;
-   bson_t storage_doc;
-   bson_t wt_doc;
-   const mongoc_index_opt_geo_t *geo_opt;
-   const mongoc_index_opt_storage_t *storage_opt;
-   const mongoc_index_opt_wt_t *wt_opt;
-   char *alloc_name = NULL;
-   bool ret = false;
-   bool reply_initialized = false;
-   mongoc_server_stream_t *server_stream = NULL;
-   mongoc_cluster_t *cluster;
-
-   ENTRY;
-
-   BSON_ASSERT_PARAM (collection);
-   BSON_ASSERT_PARAM (keys);
-
-   def_opt = mongoc_index_opt_get_default ();
-   opt = opt ? opt : def_opt;
-
-   mongoc_cmd_parts_init (&parts, collection->client, collection->db, MONGOC_QUERY_NONE, &cmd);
-   parts.is_write_command = true;
-
-   if (!_mongoc_create_index_opts_parse (collection->client, opts, &parsed, error)) {
-      GOTO (done);
-   }
-
-   if (!parsed.writeConcern) {
-      parsed.writeConcern = collection->write_concern;
-      parsed.write_concern_owned = false;
-   }
-
-   /*
-    * Generate the key name if it was not provided.
-    */
-   name = (opt->name != def_opt->name) ? opt->name : NULL;
-   if (!name) {
-      alloc_name = mongoc_collection_keys_to_index_string (keys);
-      if (alloc_name) {
-         name = alloc_name;
-      } else {
-         bson_set_error (error,
-                         MONGOC_ERROR_BSON,
-                         MONGOC_ERROR_BSON_INVALID,
-                         "Cannot generate index name from invalid `keys` argument");
-         GOTO (done);
-      }
-   }
-
-   /*
-    * Build our createIndexes command to send to the server.
-    */
-   BSON_ASSERT (BSON_APPEND_UTF8 (&cmd, "createIndexes", collection->collection));
-   bson_append_array_builder_begin (&cmd, "indexes", 7, &ar);
-   bson_array_builder_append_document_begin (ar, &doc);
-   BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "key", keys));
-   BSON_ASSERT (BSON_APPEND_UTF8 (&doc, "name", name));
-   if (opt->background) {
-      BSON_ASSERT (BSON_APPEND_BOOL (&doc, "background", true));
-   }
-   if (opt->unique) {
-      BSON_ASSERT (BSON_APPEND_BOOL (&doc, "unique", true));
-   }
-   if (opt->drop_dups) {
-      BSON_ASSERT (BSON_APPEND_BOOL (&doc, "dropDups", true));
-   }
-   if (opt->sparse) {
-      BSON_ASSERT (BSON_APPEND_BOOL (&doc, "sparse", true));
-   }
-   if (opt->expire_after_seconds != def_opt->expire_after_seconds) {
-      BSON_ASSERT (BSON_APPEND_INT32 (&doc, "expireAfterSeconds", opt->expire_after_seconds));
-   }
-   if (opt->v != def_opt->v) {
-      BSON_ASSERT (BSON_APPEND_INT32 (&doc, "v", opt->v));
-   }
-   if (opt->weights && (opt->weights != def_opt->weights)) {
-      BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "weights", opt->weights));
-   }
-   if (opt->default_language != def_opt->default_language) {
-      BSON_ASSERT (BSON_APPEND_UTF8 (&doc, "default_language", opt->default_language));
-   }
-   if (opt->language_override != def_opt->language_override) {
-      BSON_ASSERT (BSON_APPEND_UTF8 (&doc, "language_override", opt->language_override));
-   }
-   if (opt->partial_filter_expression) {
-      BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "partialFilterExpression", opt->partial_filter_expression));
-   }
-   if (opt->collation) {
-      BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "collation", opt->collation));
-   }
-   if (opt->geo_options) {
-      geo_opt = opt->geo_options;
-      def_geo = mongoc_index_opt_geo_get_default ();
-      if (geo_opt->twod_sphere_version != def_geo->twod_sphere_version) {
-         BSON_ASSERT (BSON_APPEND_INT32 (&doc, "2dsphereIndexVersion", geo_opt->twod_sphere_version));
-      }
-      if (geo_opt->twod_bits_precision != def_geo->twod_bits_precision) {
-         BSON_ASSERT (BSON_APPEND_INT32 (&doc, "bits", geo_opt->twod_bits_precision));
-      }
-      if (geo_opt->twod_location_min != def_geo->twod_location_min) {
-         BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "min", geo_opt->twod_location_min));
-      }
-      if (geo_opt->twod_location_max != def_geo->twod_location_max) {
-         BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "max", geo_opt->twod_location_max));
-      }
-      if (geo_opt->haystack_bucket_size != def_geo->haystack_bucket_size) {
-         BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "bucketSize", geo_opt->haystack_bucket_size));
-      }
-   }
-
-   if (opt->storage_options) {
-      storage_opt = opt->storage_options;
-      switch (storage_opt->type) {
-      case MONGOC_INDEX_STORAGE_OPT_WIREDTIGER:
-         wt_opt = (mongoc_index_opt_wt_t *) storage_opt;
-         BSON_APPEND_DOCUMENT_BEGIN (&doc, "storageEngine", &storage_doc);
-         BSON_APPEND_DOCUMENT_BEGIN (&storage_doc, "wiredTiger", &wt_doc);
-         BSON_ASSERT (BSON_APPEND_UTF8 (&wt_doc, "configString", wt_opt->config_str));
-         bson_append_document_end (&storage_doc, &wt_doc);
-         bson_append_document_end (&doc, &storage_doc);
-         break;
-      default:
-         break;
-      }
-   }
-
-   bson_array_builder_append_document_end (ar, &doc);
-   bson_append_array_builder_end (&cmd, ar);
-
-   const mongoc_ss_log_context_t ss_log_context = {.operation = "createIndexes"};
-   server_stream = mongoc_cluster_stream_for_writes (
-      &collection->client->cluster, &ss_log_context, parsed.client_session, NULL, reply, error);
-
-   if (!server_stream) {
-      reply_initialized = true;
-      GOTO (done);
-   }
-
-   if (!mongoc_cmd_parts_set_write_concern (&parts, parsed.writeConcern, error)) {
-      GOTO (done);
-   }
-
-   parts.assembled.session = parsed.client_session;
-   if (!bson_concat (&parts.extra, &parsed.extra)) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "'opts' is too large");
-      GOTO (done);
-   }
-
-   cluster = &collection->client->cluster;
-   if (mongoc_cmd_parts_assemble (&parts, server_stream, error)) {
-      ret = mongoc_cluster_run_command_monitored (cluster, &parts.assembled, reply, error);
-   } else {
-      _mongoc_bson_init_if_set (reply);
-   }
-
-   reply_initialized = true;
-
-   if (ret) {
-      if (reply) {
-         ret = !_mongoc_parse_wc_err (reply, error);
-      }
-   }
-
-done:
-   bson_destroy (&cmd);
-   bson_free (alloc_name);
-   _mongoc_create_index_opts_cleanup (&parsed);
-   mongoc_server_stream_cleanup (server_stream);
-   mongoc_cmd_parts_cleanup (&parts);
-   if (!reply_initialized && reply) {
-      bson_init (reply);
-   }
-
-   RETURN (ret);
-}
-
-
-bool
-mongoc_collection_ensure_index (mongoc_collection_t *collection,
-                                const bson_t *keys,
-                                const mongoc_index_opt_t *opt,
-                                bson_error_t *error)
-{
-   BEGIN_IGNORE_DEPRECATIONS
-   return mongoc_collection_create_index (collection, keys, opt, error);
-   END_IGNORE_DEPRECATIONS
-}
-
 
 mongoc_cursor_t *
 mongoc_collection_find_indexes (mongoc_collection_t *collection, bson_error_t *error)
@@ -1638,94 +1121,6 @@ mongoc_collection_find_indexes_with_opts
    return cursor;
 }
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_insert_bulk --
- *
- *       Bulk insert documents into a MongoDB collection.
- *
- * Parameters:
- *       @collection: A mongoc_collection_t.
- *       @flags: flags for the insert or 0.
- *       @documents: The documents to insert.
- *       @n_documents: The number of documents to insert.
- *       @write_concern: A write concern or NULL.
- *       @error: a location for an error or NULL.
- *
- * Returns:
- *       true if successful; otherwise false and @error is set.
- *
- *       If the write concern does not dictate checking the result of the
- *       insert, then true may be returned even though the document was
- *       not actually inserted on the MongoDB server or cluster.
- *
- * Side effects:
- *       @collection->gle is setup, depending on write_concern->w value.
- *       @error may be set upon failure if non-NULL.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_collection_insert_bulk (mongoc_collection_t *collection,
-                               mongoc_insert_flags_t flags,
-                               const bson_t **documents,
-                               uint32_t n_documents,
-                               const mongoc_write_concern_t *write_concern,
-                               bson_error_t *error)
-{
-   mongoc_write_command_t command;
-   mongoc_write_result_t result;
-   mongoc_bulk_write_flags_t write_flags = MONGOC_BULK_WRITE_FLAGS_INIT;
-   uint32_t i;
-   bool ret;
-
-   BSON_ASSERT_PARAM (collection);
-   BSON_ASSERT_PARAM (documents);
-
-   if (!write_concern) {
-      write_concern = collection->write_concern;
-   }
-
-   if (!(flags & MONGOC_INSERT_NO_VALIDATE)) {
-      for (i = 0; i < n_documents; i++) {
-         if (!_mongoc_validate_new_document (documents[i], _mongoc_default_insert_vflags, error)) {
-            RETURN (false);
-         }
-      }
-   }
-
-   bson_clear (&collection->gle);
-
-   _mongoc_write_result_init (&result);
-
-   write_flags.ordered = !(flags & MONGOC_INSERT_CONTINUE_ON_ERROR);
-
-   _mongoc_write_command_init_insert (&command, NULL, NULL, write_flags, ++collection->client->cluster.operation_id);
-
-   for (i = 0; i < n_documents; i++) {
-      _mongoc_write_command_insert_append (&command, documents[i]);
-   }
-
-   _mongoc_collection_write_command_execute (&command, collection, write_concern, NULL, &result);
-
-   collection->gle = bson_new ();
-   ret = MONGOC_WRITE_RESULT_COMPLETE (&result,
-                                       collection->client->error_api_version,
-                                       write_concern,
-                                       /* no error domain override */
-                                       (mongoc_error_domain_t) 0,
-                                       collection->gle,
-                                       error);
-
-   _mongoc_write_result_destroy (&result);
-   _mongoc_write_command_destroy (&command);
-
-   return ret;
-}
-
-
 bool
 mongoc_collection_insert (mongoc_collection_t *collection,
                           mongoc_insert_flags_t flags,
@@ -1853,8 +1248,7 @@ done:
  *
  * mongoc_collection_insert_many --
  *
- *       Insert documents into a MongoDB collection. Replaces
- *       mongoc_collection_insert_bulk.
+ *       Insert documents into a MongoDB collection.
  *
  * Parameters:
  *       @collection: A mongoc_collection_t.
@@ -2103,19 +1497,19 @@ _mongoc_collection_update_or_replace (mo
 
    if (!bson_empty0 (array_filters)) {
       if (!mongoc_write_concern_is_acknowledged (update_opts->crud.writeConcern)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "Cannot use array filters with unacknowledged writes");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "Cannot use array filters with unacknowledged writes");
          GOTO (done);
       }
    }
 
    if (_mongoc_client_session_in_txn (update_opts->crud.client_session) && update_opts->crud.writeConcern) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Cannot set write concern after starting transaction");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Cannot set write concern after starting transaction");
       GOTO (done);
    }
 
@@ -2298,66 +1692,6 @@ mongoc_collection_replace_one (mongoc_co
 }
 
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_save --
- *
- *       Save @document to @collection.
- *
- *       If the document has an _id field, it will be updated. Otherwise,
- *       the document will be inserted into the collection.
- *
- * Returns:
- *       true if successful; otherwise false and @error is set.
- *
- * Side effects:
- *       @error is set upon failure if non-NULL.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_collection_save (mongoc_collection_t *collection,
-                        const bson_t *document,
-                        const mongoc_write_concern_t *write_concern,
-                        bson_error_t *error)
-{
-   bson_iter_t iter;
-   bool ret;
-   bson_t selector;
-
-   BSON_ASSERT_PARAM (collection);
-   BSON_ASSERT_PARAM (document);
-
-   BEGIN_IGNORE_DEPRECATIONS
-   if (!bson_iter_init_find (&iter, document, "_id")) {
-      return mongoc_collection_insert (collection, MONGOC_INSERT_NONE, document, write_concern, error);
-   }
-
-   bson_init (&selector);
-   if (!bson_append_iter (&selector, NULL, 0, &iter)) {
-      bson_set_error (
-         error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Failed to append bson to create update.");
-      bson_destroy (&selector);
-      return false;
-   }
-
-   /* this document will be inserted, validate same as for inserts */
-   if (!_mongoc_validate_new_document (document, _mongoc_default_insert_vflags, error)) {
-      return false;
-   }
-
-   ret = mongoc_collection_update (
-      collection, MONGOC_UPDATE_UPSERT | MONGOC_UPDATE_NO_VALIDATE, &selector, document, write_concern, error);
-   END_IGNORE_DEPRECATIONS
-
-   bson_destroy (&selector);
-
-   return ret;
-}
-
-
 bool
 mongoc_collection_remove (mongoc_collection_t *collection,
                           mongoc_remove_flags_t flags,
@@ -2409,17 +1743,6 @@ mongoc_collection_remove (mongoc_collect
 }
 
 
-bool
-mongoc_collection_delete (mongoc_collection_t *collection,
-                          mongoc_delete_flags_t flags,
-                          const bson_t *selector,
-                          const mongoc_write_concern_t *write_concern,
-                          bson_error_t *error)
-{
-   return mongoc_collection_remove (collection, (mongoc_remove_flags_t) flags, selector, write_concern, error);
-}
-
-
 static bool
 _mongoc_delete_one_or_many (mongoc_collection_t *collection,
                             bool multi,
@@ -2751,100 +2074,6 @@ mongoc_collection_get_name (mongoc_colle
 /*
  *--------------------------------------------------------------------------
  *
- * mongoc_collection_get_last_error --
- *
- *       Returns a bulk result.
- *
- * Returns:
- *       NULL or a bson_t that should not be modified or freed. This value
- *       is not guaranteed to be persistent between calls into the
- *       mongoc_collection_t instance, and therefore must be copied if
- *       you would like to keep it around.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-const bson_t *
-mongoc_collection_get_last_error (const mongoc_collection_t *collection) /* IN */
-{
-   BSON_ASSERT_PARAM (collection);
-
-   return collection->gle;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_validate --
- *
- *       Helper to call the validate command on the MongoDB server to
- *       validate the collection.
- *
- *       Options may be additional options, or NULL.
- *       Currently supported options are:
- *
- *          "full": Boolean
- *
- *       If full is true, then perform a more resource intensive
- *       validation.
- *
- *       The result is stored in reply.
- *
- * Returns:
- *       true if successful; otherwise false and @error is set.
- *
- * Side effects:
- *       @reply is set if successful.
- *       @error may be set.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_collection_validate (mongoc_collection_t *collection, /* IN */
-                            const bson_t *options,           /* IN */
-                            bson_t *reply,                   /* OUT */
-                            bson_error_t *error)             /* IN */
-{
-   bson_iter_t iter;
-   bson_t cmd = BSON_INITIALIZER;
-   bool ret = false;
-   bool reply_initialized = false;
-
-   BSON_ASSERT_PARAM (collection);
-
-   if (options && bson_iter_init_find (&iter, options, "full") && !BSON_ITER_HOLDS_BOOL (&iter)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "'full' must be a boolean value.");
-      goto cleanup;
-   }
-
-   bson_append_utf8 (&cmd, "validate", 8, collection->collection, collection->collectionlen);
-
-   if (options) {
-      bson_concat (&cmd, options);
-   }
-
-   ret = mongoc_collection_command_simple (collection, &cmd, NULL, reply, error);
-   reply_initialized = true;
-
-cleanup:
-   bson_destroy (&cmd);
-
-   if (reply && !reply_initialized) {
-      bson_init (reply);
-   }
-
-   return ret;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
  * mongoc_collection_rename --
  *
  *       Rename the collection to @new_name.
@@ -2891,11 +2120,11 @@ mongoc_collection_rename_with_opts (mong
    BSON_ASSERT_PARAM (new_name);
 
    if (strchr (new_name, '$')) {
-      bson_set_error (error,
-                      MONGOC_ERROR_NAMESPACE,
-                      MONGOC_ERROR_NAMESPACE_INVALID,
-                      "\"%s\" is an invalid collection name.",
-                      new_name);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_NAMESPACE,
+                         MONGOC_ERROR_NAMESPACE_INVALID,
+                         "\"%s\" is an invalid collection name.",
+                         new_name);
       return false;
    }
 
@@ -2943,86 +2172,6 @@ mongoc_collection_rename_with_opts (mong
 }
 
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_collection_stats --
- *
- *       Fetches statistics about the collection.
- *
- *       The result is stored in @stats, which should NOT be an initialized
- *       bson_t or a leak will occur.
- *
- *       @stats, @options, and @error are optional.
- *
- * Returns:
- *       true on success and @stats is set.
- *       false on failure and @error is set.
- *
- * Side effects:
- *       @stats and @error.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_collection_stats (mongoc_collection_t *collection, const bson_t *options, bson_t *stats, bson_error_t *error)
-{
-   bson_iter_t iter;
-   bson_t cmd = BSON_INITIALIZER;
-   bool ret;
-
-   BSON_ASSERT_PARAM (collection);
-
-   if (options && bson_iter_init_find (&iter, options, "scale") && !BSON_ITER_HOLDS_INT32 (&iter)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "'scale' must be an int32 value.");
-      return false;
-   }
-
-   BSON_APPEND_UTF8 (&cmd, "collStats", collection->collection);
-
-   if (options) {
-      bson_concat (&cmd, options);
-   }
-
-   /* Server Selection Spec: "may-use-secondary" commands SHOULD take a read
-    * preference argument and otherwise MUST use the default read preference
-    * from client, database or collection configuration. */
-   ret = mongoc_collection_command_simple (collection, &cmd, collection->read_prefs, stats, error);
-
-   bson_destroy (&cmd);
-
-   return ret;
-}
-
-
-mongoc_bulk_operation_t *
-mongoc_collection_create_bulk_operation (mongoc_collection_t *collection,
-                                         bool ordered,
-                                         const mongoc_write_concern_t *write_concern)
-{
-   bson_t opts = BSON_INITIALIZER;
-   mongoc_bulk_operation_t *bulk;
-   bool wc_ok = true;
-
-   bson_append_bool (&opts, "ordered", 7, ordered);
-   if (write_concern) {
-      wc_ok = mongoc_write_concern_append ((mongoc_write_concern_t *) write_concern, &opts);
-   }
-
-   bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts);
-
-   bson_destroy (&opts);
-
-   if (!wc_ok) {
-      bson_set_error (
-         &bulk->result.error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid writeConcern");
-   }
-
-   return bulk;
-}
-
-
 mongoc_bulk_operation_t *
 mongoc_collection_create_bulk_operation_with_opts (mongoc_collection_t *collection, const bson_t *opts)
 {
@@ -3055,10 +2204,10 @@ mongoc_collection_create_bulk_operation_
       memcpy (&bulk->result.error, &err, sizeof (bson_error_t));
    } else if (_mongoc_client_session_in_txn (bulk_opts.client_session) &&
               !mongoc_write_concern_is_default (bulk_opts.writeConcern)) {
-      bson_set_error (&bulk->result.error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Cannot set write concern after starting transaction");
+      _mongoc_set_error (&bulk->result.error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Cannot set write concern after starting transaction");
    }
 
    _mongoc_bulk_opts_cleanup (&bulk_opts);
@@ -3189,10 +2338,10 @@ mongoc_collection_find_and_modify_with_o
 
    if (appended_opts.writeConcern) {
       if (_mongoc_client_session_in_txn (parts.assembled.session)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot set write concern after starting transaction");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot set write concern after starting transaction");
          GOTO (done);
       }
 
@@ -3201,7 +2350,7 @@ mongoc_collection_find_and_modify_with_o
    /* inherit write concern from collection if not in transaction */
    else if (!_mongoc_client_session_in_txn (parts.assembled.session)) {
       if (!mongoc_write_concern_is_valid (collection->write_concern)) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The write concern is invalid.");
          GOTO (done);
       }
@@ -3215,10 +2364,10 @@ mongoc_collection_find_and_modify_with_o
                                 : WIRE_VERSION_FIND_AND_MODIFY_HINT;
 
       if (server_stream->sd->max_wire_version < max_wire_version) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "The selected server does not support hint for findAndModify");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "The selected server does not support hint for findAndModify");
          GOTO (done);
       }
 
@@ -3258,7 +2407,7 @@ mongoc_collection_find_and_modify_with_o
 
    if (bson_iter_init_find (&iter, reply, "writeConcernError") && BSON_ITER_HOLDS_DOCUMENT (&iter)) {
       const char *errmsg = NULL;
-      int32_t code = 0;
+      uint32_t code = 0;
 
       BSON_ASSERT (bson_iter_recurse (&iter, &inner));
       while (bson_iter_next (&inner)) {
@@ -3268,7 +2417,8 @@ mongoc_collection_find_and_modify_with_o
             errmsg = bson_iter_utf8 (&inner, NULL);
          }
       }
-      bson_set_error (error, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg);
+      _mongoc_set_error_with_category (
+         error, MONGOC_ERROR_CATEGORY_SERVER, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg);
       ret = false;
    }
 
@@ -3437,10 +2587,10 @@ mongoc_collection_create_indexes_with_op
          // Raise an error required by the specification:
          // "Drivers MUST manually raise an error if this option is specified
          // when creating an index on a pre 4.4 server."
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "The selected server does not support the commitQuorum option");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "The selected server does not support the commitQuorum option");
          GOTO (fail);
       }
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-collection.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-collection.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-collection.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-collection.h	2025-06-19 15:42:22.000000000 +0000
@@ -26,7 +26,6 @@
 #include <mongoc/mongoc-bulk-operation.h>
 #include <mongoc/mongoc-flags.h>
 #include <mongoc/mongoc-cursor.h>
-#include <mongoc/mongoc-index.h>
 #include <mongoc/mongoc-read-prefs.h>
 #include <mongoc/mongoc-read-concern.h>
 #include <mongoc/mongoc-write-concern.h>
@@ -37,26 +36,20 @@ BSON_BEGIN_DECLS
 
 typedef struct _mongoc_collection_t mongoc_collection_t;
 
+
 MONGOC_EXPORT (mongoc_cursor_t *)
 mongoc_collection_aggregate (mongoc_collection_t *collection,
                              mongoc_query_flags_t flags,
                              const bson_t *pipeline,
                              const bson_t *opts,
                              const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_collection_destroy (mongoc_collection_t *collection);
+
 MONGOC_EXPORT (mongoc_collection_t *)
 mongoc_collection_copy (mongoc_collection_t *collection) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_collection_command (mongoc_collection_t *collection,
-                           mongoc_query_flags_t flags,
-                           uint32_t skip,
-                           uint32_t limit,
-                           uint32_t batch_size,
-                           const bson_t *command,
-                           const bson_t *fields,
-                           const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_command_simple);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_read_command_with_opts (mongoc_collection_t *collection,
                                           const bson_t *command,
@@ -64,9 +57,11 @@ mongoc_collection_read_command_with_opts
                                           const bson_t *opts,
                                           bson_t *reply,
                                           bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_write_command_with_opts (
    mongoc_collection_t *collection, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_read_write_command_with_opts (mongoc_collection_t *collection,
                                                 const bson_t *command,
@@ -74,6 +69,7 @@ mongoc_collection_read_write_command_wit
                                                 const bson_t *opts,
                                                 bson_t *reply,
                                                 bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_command_with_opts (mongoc_collection_t *collection,
                                      const bson_t *command,
@@ -81,65 +77,32 @@ mongoc_collection_command_with_opts (mon
                                      const bson_t *opts,
                                      bson_t *reply,
                                      bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_command_simple (mongoc_collection_t *collection,
                                   const bson_t *command,
                                   const mongoc_read_prefs_t *read_prefs,
                                   bson_t *reply,
                                   bson_error_t *error);
-MONGOC_EXPORT (int64_t)
-mongoc_collection_count (mongoc_collection_t *collection,
-                         mongoc_query_flags_t flags,
-                         const bson_t *query,
-                         int64_t skip,
-                         int64_t limit,
-                         const mongoc_read_prefs_t *read_prefs,
-                         bson_error_t *error)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or mongoc_collection_estimated_document_count);
-MONGOC_EXPORT (int64_t)
-mongoc_collection_count_with_opts (mongoc_collection_t *collection,
-                                   mongoc_query_flags_t flags,
-                                   const bson_t *query,
-                                   int64_t skip,
-                                   int64_t limit,
-                                   const bson_t *opts,
-                                   const mongoc_read_prefs_t *read_prefs,
-                                   bson_error_t *error)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or mongoc_collection_estimated_document_count);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_drop (mongoc_collection_t *collection, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_drop_with_opts (mongoc_collection_t *collection, const bson_t *opts, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_drop_index (mongoc_collection_t *collection, const char *index_name, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_drop_index_with_opts (mongoc_collection_t *collection,
                                         const char *index_name,
                                         const bson_t *opts,
                                         bson_error_t *error);
-MONGOC_EXPORT (bool)
-mongoc_collection_create_index (mongoc_collection_t *collection,
-                                const bson_t *keys,
-                                const mongoc_index_opt_t *opt,
-                                bson_error_t *error) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (bool)
-mongoc_collection_create_index_with_opts (mongoc_collection_t *collection,
-                                          const bson_t *keys,
-                                          const mongoc_index_opt_t *opt,
-                                          const bson_t *opts,
-                                          bson_t *reply,
-                                          bson_error_t *error) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (bool)
-mongoc_collection_ensure_index (mongoc_collection_t *collection,
-                                const bson_t *keys,
-                                const mongoc_index_opt_t *opt,
-                                bson_error_t *error) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_collection_find_indexes (mongoc_collection_t *collection, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_find_indexes_with_opts);
+
 MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection,
-                                          const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
 
 typedef struct _mongoc_index_model_t mongoc_index_model_t;
 
@@ -156,31 +119,23 @@ mongoc_collection_create_indexes_with_op
                                             bson_t *reply,
                                             bson_error_t *error);
 
-
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_collection_find (mongoc_collection_t *collection,
-                        mongoc_query_flags_t flags,
-                        uint32_t skip,
-                        uint32_t limit,
-                        uint32_t batch_size,
-                        const bson_t *query,
-                        const bson_t *fields,
-                        const mongoc_read_prefs_t *read_prefs)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_find_with_opts) BSON_GNUC_WARN_UNUSED_RESULT;
 MONGOC_EXPORT (mongoc_cursor_t *)
 mongoc_collection_find_with_opts (mongoc_collection_t *collection,
                                   const bson_t *filter,
                                   const bson_t *opts,
                                   const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (bool)
 mongoc_collection_insert (mongoc_collection_t *collection,
                           mongoc_insert_flags_t flags,
                           const bson_t *document,
                           const mongoc_write_concern_t *write_concern,
                           bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_insert_one (
    mongoc_collection_t *collection, const bson_t *document, const bson_t *opts, bson_t *reply, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_insert_many (mongoc_collection_t *collection,
                                const bson_t **documents,
@@ -188,13 +143,7 @@ mongoc_collection_insert_many (mongoc_co
                                const bson_t *opts,
                                bson_t *reply,
                                bson_error_t *error);
-MONGOC_EXPORT (bool)
-mongoc_collection_insert_bulk (mongoc_collection_t *collection,
-                               mongoc_insert_flags_t flags,
-                               const bson_t **documents,
-                               uint32_t n_documents,
-                               const mongoc_write_concern_t *write_concern,
-                               bson_error_t *error) BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_many);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_update (mongoc_collection_t *collection,
                           mongoc_update_flags_t flags,
@@ -202,6 +151,7 @@ mongoc_collection_update (mongoc_collect
                           const bson_t *update,
                           const mongoc_write_concern_t *write_concern,
                           bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_update_one (mongoc_collection_t *collection,
                               const bson_t *selector,
@@ -209,6 +159,7 @@ mongoc_collection_update_one (mongoc_col
                               const bson_t *opts,
                               bson_t *reply,
                               bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_update_many (mongoc_collection_t *collection,
                                const bson_t *selector,
@@ -216,6 +167,7 @@ mongoc_collection_update_many (mongoc_co
                                const bson_t *opts,
                                bson_t *reply,
                                bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_replace_one (mongoc_collection_t *collection,
                                const bson_t *selector,
@@ -223,37 +175,29 @@ mongoc_collection_replace_one (mongoc_co
                                const bson_t *opts,
                                bson_t *reply,
                                bson_error_t *error);
-MONGOC_EXPORT (bool)
-mongoc_collection_delete (mongoc_collection_t *collection,
-                          mongoc_delete_flags_t flags,
-                          const bson_t *selector,
-                          const mongoc_write_concern_t *write_concern,
-                          bson_error_t *error)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_delete_one or mongoc_collection_delete_many);
-MONGOC_EXPORT (bool)
-mongoc_collection_save (mongoc_collection_t *collection,
-                        const bson_t *document,
-                        const mongoc_write_concern_t *write_concern,
-                        bson_error_t *error)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_one or mongoc_collection_replace_one);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_remove (mongoc_collection_t *collection,
                           mongoc_remove_flags_t flags,
                           const bson_t *selector,
                           const mongoc_write_concern_t *write_concern,
                           bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_delete_one (
    mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_delete_many (
    mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_rename (mongoc_collection_t *collection,
                           const char *new_db,
                           const char *new_name,
                           bool drop_target_before_rename,
                           bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_rename_with_opts (mongoc_collection_t *collection,
                                     const char *new_db,
@@ -261,12 +205,14 @@ mongoc_collection_rename_with_opts (mong
                                     bool drop_target_before_rename,
                                     const bson_t *opts,
                                     bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_find_and_modify_with_opts (mongoc_collection_t *collection,
                                              const bson_t *query,
                                              const mongoc_find_and_modify_opts_t *opts,
                                              bson_t *reply,
                                              bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_collection_find_and_modify (mongoc_collection_t *collection,
                                    const bson_t *query,
@@ -278,42 +224,39 @@ mongoc_collection_find_and_modify (mongo
                                    bool _new,
                                    bson_t *reply,
                                    bson_error_t *error);
-MONGOC_EXPORT (bool)
-mongoc_collection_stats (mongoc_collection_t *collection, const bson_t *options, bson_t *reply, bson_error_t *error)
-   BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (mongoc_bulk_operation_t *)
-mongoc_collection_create_bulk_operation (mongoc_collection_t *collection,
-                                         bool ordered,
-                                         const mongoc_write_concern_t *write_concern) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_collection_create_bulk_operation_with_opts);
+
 MONGOC_EXPORT (mongoc_bulk_operation_t *)
-mongoc_collection_create_bulk_operation_with_opts (mongoc_collection_t *collection,
-                                                   const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_collection_create_bulk_operation_with_opts (mongoc_collection_t *collection, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (const mongoc_read_prefs_t *)
 mongoc_collection_get_read_prefs (const mongoc_collection_t *collection);
+
 MONGOC_EXPORT (void)
 mongoc_collection_set_read_prefs (mongoc_collection_t *collection, const mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (const mongoc_read_concern_t *)
 mongoc_collection_get_read_concern (const mongoc_collection_t *collection);
+
 MONGOC_EXPORT (void)
 mongoc_collection_set_read_concern (mongoc_collection_t *collection, const mongoc_read_concern_t *read_concern);
+
 MONGOC_EXPORT (const mongoc_write_concern_t *)
 mongoc_collection_get_write_concern (const mongoc_collection_t *collection);
+
 MONGOC_EXPORT (void)
 mongoc_collection_set_write_concern (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (const char *)
 mongoc_collection_get_name (mongoc_collection_t *collection);
-MONGOC_EXPORT (const bson_t *)
-mongoc_collection_get_last_error (const mongoc_collection_t *collection) BSON_GNUC_DEPRECATED;
+
 MONGOC_EXPORT (char *)
 mongoc_collection_keys_to_index_string (const bson_t *keys) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (bool)
-mongoc_collection_validate (mongoc_collection_t *collection, const bson_t *options, bson_t *reply, bson_error_t *error)
-   BSON_GNUC_DEPRECATED;
+
 MONGOC_EXPORT (mongoc_change_stream_t *)
-mongoc_collection_watch (const mongoc_collection_t *coll,
-                         const bson_t *pipeline,
-                         const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_collection_watch (const mongoc_collection_t *coll, const bson_t *pipeline, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (int64_t)
 mongoc_collection_count_documents (mongoc_collection_t *coll,
                                    const bson_t *filter,
@@ -321,6 +264,7 @@ mongoc_collection_count_documents (mongo
                                    const mongoc_read_prefs_t *read_prefs,
                                    bson_t *reply,
                                    bson_error_t *error);
+
 MONGOC_EXPORT (int64_t)
 mongoc_collection_estimated_document_count (mongoc_collection_t *coll,
                                             const bson_t *opts,
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-compression.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-compression.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-compression.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-compression.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,7 @@
 #include <mongoc/mongoc-compression-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-util-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #ifdef MONGOC_ENABLE_COMPRESSION
 #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB
@@ -46,7 +46,7 @@ mongoc_compressor_max_compressed_length
 
 #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB
    case MONGOC_COMPRESSOR_ZLIB_ID:
-      BSON_ASSERT (mcommon_in_range_unsigned (unsigned_long, len));
+      BSON_ASSERT (mlib_in_range (unsigned long, len));
       return compressBound ((unsigned long) len);
 #endif
 
@@ -171,12 +171,12 @@ mongoc_uncompress (int32_t compressor_id
    case MONGOC_COMPRESSOR_ZLIB_ID: {
 #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB
       // Malformed message: unrepresentable.
-      if (BSON_UNLIKELY (!mcommon_in_range_unsigned (unsigned_long, compressed_len))) {
+      if (BSON_UNLIKELY (!mlib_in_range (unsigned long, compressed_len))) {
          return false;
       }
 
       // Malformed message: unrepresentable.
-      if (BSON_UNLIKELY (!mcommon_in_range_unsigned (unsigned_long, *uncompressed_len))) {
+      if (BSON_UNLIKELY (!mlib_in_range (unsigned long, *uncompressed_len))) {
          return false;
       }
 
@@ -254,7 +254,7 @@ mongoc_compress (int32_t compressor_id,
 
    case MONGOC_COMPRESSOR_ZLIB_ID:
 #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB
-      BSON_ASSERT (mcommon_in_range_unsigned (unsigned_long, uncompressed_len));
+      BSON_ASSERT (mlib_in_range (unsigned long, uncompressed_len));
       return compress2 ((unsigned char *) compressed,
                         (unsigned long *) compressed_len,
                         (unsigned char *) uncompressed,
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-config.h.in 2.0.2-1/src/libmongoc/src/mongoc/mongoc-config.h.in
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-config.h.in	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-config.h.in	2025-06-19 15:42:22.000000000 +0000
@@ -97,17 +97,6 @@
 
 
 /*
- * MONGOC_ENABLE_SSL_LIBRESSL is set from configure to determine if we are
- * compiled with LibreSSL support.
- */
-#define MONGOC_ENABLE_SSL_LIBRESSL @MONGOC_ENABLE_SSL_LIBRESSL@
-
-#if MONGOC_ENABLE_SSL_LIBRESSL != 1
-#  undef MONGOC_ENABLE_SSL_LIBRESSL
-#endif
-
-
-/*
  * MONGOC_ENABLE_SSL_OPENSSL is set from configure to determine if we are
  * compiled with OpenSSL support.
  */
@@ -214,17 +203,6 @@
 #  undef MONGOC_HAVE_SASL_CLIENT_DONE
 #endif
 
-
-/*
- * Disable automatic calls to mongoc_init() and mongoc_cleanup()
- * before main() is called, and after exit() (respectively).
- */
-#define MONGOC_NO_AUTOMATIC_GLOBALS @MONGOC_NO_AUTOMATIC_GLOBALS@
-
-#if MONGOC_NO_AUTOMATIC_GLOBALS != 1
-#  undef MONGOC_NO_AUTOMATIC_GLOBALS
-#endif
-
 /*
  * MONGOC_HAVE_SOCKLEN is set from configure to determine if we
  * need to emulate the type.
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-counters.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-counters.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-counters.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-counters.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,7 @@
  */
 
 
+#include <mlib/cmp.h>
 #include <bson/bson.h>
 
 #include <fcntl.h>
@@ -111,7 +112,12 @@ mongoc_counters_calc_size (void)
            (n_cpu * n_groups * sizeof (mongoc_counter_slots_t)));
 
 #ifdef BSON_OS_UNIX
-   return BSON_MAX (sysconf (_SC_PAGESIZE), size);
+   const long pg_sz = sysconf (_SC_PAGESIZE);
+   if (mlib_cmp (size, >, pg_sz)) {
+      return size;
+   } else {
+      return (size_t) pg_sz;
+   }
 #else
    return size;
 #endif
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypt.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypt.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypt.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypt.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,6 +24,7 @@
 
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-collection-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-ssl-private.h>
@@ -34,7 +35,7 @@
 #include <mongoc/mcd-time.h>
 #include <mongoc/service-gcp.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 // `mcd_mapof_kmsid_to_tlsopts` maps a KMS ID (e.g. `aws` or `aws:myname`) to a
 // `mongoc_ssl_opt_t`. The acryonym TLS is preferred over SSL for
@@ -169,7 +170,7 @@ _prefix_mongocryptd_error (bson_error_t
    char buf[sizeof (error->message)];
 
    // Truncation is OK.
-   int req = bson_snprintf (buf, sizeof (buf), "mongocryptd error: %s:", error->message);
+   int req = bson_snprintf (buf, sizeof (buf), "mongocryptd error: %s", error->message);
    BSON_ASSERT (req > 0);
    memcpy (error->message, buf, sizeof (buf));
 }
@@ -180,7 +181,7 @@ _prefix_keyvault_error (bson_error_t *er
    char buf[sizeof (error->message)];
 
    // Truncation is OK.
-   int req = bson_snprintf (buf, sizeof (buf), "key vault error: %s:", error->message);
+   int req = bson_snprintf (buf, sizeof (buf), "key vault error: %s", error->message);
    BSON_ASSERT (req > 0);
    memcpy (error->message, buf, sizeof (buf));
 }
@@ -188,11 +189,12 @@ _prefix_keyvault_error (bson_error_t *er
 static void
 _status_to_error (mongocrypt_status_t *status, bson_error_t *error)
 {
-   bson_set_error (error,
-                   MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                   mongocrypt_status_code (status),
-                   "%s",
-                   mongocrypt_status_message (status, NULL));
+   _mongoc_set_error_with_category (error,
+                                    MONGOC_ERROR_CATEGORY_CRYPT,
+                                    MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                                    mongocrypt_status_code (status),
+                                    "%s",
+                                    mongocrypt_status_message (status, NULL));
 }
 
 /* Checks for an error on mongocrypt context.
@@ -213,10 +215,10 @@ _ctx_check_error (mongocrypt_ctx_t *ctx,
       mongocrypt_status_destroy (status);
       return false;
    } else if (error_expected) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "generic error from libmongocrypt operation");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "generic error from libmongocrypt operation");
       mongocrypt_status_destroy (status);
       return false;
    }
@@ -235,10 +237,10 @@ _kms_ctx_check_error (mongocrypt_kms_ctx
       mongocrypt_status_destroy (status);
       return false;
    } else if (error_expected) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "generic error from libmongocrypt KMS operation");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "generic error from libmongocrypt KMS operation");
       mongocrypt_status_destroy (status);
       return false;
    }
@@ -257,10 +259,10 @@ _crypt_check_error (mongocrypt_t *crypt,
       mongocrypt_status_destroy (status);
       return false;
    } else if (error_expected) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "generic error from libmongocrypt handle");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "generic error from libmongocrypt handle");
       mongocrypt_status_destroy (status);
       return false;
    }
@@ -274,7 +276,7 @@ _bin_to_static_bson (mongocrypt_binary_t
 {
    /* Copy bin into bson_t result. */
    if (!bson_init_static (out, mongocrypt_binary_data (bin), mongocrypt_binary_len (bin))) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid returned bson");
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid returned bson");
       return false;
    }
    return true;
@@ -340,15 +342,18 @@ _state_need_mongo_collinfo (_state_machi
       goto fail;
    }
 
-   /* 2. Return the first result (if any) with mongocrypt_ctx_mongo_feed or
+   /* 2. Return all results (if any) with mongocrypt_ctx_mongo_feed or
     * proceed to the next step if nothing was returned. */
-   if (mongoc_cursor_next (cursor, &collinfo_bson)) {
+   while (mongoc_cursor_next (cursor, &collinfo_bson)) {
       collinfo_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (collinfo_bson), collinfo_bson->len);
       if (!mongocrypt_ctx_mongo_feed (state_machine->ctx, collinfo_bin)) {
          _ctx_check_error (state_machine->ctx, error, true);
          goto fail;
       }
-   } else if (mongoc_cursor_error (cursor, error)) {
+      mongocrypt_binary_destroy (collinfo_bin);
+      collinfo_bin = NULL;
+   }
+   if (mongoc_cursor_error (cursor, error)) {
       goto fail;
    }
 
@@ -509,7 +514,7 @@ _get_stream (const char *endpoint, int32
    tls_stream = mongoc_stream_tls_new_with_hostname (base_stream, host.host, &ssl_opt_copy, 1 /* client */);
 
    if (!tls_stream) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create TLS stream to: %s", endpoint);
       goto fail;
    }
@@ -609,12 +614,12 @@ _state_need_kms (_state_machine_t *state
          } else {
             bson_error_t kms_error;
             BSON_ASSERT (!_kms_ctx_check_error (kms_ctx, &kms_error, true));
-            bson_set_error (error,
-                            MONGOC_ERROR_STREAM,
-                            MONGOC_ERROR_STREAM_SOCKET,
-                            "%s. Failed to write to KMS stream: %s",
-                            kms_error.message,
-                            endpoint);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_STREAM,
+                               MONGOC_ERROR_STREAM_SOCKET,
+                               "%s. Failed to write to KMS stream: %s",
+                               kms_error.message,
+                               endpoint);
             goto fail;
          }
       }
@@ -638,18 +643,18 @@ _state_need_kms (_state_machine_t *state
             } else {
                bson_error_t kms_error;
                BSON_ASSERT (!_kms_ctx_check_error (kms_ctx, &kms_error, true));
-               bson_set_error (error,
-                               MONGOC_ERROR_STREAM,
-                               MONGOC_ERROR_STREAM_SOCKET,
-                               "%s. Failed to read from KMS stream to: %s",
-                               kms_error.message,
-                               endpoint);
+               _mongoc_set_error (error,
+                                  MONGOC_ERROR_STREAM,
+                                  MONGOC_ERROR_STREAM_SOCKET,
+                                  "%s. Failed to read from KMS stream to: %s",
+                                  kms_error.message,
+                                  endpoint);
                goto fail;
             }
          }
          mongocrypt_binary_destroy (http_reply);
 
-         BSON_ASSERT (mcommon_in_range_signed (uint32_t, read_ret));
+         BSON_ASSERT (mlib_in_range (uint32_t, read_ret));
          http_reply = mongocrypt_binary_new_from_data (buf, (uint32_t) read_ret);
          if (!mongocrypt_kms_ctx_feed (kms_ctx, http_reply)) {
             _kms_ctx_check_error (kms_ctx, error, true);
@@ -850,10 +855,10 @@ _try_add_azure_from_env (_mongoc_crypt_t
                      BSON_APPEND_DOCUMENT (out, "azure", &new_azure_creds);
    bson_destroy (&new_azure_creds);
    if (!okay) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Failed to build new 'azure' credentials");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Failed to build new 'azure' credentials");
    }
 
    return okay;
@@ -928,10 +933,10 @@ _try_add_gcp_from_env (bson_t *out, bson
    bson_destroy (&new_gcp_creds);
    gcp_access_token_destroy (&gcp_token);
    if (!okay) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Failed to build new 'gcp' credentials");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Failed to build new 'gcp' credentials");
    }
 
    return okay;
@@ -951,11 +956,11 @@ _state_need_kms_credentials (_state_mach
          if (!error->code) {
             // The callback did not set an error, so we'll provide a default
             // one.
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "The user-provided callback for on-demand KMS "
-                            "credentials failed.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "The user-provided callback for on-demand KMS "
+                               "credentials failed.");
          }
          goto fail;
       }
@@ -1107,11 +1112,11 @@ _state_machine_run (_state_machine_t *st
          goto success;
          break;
       case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO_WITH_DB:
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "MONGOCRYPT_CTX_NEED_MONGO_COLLINFO_WITH_DB is "
-                         "unimplemented");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "MONGOCRYPT_CTX_NEED_MONGO_COLLINFO_WITH_DB is "
+                            "unimplemented");
          goto fail;
          break;
       }
@@ -1147,22 +1152,22 @@ _parse_one_tls_opts (bson_iter_t *iter,
    memset (out_opt, 0, sizeof (mongoc_ssl_opt_t));
 
    if (!BSON_ITER_HOLDS_DOCUMENT (iter)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Expected TLS options for %s to be a document, got: %s",
-                      kms_provider,
-                      _mongoc_bson_type_to_str (bson_iter_type (iter)));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Expected TLS options for %s to be a document, got: %s",
+                         kms_provider,
+                         _mongoc_bson_type_to_str (bson_iter_type (iter)));
       goto fail;
    }
 
    bson_iter_document (iter, &len, &data);
    if (!bson_init_static (&tls_opts_doc, data, len) || !bson_iter_init (&permitted_iter, &tls_opts_doc)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Error iterating into TLS options document for %s",
-                      kms_provider);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Error iterating into TLS options document for %s",
+                         kms_provider);
       goto fail;
    }
 
@@ -1185,22 +1190,22 @@ _parse_one_tls_opts (bson_iter_t *iter,
          continue;
       }
 
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Error setting TLS option %s for %s. Insecure TLS options prohibited.",
-                      key,
-                      kms_provider);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Error setting TLS option %s for %s. Insecure TLS options prohibited.",
+                         key,
+                         kms_provider);
       goto fail;
    }
 
    if (!_mongoc_ssl_opts_from_bson (out_opt, &tls_opts_doc, &errmsg)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Error parsing TLS options for %s: %s",
-                      kms_provider,
-                      mcommon_str_from_append (&errmsg));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Error parsing TLS options for %s: %s",
+                         kms_provider,
+                         mcommon_str_from_append (&errmsg));
       goto fail;
    }
 
@@ -1231,10 +1236,10 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
    }
 
    if (!bson_iter_init (&iter, tls_opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Error starting iteration of TLS options");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Error starting iteration of TLS options");
       goto fail;
    }
 
@@ -1244,11 +1249,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
       key = bson_iter_key (&iter);
       if (0 == strcmp (key, "aws")) {
          if (has_aws) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Error parsing duplicate TLS options for %s",
-                            key);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Error parsing duplicate TLS options for %s",
+                               key);
             goto fail;
          }
 
@@ -1261,11 +1266,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
 
       if (0 == strcmp (key, "azure")) {
          if (has_azure) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Error parsing duplicate TLS options for %s",
-                            key);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Error parsing duplicate TLS options for %s",
+                               key);
             goto fail;
          }
 
@@ -1278,11 +1283,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
 
       if (0 == strcmp (key, "gcp")) {
          if (has_gcp) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Error parsing duplicate TLS options for %s",
-                            key);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Error parsing duplicate TLS options for %s",
+                               key);
             goto fail;
          }
 
@@ -1295,11 +1300,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
 
       if (0 == strcmp (key, "kmip")) {
          if (has_kmip) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Error parsing duplicate TLS options for %s",
-                            key);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Error parsing duplicate TLS options for %s",
+                               key);
             goto fail;
          }
 
@@ -1314,11 +1319,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
       if (colon_pos != NULL) {
          // Parse TLS options for a named KMS provider.
          if (mcd_mapof_kmsid_to_tlsopts_has (crypt->kmsid_to_tlsopts, key)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                            "Error parsing duplicate TLS options for %s",
-                            key);
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                               MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                               "Error parsing duplicate TLS options for %s",
+                               key);
             goto fail;
          }
 
@@ -1332,11 +1337,11 @@ _parse_all_tls_opts (_mongoc_crypt_t *cr
          continue;
       }
 
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
-                      "Cannot configure TLS options for KMS provider: %s",
-                      key);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG,
+                         "Cannot configure TLS options for KMS provider: %s",
+                         key);
       goto fail;
    }
 
@@ -1395,6 +1400,10 @@ _mongoc_crypt_new (const bson_t *kms_pro
    crypt->kmsid_to_tlsopts = mcd_mapof_kmsid_to_tlsopts_new ();
    crypt->handle = mongocrypt_new ();
    mongocrypt_setopt_retry_kms (crypt->handle, true);
+   if (!mongocrypt_setopt_enable_multiple_collinfo (crypt->handle)) {
+      _crypt_check_error (crypt->handle, error, true);
+      goto fail;
+   }
 
    // Stash away a copy of the user's kmsProviders in case we need to lazily
    // load credentials.
@@ -1476,11 +1485,11 @@ _mongoc_crypt_new (const bson_t *kms_pro
       if (!s || len == 0) {
          // empty/null version string indicates that crypt_shared was not loaded
          // by libmongocrypt
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "Option 'cryptSharedLibRequired' is 'true', but failed to "
-                         "load the crypt_shared runtime library");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "Option 'cryptSharedLibRequired' is 'true', but failed to "
+                            "load the crypt_shared runtime library");
          goto fail;
       }
       mongoc_log (
@@ -1693,7 +1702,7 @@ _create_explicit_state_machine (_mongoc_
       bool keyid_ret;
 
       if (keyid->value.v_binary.subtype != BSON_SUBTYPE_UUID) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "keyid must be a UUID");
          goto fail;
       }
@@ -1770,10 +1779,10 @@ _mongoc_crypt_explicit_encrypt (_mongoc_
 
    /* extract value */
    if (!bson_iter_init_find (&iter, &result, "v")) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "encrypted result unexpected: no 'v' found");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "encrypted result unexpected: no 'v' found");
       goto fail;
    } else {
       const bson_value_t *tmp;
@@ -1845,20 +1854,20 @@ _mongoc_crypt_explicit_encrypt_expressio
 
    /* extract document */
    if (!bson_iter_init_find (&iter, &result, "v")) {
-      bson_set_error (error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                      "encrypted result unexpected: no 'v' found");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                         "encrypted result unexpected: no 'v' found");
       goto fail;
    } else {
       bson_t tmp;
 
       if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_CLIENT,
-                         MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
-                         "encrypted result unexpected: 'v' is not a document, got: %s",
-                         _mongoc_bson_type_to_str (bson_iter_type (&iter)));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_CLIENT,
+                            MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE,
+                            "encrypted result unexpected: 'v' is not a document, got: %s",
+                            _mongoc_bson_type_to_str (bson_iter_type (&iter)));
          goto fail;
       }
 
@@ -1915,7 +1924,7 @@ _mongoc_crypt_explicit_decrypt (_mongoc_
 
    /* extract value */
    if (!bson_iter_init_find (&iter, &result, "v")) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "decrypted result unexpected");
       goto fail;
    } else {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypto-cng.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypto-cng.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypto-cng.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypto-cng.c	2025-06-19 15:42:22.000000000 +0000
@@ -21,7 +21,7 @@
 #include <mongoc/mongoc-crypto-cng-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-thread-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <windows.h>
 #include <stdio.h>
@@ -159,19 +159,19 @@ _bcrypt_derive_key_pbkdf2 (BCRYPT_ALG_HA
                            size_t output_len,
                            unsigned char *output)
 {
-   if (BSON_UNLIKELY (mcommon_cmp_greater_uu (password_len, ULONG_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (password_len, >, ULONG_MAX))) {
       MONGOC_ERROR ("PBDKF2 HMAC password length exceeds ULONG_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_uu (salt_len, ULONG_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (salt_len, >, ULONG_MAX))) {
       MONGOC_ERROR ("PBDKF2 HMAC salt length exceeds ULONG_MAX");
       return false;
    }
 
    // `(ULONGLONG) iterations` is statically asserted above.
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_uu (output_len, ULONG_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (output_len, >, ULONG_MAX))) {
       MONGOC_ERROR ("PBDKF2 HMAC output length exceeds ULONG_MAX");
       return false;
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c	2025-06-19 15:42:22.000000000 +0000
@@ -21,7 +21,7 @@
 #include <mongoc/mongoc-crypto-openssl-private.h>
 #include <mongoc/mongoc-crypto-private.h>
 #include <mongoc/mongoc-log.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <openssl/sha.h>
 #include <openssl/evp.h>
@@ -39,22 +39,22 @@ mongoc_crypto_openssl_pbkdf2_hmac_sha1 (
 {
    BSON_UNUSED (crypto);
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (password_len, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (password_len, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC password length exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (salt_len, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (salt_len, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC salt length exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (iterations, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (iterations, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC iteration count exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (iterations, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (iterations, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC output buffer length exceeds INT_MAX");
       return false;
    }
@@ -137,22 +137,22 @@ mongoc_crypto_openssl_pbkdf2_hmac_sha256
 {
    BSON_UNUSED (crypto);
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (password_len, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (password_len, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC password length exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (salt_len, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (salt_len, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC salt length exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (iterations, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (iterations, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC iteration count exceeds INT_MAX");
       return false;
    }
 
-   if (BSON_UNLIKELY (mcommon_cmp_greater_us (iterations, INT_MAX))) {
+   if (BSON_UNLIKELY (mlib_cmp (iterations, >, INT_MAX))) {
       MONGOC_ERROR ("PBKDF2 HMAC output buffer length exceeds INT_MAX");
       return false;
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,6 +16,7 @@
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mongoc/mongoc-error-private.h>
 
 typedef struct _data_change_stream_t {
    mongoc_cursor_response_t response;
@@ -134,7 +135,7 @@ _mongoc_cursor_change_stream_new (mongoc
    cursor->state = IN_BATCH;
 
    if (!_mongoc_cursor_start_reading_response (cursor, &data->response)) {
-      bson_set_error (
+      _mongoc_set_error (
          &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Couldn't parse cursor document");
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,6 +16,7 @@
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mongoc/mongoc-error-private.h>
 
 typedef enum { NONE, CMD_RESPONSE, OP_GETMORE_RESPONSE } reading_from_t;
 typedef enum { UNKNOWN, GETMORE_CMD, OP_GETMORE } getmore_type_t;
@@ -202,7 +203,7 @@ _mongoc_cursor_cmd_new_from_reply (mongo
    }
 
    if (!_mongoc_cursor_start_reading_response (cursor, &data->response)) {
-      bson_set_error (
+      _mongoc_set_error (
          &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Couldn't parse cursor document");
    }
 
@@ -212,14 +213,14 @@ _mongoc_cursor_cmd_new_from_reply (mongo
       // identifies the server with the cursor.
       // The server with the cursor is required to send a "getMore" or
       // "killCursors" command.
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_CURSOR,
-                      MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                      "Expected `serverId` option to identify server with open cursor "
-                      "(cursor ID is %" PRId64 "). "
-                      "Consider using `mongoc_client_select_server` and using the "
-                      "resulting server ID to create the cursor.",
-                      cursor->cursor_id);
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_CURSOR,
+                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                         "Expected `serverId` option to identify server with open cursor "
+                         "(cursor ID is %" PRId64 "). "
+                         "Consider using `mongoc_client_select_server` and using the "
+                         "resulting server ID to create the cursor.",
+                         cursor->cursor_id);
       // Reset cursor_id to 0 to avoid an assertion error in
       // `mongoc_cursor_destroy` when attempting to send "killCursors".
       cursor->cursor_id = 0;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-counters-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-read-concern-private.h>
@@ -202,23 +202,23 @@ _mongoc_cursor_op_getmore (mongoc_cursor
 
    const int32_t op_code = mcd_rpc_header_get_op_code (response->rpc);
    if (op_code != MONGOC_OP_CODE_REPLY) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid opcode for OP_GET_MORE: expected %" PRId32 ", got %" PRId32,
-                      MONGOC_OP_CODE_REPLY,
-                      op_code);
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid opcode for OP_GET_MORE: expected %" PRId32 ", got %" PRId32,
+                         MONGOC_OP_CODE_REPLY,
+                         op_code);
       GOTO (fail);
    }
 
    const int32_t response_to = mcd_rpc_header_get_response_to (response->rpc);
    if (response_to != request_id) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid response_to for OP_GET_MORE: expected %" PRId32 ", got %" PRId32,
-                      request_id,
-                      response_to);
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid response_to for OP_GET_MORE: expected %" PRId32 ", got %" PRId32,
+                         request_id,
+                         response_to);
       GOTO (fail);
    }
 
@@ -259,44 +259,44 @@ done:
 }
 
 
-#define OPT_CHECK(_type)                                         \
-   do {                                                          \
-      if (!BSON_ITER_HOLDS_##_type (&iter)) {                    \
-         bson_set_error (&cursor->error,                         \
-                         MONGOC_ERROR_COMMAND,                   \
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,       \
-                         "invalid option %s, should be type %s", \
-                         key,                                    \
-                         #_type);                                \
-         return NULL;                                            \
-      }                                                          \
+#define OPT_CHECK(_type)                                            \
+   do {                                                             \
+      if (!BSON_ITER_HOLDS_##_type (&iter)) {                       \
+         _mongoc_set_error (&cursor->error,                         \
+                            MONGOC_ERROR_COMMAND,                   \
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,       \
+                            "invalid option %s, should be type %s", \
+                            key,                                    \
+                            #_type);                                \
+         return NULL;                                               \
+      }                                                             \
    } while (false)
 
 
-#define OPT_CHECK_INT()                                          \
-   do {                                                          \
-      if (!BSON_ITER_HOLDS_INT (&iter)) {                        \
-         bson_set_error (&cursor->error,                         \
-                         MONGOC_ERROR_COMMAND,                   \
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,       \
-                         "invalid option %s, should be integer", \
-                         key);                                   \
-         return NULL;                                            \
-      }                                                          \
+#define OPT_CHECK_INT()                                             \
+   do {                                                             \
+      if (!BSON_ITER_HOLDS_INT (&iter)) {                           \
+         _mongoc_set_error (&cursor->error,                         \
+                            MONGOC_ERROR_COMMAND,                   \
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,       \
+                            "invalid option %s, should be integer", \
+                            key);                                   \
+         return NULL;                                               \
+      }                                                             \
    } while (false)
 
 
-#define OPT_ERR(_msg)                                                                                \
-   do {                                                                                              \
-      bson_set_error (&cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, _msg); \
-      return NULL;                                                                                   \
+#define OPT_ERR(_msg)                                                                                   \
+   do {                                                                                                 \
+      _mongoc_set_error (&cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, _msg); \
+      return NULL;                                                                                      \
    } while (false)
 
 
-#define OPT_BSON_ERR(_msg)                                                                 \
-   do {                                                                                    \
-      bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, _msg); \
-      return NULL;                                                                         \
+#define OPT_BSON_ERR(_msg)                                                                    \
+   do {                                                                                       \
+      _mongoc_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, _msg); \
+      return NULL;                                                                            \
    } while (false)
 
 
@@ -426,10 +426,10 @@ _mongoc_cursor_parse_opts_for_op_query (
          PUSH_DOLLAR_QUERY ();
          BSON_APPEND_BOOL (query, "$snapshot", bson_iter_as_bool (&iter));
       } else if (!strcmp (key, MONGOC_CURSOR_COLLATION)) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "The selected server does not support collation");
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "The selected server does not support collation");
          return NULL;
       }
       /* singleBatch limit and batchSize are handled in _mongoc_n_return,
@@ -445,11 +445,11 @@ _mongoc_cursor_parse_opts_for_op_query (
          PUSH_DOLLAR_QUERY ();
          dollar_modifier = bson_strdup_printf ("$%s", key);
          if (!bson_append_iter (query, dollar_modifier, -1, &iter)) {
-            bson_set_error (&cursor->error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Error adding \"%s\" to query",
-                            dollar_modifier);
+            _mongoc_set_error (&cursor->error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Error adding \"%s\" to query",
+                               dollar_modifier);
             bson_free (dollar_modifier);
             return NULL;
          }
@@ -572,23 +572,23 @@ _mongoc_cursor_op_query_find (mongoc_cur
 
    const int32_t op_code = mcd_rpc_header_get_op_code (response->rpc);
    if (op_code != MONGOC_OP_CODE_REPLY) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid opcode for OP_QUERY: expected %" PRId32 ", got %" PRId32,
-                      MONGOC_OP_CODE_REPLY,
-                      op_code);
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid opcode for OP_QUERY: expected %" PRId32 ", got %" PRId32,
+                         MONGOC_OP_CODE_REPLY,
+                         op_code);
       GOTO (done);
    }
 
    const int32_t response_to = mcd_rpc_header_get_response_to (response->rpc);
    if (response_to != request_id) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid response_to for OP_QUERY: expected %" PRId32 ", got %" PRId32,
-                      request_id,
-                      response_to);
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid response_to for OP_QUERY: expected %" PRId32 ", got %" PRId32,
+                         request_id,
+                         response_to);
       GOTO (done);
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,7 +20,6 @@
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-client-session-private.h>
 #include <mongoc/mongoc-counters-private.h>
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-trace-private.h>
@@ -32,7 +31,7 @@
 #include <mongoc/mongoc-structured-log-private.h>
 
 #include <common-bson-dsl-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #undef MONGOC_LOG_DOMAIN
 #define MONGOC_LOG_DOMAIN "cursor"
@@ -203,12 +202,12 @@ _mongoc_cursor_check_and_copy_to (mongoc
    bson_init (dst);
    if (src) {
       if (!bson_validate_with_error (src, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Invalid %s: %s",
-                         err_prefix,
-                         validate_err.message);
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Invalid %s: %s",
+                            err_prefix,
+                            validate_err.message);
          return false;
       }
 
@@ -218,6 +217,39 @@ _mongoc_cursor_check_and_copy_to (mongoc
    return true;
 }
 
+// Get "serverId" from opts. Sets *server_id to the serverId from "opts" or 0 if absent.
+// On error, fills out *error and return false.
+static bool
+_mongoc_get_server_id_from_opts (const bson_t *opts, uint32_t *server_id, bson_error_t *error)
+{
+   bson_iter_t iter;
+
+   ENTRY;
+
+   BSON_ASSERT (server_id);
+
+   *server_id = 0;
+
+   if (!opts || !bson_iter_init_find (&iter, opts, "serverId")) {
+      RETURN (true);
+   }
+
+   if (!BSON_ITER_HOLDS_INT (&iter)) {
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "The serverId option must be an integer");
+      RETURN (false);
+   }
+
+   if (bson_iter_as_int64 (&iter) <= 0) {
+      _mongoc_set_error (
+         error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "The serverId option must be >= 1");
+      RETURN (false);
+   }
+
+   *server_id = (uint32_t) bson_iter_as_int64 (&iter);
+
+   RETURN (true);
+}
 
 mongoc_cursor_t *
 _mongoc_cursor_new_with_opts (mongoc_client_t *client,
@@ -249,21 +281,21 @@ _mongoc_cursor_new_with_opts (mongoc_cli
 
    if (opts) {
       if (!bson_validate_with_error (opts, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Invalid opts: %s",
-                         validate_err.message);
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Invalid opts: %s",
+                            validate_err.message);
          GOTO (finish);
       }
 
       dollar_field = _first_dollar_field (opts);
       if (dollar_field) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Cannot use $-modifiers in opts: \"%s\"",
-                         dollar_field);
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Cannot use $-modifiers in opts: \"%s\"",
+                            dollar_field);
          GOTO (finish);
       }
 
@@ -287,8 +319,7 @@ _mongoc_cursor_new_with_opts (mongoc_cli
       }
 
       /* true if there's a valid serverId or no serverId, false on err */
-      if (!_mongoc_get_server_id_from_opts (
-             opts, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, &server_id, &cursor->error)) {
+      if (!_mongoc_get_server_id_from_opts (opts, &server_id, &cursor->error)) {
          GOTO (finish);
       }
 
@@ -306,20 +337,20 @@ _mongoc_cursor_new_with_opts (mongoc_cli
 
    if (_mongoc_client_session_in_txn (cursor->client_session)) {
       if (!IS_PREF_PRIMARY (user_prefs)) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Read preference in a transaction must be primary");
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Read preference in a transaction must be primary");
          GOTO (finish);
       }
 
       cursor->read_prefs = mongoc_read_prefs_copy (cursor->client_session->txn.opts.read_prefs);
 
       if (bson_has_field (opts, "readConcern")) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Cannot set read concern after starting transaction");
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Cannot set read concern after starting transaction");
          GOTO (finish);
       }
    } else if (user_prefs) {
@@ -338,10 +369,10 @@ _mongoc_cursor_new_with_opts (mongoc_cli
 
    if (_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST)) {
       if (_mongoc_cursor_get_opt_int64 (cursor, MONGOC_CURSOR_LIMIT, 0)) {
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "Cannot specify both 'exhaust' and 'limit'.");
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "Cannot specify both 'exhaust' and 'limit'.");
          GOTO (finish);
       }
    }
@@ -476,24 +507,25 @@ _mongoc_cursor_translate_dollar_query_op
    if (bson_has_field (query, "$query")) {
       /* like "{$query: {a: 1}, $orderby: {b: 1}, $otherModifier: true}" */
       if (!bson_iter_init (&iter, query)) {
-         bson_set_error (&error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in query document");
+         _mongoc_set_error (
+            &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in query document");
          GOTO (done);
       }
       while (bson_iter_next (&iter)) {
          key = bson_iter_key (&iter);
          if (key[0] != '$') {
-            bson_set_error (&error_local,
-                            MONGOC_ERROR_CURSOR,
-                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                            "Cannot mix $query with non-dollar field '%s'",
-                            key);
+            _mongoc_set_error (&error_local,
+                               MONGOC_ERROR_CURSOR,
+                               MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                               "Cannot mix $query with non-dollar field '%s'",
+                               key);
             GOTO (done);
          }
          if (!strcmp (key, "$query")) {
             /* set "filter" to the incoming document's "$query" */
             bson_iter_document (&iter, &data_len, &data);
             if (!bson_init_static (unwrapped, data, (size_t) data_len)) {
-               bson_set_error (
+               _mongoc_set_error (
                   &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in $query subdocument");
                GOTO (done);
             }
@@ -501,13 +533,13 @@ _mongoc_cursor_translate_dollar_query_op
          } else if (_translate_query_opt (key, &opt_key, &len)) {
             /* "$orderby" becomes "sort", etc., "$unknown" -> "unknown" */
             if (!bson_append_iter (opts, opt_key, len, &iter)) {
-               bson_set_error (
+               _mongoc_set_error (
                   &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error adding \"%s\" to query", opt_key);
             }
          } else {
             /* strip leading "$" */
             if (!bson_append_iter (opts, key + 1, -1, &iter)) {
-               bson_set_error (
+               _mongoc_set_error (
                   &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error adding \"%s\" to query", key);
             }
          }
@@ -846,19 +878,19 @@ _mongoc_cursor_monitor_failed (mongoc_cu
 }
 
 
-#define ADD_FLAG(_flags, _value)                                   \
-   do {                                                            \
-      if (!BSON_ITER_HOLDS_BOOL (&iter)) {                         \
-         bson_set_error (&cursor->error,                           \
-                         MONGOC_ERROR_COMMAND,                     \
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,         \
-                         "invalid option %s, should be type bool", \
-                         key);                                     \
-         return false;                                             \
-      }                                                            \
-      if (bson_iter_as_bool (&iter)) {                             \
-         *_flags |= _value;                                        \
-      }                                                            \
+#define ADD_FLAG(_flags, _value)                                      \
+   do {                                                               \
+      if (!BSON_ITER_HOLDS_BOOL (&iter)) {                            \
+         _mongoc_set_error (&cursor->error,                           \
+                            MONGOC_ERROR_COMMAND,                     \
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,         \
+                            "invalid option %s, should be type bool", \
+                            key);                                     \
+         return false;                                                \
+      }                                                               \
+      if (bson_iter_as_bool (&iter)) {                                \
+         *_flags |= _value;                                           \
+      }                                                               \
    } while (false)
 
 bool
@@ -871,7 +903,7 @@ _mongoc_cursor_opts_to_flags (mongoc_cur
    *flags = MONGOC_OP_QUERY_FLAG_NONE;
 
    if (!bson_iter_init (&iter, &cursor->opts)) {
-      bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid 'opts' parameter.");
+      _mongoc_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -948,7 +980,8 @@ _mongoc_cursor_run_command (
    if (opts) {
       if (!bson_iter_init (&iter, opts)) {
          _mongoc_bson_init_if_set (reply);
-         bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in opts document");
+         _mongoc_set_error (
+            &cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in opts document");
          GOTO (done);
       }
       if (!mongoc_cmd_parts_append_opts (&parts, &iter, &cursor->error)) {
@@ -1001,13 +1034,13 @@ _mongoc_cursor_run_command (
       const int32_t wire_version = server_stream->sd->max_wire_version;
       if (sharded && wire_version < WIRE_VERSION_MONGOS_EXHAUST) {
          /* Return error since mongos < 7.2 doesn't support exhaust cursors */
-         bson_set_error (&cursor->error,
-                         MONGOC_ERROR_CURSOR,
-                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                         "exhaust cursors require mongos with wire version: "
-                         "%d, but mongos has wire version: %d.",
-                         wire_version,
-                         WIRE_VERSION_MONGOS_EXHAUST);
+         _mongoc_set_error (&cursor->error,
+                            MONGOC_ERROR_CURSOR,
+                            MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                            "exhaust cursors require mongos with wire version: "
+                            "%d, but mongos has wire version: %d.",
+                            wire_version,
+                            WIRE_VERSION_MONGOS_EXHAUST);
          _mongoc_bson_init_if_set (reply);
          GOTO (done);
       }
@@ -1161,7 +1194,9 @@ mongoc_cursor_error_document (mongoc_cur
    BSON_ASSERT (cursor);
 
    if (BSON_UNLIKELY (CURSOR_FAILED (cursor))) {
-      bson_set_error (error, cursor->error.domain, cursor->error.code, "%s", cursor->error.message);
+      if (error) {
+         *error = cursor->error;
+      }
 
       if (doc) {
          *doc = &cursor->error_doc;
@@ -1223,10 +1258,10 @@ mongoc_cursor_next (mongoc_cursor_t *cur
    TRACE ("cursor_id(%" PRId64 ")", cursor->cursor_id);
 
    if (cursor->client_generation != cursor->client->generation) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_CURSOR,
-                      MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                      "Cannot advance cursor after client reset");
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_CURSOR,
+                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                         "Cannot advance cursor after client reset");
       RETURN (false);
    }
 
@@ -1239,10 +1274,10 @@ mongoc_cursor_next (mongoc_cursor_t *cur
    }
 
    if (cursor->state == DONE) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_CURSOR,
-                      MONGOC_ERROR_CURSOR_INVALID_CURSOR,
-                      "Cannot advance a completed or failed cursor.");
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_CURSOR,
+                         MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                         "Cannot advance a completed or failed cursor.");
       RETURN (false);
    }
 
@@ -1250,10 +1285,10 @@ mongoc_cursor_next (mongoc_cursor_t *cur
     * We cannot proceed if another cursor is receiving results in exhaust mode.
     */
    if (cursor->client->in_exhaust && !cursor->in_exhaust) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_CLIENT_IN_EXHAUST,
-                      "Another cursor derived from this client is in exhaust.");
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_CLIENT_IN_EXHAUST,
+                         "Another cursor derived from this client is in exhaust.");
       RETURN (false);
    }
 
@@ -1386,23 +1421,6 @@ mongoc_cursor_clone (const mongoc_cursor
 }
 
 
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_cursor_is_alive --
- *
- *       Deprecated for mongoc_cursor_more.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_cursor_is_alive (const mongoc_cursor_t *cursor) /* IN */
-{
-   return mongoc_cursor_more ((mongoc_cursor_t *) cursor);
-}
-
-
 const bson_t *
 mongoc_cursor_current (const mongoc_cursor_t *cursor) /* IN */
 {
@@ -1422,7 +1440,7 @@ mongoc_cursor_set_batch_size (mongoc_cur
    } else if (BSON_ITER_HOLDS_INT64 (&iter)) {
       bson_iter_overwrite_int64 (&iter, (int64_t) batch_size);
    } else if (BSON_ITER_HOLDS_INT32 (&iter)) {
-      if (!mcommon_in_range_int32_t_unsigned (batch_size)) {
+      if (!mlib_in_range (int32_t, batch_size)) {
          MONGOC_WARNING ("unable to overwrite stored int32 batchSize with "
                          "out-of-range value %" PRIu32,
                          batch_size);
@@ -1489,12 +1507,6 @@ mongoc_cursor_get_limit (const mongoc_cu
 
 
 bool
-mongoc_cursor_set_hint (mongoc_cursor_t *cursor, uint32_t server_id)
-{
-   return mongoc_cursor_set_server_id (cursor, server_id);
-}
-
-bool
 mongoc_cursor_set_server_id (mongoc_cursor_t *cursor, uint32_t server_id)
 {
    BSON_ASSERT (cursor);
@@ -1516,12 +1528,6 @@ mongoc_cursor_set_server_id (mongoc_curs
 
 
 uint32_t
-mongoc_cursor_get_hint (const mongoc_cursor_t *cursor)
-{
-   return mongoc_cursor_get_server_id (cursor);
-}
-
-uint32_t
 mongoc_cursor_get_server_id (const mongoc_cursor_t *cursor)
 {
    BSON_ASSERT (cursor);
@@ -1565,31 +1571,6 @@ mongoc_cursor_get_max_await_time_ms (con
 }
 
 
-/* deprecated for mongoc_cursor_new_from_command_reply_with_opts */
-mongoc_cursor_t *
-mongoc_cursor_new_from_command_reply (mongoc_client_t *client, bson_t *reply, uint32_t server_id)
-{
-   mongoc_cursor_t *cursor;
-   bson_t cmd = BSON_INITIALIZER;
-   bson_t opts = BSON_INITIALIZER;
-
-   BSON_ASSERT_PARAM (client);
-   BSON_ASSERT (reply);
-   /* options are passed through by adding them to reply. */
-   bsonBuildAppend (*reply, insert (opts, not(key ("cursor", "ok", "operationTime", "$clusterTime", "$gleStats"))));
-
-   if (server_id) {
-      bson_append_int64 (&opts, "serverId", 8, server_id);
-   }
-
-   cursor = _mongoc_cursor_cmd_new_from_reply (client, &cmd, &opts, reply);
-   bson_destroy (&cmd);
-   bson_destroy (&opts);
-
-   return cursor;
-}
-
-
 mongoc_cursor_t *
 mongoc_cursor_new_from_command_reply_with_opts (mongoc_client_t *client, bson_t *reply, const bson_t *opts)
 {
@@ -1683,11 +1664,11 @@ _mongoc_cursor_response_refresh (mongoc_
       }
    }
    if (!cursor->error.domain) {
-      bson_set_error (&cursor->error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "Invalid reply to %s command.",
-                      _mongoc_get_command_name (command));
+      _mongoc_set_error (&cursor->error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "Invalid reply to %s command.",
+                         _mongoc_get_command_name (command));
    }
 }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cursor.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cursor.h	2025-06-19 15:42:22.000000000 +0000
@@ -33,58 +33,69 @@ typedef struct _mongoc_cursor_t mongoc_c
 /* forward decl */
 struct _mongoc_client_t;
 
+
 MONGOC_EXPORT (mongoc_cursor_t *)
 mongoc_cursor_clone (const mongoc_cursor_t *cursor) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_cursor_destroy (mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_more (mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_next (mongoc_cursor_t *cursor, const bson_t **bson);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_error (mongoc_cursor_t *cursor, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_error_document (mongoc_cursor_t *cursor, bson_error_t *error, const bson_t **doc);
+
 MONGOC_EXPORT (void)
 mongoc_cursor_get_host (mongoc_cursor_t *cursor, mongoc_host_list_t *host);
-MONGOC_EXPORT (bool)
-mongoc_cursor_is_alive (const mongoc_cursor_t *cursor) BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_more);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_cursor_current (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (void)
 mongoc_cursor_set_batch_size (mongoc_cursor_t *cursor, uint32_t batch_size);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_cursor_get_batch_size (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_set_limit (mongoc_cursor_t *cursor, int64_t limit);
+
 MONGOC_EXPORT (int64_t)
 mongoc_cursor_get_limit (const mongoc_cursor_t *cursor);
+
 // `mongoc_cursor_set_hint` is deprecated for more aptly named `mongoc_cursor_set_server_id`.
-MONGOC_EXPORT (bool)
-mongoc_cursor_set_hint (mongoc_cursor_t *cursor, uint32_t server_id)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_set_server_id);
+BSON_DEPRECATED_FOR (mongoc_cursor_set_server_id)
+MONGOC_EXPORT (bool) mongoc_cursor_set_hint (mongoc_cursor_t *cursor, uint32_t server_id);
+
 MONGOC_EXPORT (bool)
 mongoc_cursor_set_server_id (mongoc_cursor_t *cursor, uint32_t server_id);
+
 // `mongoc_cursor_get_hint` is deprecated for more aptly named `mongoc_cursor_get_server_id`.
-MONGOC_EXPORT (uint32_t)
-mongoc_cursor_get_hint (const mongoc_cursor_t *cursor) BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_get_server_id);
+BSON_DEPRECATED_FOR (mongoc_cursor_get_server_id)
+MONGOC_EXPORT (uint32_t) mongoc_cursor_get_hint (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_cursor_get_server_id (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (int64_t)
 mongoc_cursor_get_id (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (void)
 mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor, uint32_t max_await_time_ms);
+
 MONGOC_EXPORT (uint32_t)
 mongoc_cursor_get_max_await_time_ms (const mongoc_cursor_t *cursor);
+
 MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_cursor_new_from_command_reply (struct _mongoc_client_t *client,
-                                      bson_t *reply,
-                                      uint32_t server_id) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_new_from_command_reply_with_opts);
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_cursor_new_from_command_reply_with_opts (struct _mongoc_client_t *client,
-                                                bson_t *reply,
-                                                const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_cursor_new_from_command_reply_with_opts (struct _mongoc_client_t *client, bson_t *reply, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
 
 BSON_END_DECLS
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cyrus.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cyrus.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-cyrus.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-cyrus.c	2025-06-19 15:42:22.000000000 +0000
@@ -26,11 +26,16 @@
 #include <mongoc/mongoc-trace-private.h>
 #include <common-b64-private.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #undef MONGOC_LOG_DOMAIN
 #define MONGOC_LOG_DOMAIN "CYRUS-SASL"
 
+// CDRIVER-2722: Cyrus SASL is deprecated on MacOS.
+#if defined(__APPLE__)
+BEGIN_IGNORE_DEPRECATIONS
+#endif // defined(__APPLE__)
+
 bool
 _mongoc_cyrus_set_mechanism (mongoc_cyrus_t *sasl, const char *mechanism, bson_error_t *error)
 {
@@ -57,13 +62,14 @@ _mongoc_cyrus_set_mechanism (mongoc_cyru
       bson_free (sasl->credentials.mechanism);
       sasl->credentials.mechanism = mechanism ? bson_strdup (mechanism) : NULL;
    } else {
-      bson_set_error (error,
-                      MONGOC_ERROR_SASL,
-                      SASL_NOMECH,
-                      "SASL Failure: Unsupported mechanism by client: %s. "
-                      "Available mechanisms: %s",
-                      mechanism,
-                      mcommon_str_from_append (&available_mechs_str));
+      _mongoc_set_error_with_category (error,
+                                       MONGOC_ERROR_CATEGORY_SASL,
+                                       MONGOC_ERROR_SASL,
+                                       (uint32_t) SASL_NOMECH,
+                                       "SASL Failure: Unsupported mechanism by client: %s. "
+                                       "Available mechanisms: %s",
+                                       mechanism,
+                                       mcommon_str_from_append (&available_mechs_str));
    }
 
    mcommon_string_from_append_destroy (&available_mechs_str);
@@ -129,52 +135,6 @@ _mongoc_cyrus_get_user (mongoc_cyrus_t *
    return (sasl->credentials.user != NULL) ? SASL_OK : SASL_FAIL;
 }
 
-static const char *
-sasl_verify_type_to_str (sasl_verify_type_t type)
-{
-   switch (type) {
-   case SASL_VRFY_PLUGIN:
-      return "SASL_VRFY_PLUGIN";
-   case SASL_VRFY_CONF:
-      return "SASL_VRFY_CONF";
-   case SASL_VRFY_PASSWD:
-      return "SASL_VRFY_PASSWD";
-   case SASL_VRFY_OTHER:
-      return "SASL_VRFY_OTHER";
-   default:
-      return "Unknown";
-   }
-}
-
-int
-_mongoc_cyrus_verifyfile_cb (void *context, const char *file, sasl_verify_type_t type)
-{
-   BSON_UNUSED (context);
-
-   TRACE ("Attempting to load file: `%s`. Type is %s\n", file, sasl_verify_type_to_str (type));
-
-#ifdef _WIN32
-   // On Windows, Cyrus SASL hard-codes the plugin path.
-   // Only permit loading plugin from user configured path to prevent unintentional library loading.
-   if (type == SASL_VRFY_PLUGIN) {
-      const char *path_prefix = MONGOC_CYRUS_PLUGIN_PATH_PREFIX;
-      bool has_valid_prefix = (path_prefix && file == strstr (file, path_prefix));
-      // Check if `file` has necessary prefix.
-      if (has_valid_prefix) {
-         return SASL_OK;
-      }
-      MONGOC_WARNING ("Refusing to load Cyrus SASL plugin at: '%s'. If needed, set CYRUS_PLUGIN_PATH_PREFIX (currently "
-                      "'%s') to the absolute path prefix of the plugin during build configuration of the C Driver.",
-                      file,
-                      path_prefix ? path_prefix : "(unset)");
-      return SASL_CONTINUE;
-   }
-#endif
-
-   return SASL_OK;
-}
-
-
 void
 _mongoc_cyrus_init (mongoc_cyrus_t *sasl)
 {
@@ -183,7 +143,6 @@ _mongoc_cyrus_init (mongoc_cyrus_t *sasl
                                   {SASL_CB_USER, SASL_CALLBACK_FN (_mongoc_cyrus_get_user), sasl},
                                   {SASL_CB_PASS, SASL_CALLBACK_FN (_mongoc_cyrus_get_pass), sasl},
                                   {SASL_CB_CANON_USER, SASL_CALLBACK_FN (_mongoc_cyrus_canon_user), sasl},
-                                  {SASL_CB_VERIFYFILE, SASL_CALLBACK_FN (_mongoc_cyrus_verifyfile_cb), NULL},
                                   {SASL_CB_LIST_END}};
    MC_DISABLE_CAST_FUNCTION_TYPE_STRICT_WARNING_END
 
@@ -274,7 +233,11 @@ _mongoc_cyrus_is_failure (int status, bs
    if (ret) {
       switch (status) {
       case SASL_NOMEM:
-         bson_set_error (error, MONGOC_ERROR_SASL, status, "SASL Failure: insufficient memory.");
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY_SASL,
+                                          MONGOC_ERROR_SASL,
+                                          (uint32_t) status,
+                                          "SASL Failure: insufficient memory.");
          break;
       case SASL_NOMECH: {
          mcommon_string_append_t available_mechs_str;
@@ -288,23 +251,30 @@ _mongoc_cyrus_is_failure (int status, bs
                mcommon_string_append (&available_mechs_str, ",");
             }
          }
-         bson_set_error (error,
-                         MONGOC_ERROR_SASL,
-                         status,
-                         "SASL Failure: failure to negotiate mechanism (available mechanisms: %s)",
-                         mcommon_str_from_append (&available_mechs_str));
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY_SASL,
+                                          MONGOC_ERROR_SASL,
+                                          (uint32_t) status,
+                                          "SASL Failure: failure to negotiate mechanism (available mechanisms: %s)",
+                                          mcommon_str_from_append (&available_mechs_str));
          mcommon_string_from_append_destroy (&available_mechs_str);
       } break;
       case SASL_BADPARAM:
-         bson_set_error (error,
-                         MONGOC_ERROR_SASL,
-                         status,
-                         "Bad parameter supplied. Please file a bug "
-                         "with mongo-c-driver.");
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY_SASL,
+                                          MONGOC_ERROR_SASL,
+                                          (uint32_t) status,
+                                          "Bad parameter supplied. Please file a bug "
+                                          "with mongo-c-driver.");
          break;
       default:
-         bson_set_error (
-            error, MONGOC_ERROR_SASL, status, "SASL Failure: (%d): %s", status, sasl_errstring (status, NULL, NULL));
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY_SASL,
+                                          MONGOC_ERROR_SASL,
+                                          (uint32_t) status,
+                                          "SASL Failure: (%d): %s",
+                                          status,
+                                          sasl_errstring (status, NULL, NULL));
          break;
       }
    }
@@ -348,7 +318,12 @@ _mongoc_cyrus_start (mongoc_cyrus_t *sas
    }
 
    if ((0 != strcasecmp (mechanism, "GSSAPI")) && (0 != strcasecmp (mechanism, "PLAIN"))) {
-      bson_set_error (error, MONGOC_ERROR_SASL, SASL_NOMECH, "SASL Failure: invalid mechanism \"%s\"", mechanism);
+      _mongoc_set_error_with_category (error,
+                                       MONGOC_ERROR_CATEGORY_SASL,
+                                       MONGOC_ERROR_SASL,
+                                       (uint32_t) SASL_NOMECH,
+                                       "SASL Failure: invalid mechanism \"%s\"",
+                                       mechanism);
       return false;
    }
 
@@ -358,11 +333,11 @@ _mongoc_cyrus_start (mongoc_cyrus_t *sas
 
    const int b64_ret = mcommon_b64_ntop ((uint8_t *) raw, raw_len, (char *) *outbuf, outbuf_capacity);
    if (b64_ret < 0) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 encode client SASL message");
       return false;
    } else {
-      BSON_ASSERT (mcommon_in_range_signed (uint32_t, b64_ret));
+      BSON_ASSERT (mlib_in_range (uint32_t, b64_ret));
       *outbuflen = (uint32_t) b64_ret;
    }
 
@@ -395,17 +370,21 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl
    if (sasl->step == 1) {
       return _mongoc_cyrus_start (sasl, outbuf, outbuflen, error);
    } else if (sasl->step >= 10) {
-      bson_set_error (error, MONGOC_ERROR_SASL, SASL_NOTDONE, "SASL Failure: maximum steps detected");
+      _mongoc_set_error_with_category (error,
+                                       MONGOC_ERROR_CATEGORY_SASL,
+                                       MONGOC_ERROR_SASL,
+                                       (uint32_t) SASL_NOTDONE,
+                                       "SASL Failure: maximum steps detected");
       return false;
    }
 
    TRACE ("Running %d, inbuflen: %" PRIu32, sasl->step, inbuflen);
    if (!inbuflen) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SASL,
-                      MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                      "SASL Failure: no payload provided from server: %s",
-                      sasl_errdetail (sasl->conn));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SASL,
+                         MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                         "SASL Failure: no payload provided from server: %s",
+                         sasl_errdetail (sasl->conn));
       return false;
    }
 
@@ -416,7 +395,7 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl
    {
       const int b64_ret = mcommon_b64_pton ((char *) inbuf, (uint8_t *) decoded, decoded_capacity);
       if (b64_ret < 0) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 decode client SASL message");
          bson_free (decoded);
          bson_free (*outbuf);
@@ -443,8 +422,11 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl
    {
       const int b64_ret = mcommon_b64_ntop ((const uint8_t *) raw, rawlen, (char *) *outbuf, outbuf_capacity);
       if (b64_ret < 0) {
-         bson_set_error (
-            error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 encode client SASL message");
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY,
+                                          MONGOC_ERROR_SASL,
+                                          MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                                          "Unable to base64 encode client SASL message");
          bson_free (decoded);
          bson_free (*outbuf);
          *outbuf = NULL;
@@ -452,7 +434,7 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl
       } else {
          /* Set the output length to the number of characters written excluding
           * the NULL. */
-         BSON_ASSERT (mcommon_in_range_signed (uint32_t, b64_ret));
+         BSON_ASSERT (mlib_in_range (uint32_t, b64_ret));
          *outbuflen = (uint32_t) b64_ret;
       }
    }
@@ -461,4 +443,9 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl
    return true;
 }
 
+// CDRIVER-2722: Cyrus SASL is deprecated on MacOS.
+#if defined(__APPLE__)
+END_IGNORE_DEPRECATIONS
+#endif // defined(__APPLE__)
+
 #endif
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-database.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-database.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-database.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-database.c	2025-06-19 15:42:22.000000000 +0000
@@ -23,7 +23,7 @@
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-database.h>
 #include <mongoc/mongoc-database-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-util-private.h>
@@ -175,44 +175,6 @@ mongoc_database_copy (mongoc_database_t
       database->client, database->name, database->read_prefs, database->read_concern, database->write_concern));
 }
 
-mongoc_cursor_t *
-mongoc_database_command (mongoc_database_t *database,
-                         mongoc_query_flags_t flags,
-                         uint32_t skip,
-                         uint32_t limit,
-                         uint32_t batch_size,
-                         const bson_t *command,
-                         const bson_t *fields,
-                         const mongoc_read_prefs_t *read_prefs)
-{
-   char *ns;
-   mongoc_cursor_t *cursor;
-
-   BSON_UNUSED (flags);
-   BSON_UNUSED (skip);
-   BSON_UNUSED (limit);
-   BSON_UNUSED (batch_size);
-   BSON_UNUSED (fields);
-
-   BSON_ASSERT_PARAM (database);
-   BSON_ASSERT_PARAM (command);
-
-   ns = bson_strdup_printf ("%s.$cmd", database->name);
-
-   /* Server Selection Spec: "The generic command method has a default read
-    * preference of mode 'primary'. The generic command method MUST ignore any
-    * default read preference from client, database or collection
-    * configuration. The generic command method SHOULD allow an optional read
-    * preference argument."
-    */
-
-   /* flags, skip, limit, batch_size, fields are unused */
-   cursor = _mongoc_cursor_cmd_deprecated_new (database->client, ns, command, read_prefs);
-   bson_free (ns);
-   return cursor;
-}
-
-
 bool
 mongoc_database_command_simple (mongoc_database_t *database,
                                 const bson_t *command,
@@ -713,36 +675,6 @@ cleanup:
 
 
 mongoc_cursor_t *
-mongoc_database_find_collections (mongoc_database_t *database, const bson_t *filter, bson_error_t *error)
-{
-   bson_t opts = BSON_INITIALIZER;
-   mongoc_cursor_t *cursor;
-
-   BSON_ASSERT_PARAM (database);
-
-   if (filter) {
-      if (!BSON_APPEND_DOCUMENT (&opts, "filter", filter)) {
-         bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid 'filter' parameter.");
-         bson_destroy (&opts);
-         return NULL;
-      }
-   }
-
-   cursor = mongoc_database_find_collections_with_opts (database, &opts);
-
-   bson_destroy (&opts);
-
-   /* this deprecated API returns NULL on error */
-   if (mongoc_cursor_error (cursor, error)) {
-      mongoc_cursor_destroy (cursor);
-      return NULL;
-   }
-
-   return cursor;
-}
-
-
-mongoc_cursor_t *
 mongoc_database_find_collections_with_opts (mongoc_database_t *database, const bson_t *opts)
 {
    mongoc_cursor_t *cursor;
@@ -765,13 +697,6 @@ mongoc_database_find_collections_with_op
 
 
 char **
-mongoc_database_get_collection_names (mongoc_database_t *database, bson_error_t *error)
-{
-   return mongoc_database_get_collection_names_with_opts (database, NULL, error);
-}
-
-
-char **
 mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error)
 {
    bson_t opts_copy;
@@ -839,7 +764,7 @@ create_collection (mongoc_database_t *da
    BSON_ASSERT_PARAM (name);
 
    if (strchr (name, '$')) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_NAMESPACE, MONGOC_ERROR_NAMESPACE_INVALID, "The namespace \"%s\" is invalid.", name);
       return NULL;
    }
@@ -847,10 +772,10 @@ create_collection (mongoc_database_t *da
    if (opts) {
       if (bson_iter_init_find (&iter, opts, "capped")) {
          if (!BSON_ITER_HOLDS_BOOL (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The argument \"capped\" must be a boolean.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The argument \"capped\" must be a boolean.");
             return NULL;
          }
          capped = bson_iter_bool (&iter);
@@ -858,72 +783,72 @@ create_collection (mongoc_database_t *da
 
       if (bson_iter_init_find (&iter, opts, "size")) {
          if (!BSON_ITER_HOLDS_INT (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The argument \"size\" must be an integer.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The argument \"size\" must be an integer.");
             return NULL;
          }
          if (!capped) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The \"size\" parameter requires {\"capped\": true}");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The \"size\" parameter requires {\"capped\": true}");
             return NULL;
          }
       }
 
       if (bson_iter_init_find (&iter, opts, "max")) {
          if (!BSON_ITER_HOLDS_INT (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The argument \"max\" must be an integer.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The argument \"max\" must be an integer.");
             return NULL;
          }
          if (!capped) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The \"max\" parameter requires {\"capped\": true}");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The \"max\" parameter requires {\"capped\": true}");
             return NULL;
          }
       }
 
       if (bson_iter_init_find (&iter, opts, "storageEngine")) {
          if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) {
-            bson_set_error (error,
-                            MONGOC_ERROR_COMMAND,
-                            MONGOC_ERROR_COMMAND_INVALID_ARG,
-                            "The \"storageEngine\" parameter must be a document");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_COMMAND,
+                               MONGOC_ERROR_COMMAND_INVALID_ARG,
+                               "The \"storageEngine\" parameter must be a document");
 
             return NULL;
          }
 
          if (bson_iter_find (&iter, "wiredTiger")) {
             if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) {
-               bson_set_error (error,
-                               MONGOC_ERROR_COMMAND,
-                               MONGOC_ERROR_COMMAND_INVALID_ARG,
-                               "The \"wiredTiger\" option must take a document "
-                               "argument with a \"configString\" field");
+               _mongoc_set_error (error,
+                                  MONGOC_ERROR_COMMAND,
+                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                  "The \"wiredTiger\" option must take a document "
+                                  "argument with a \"configString\" field");
                return NULL;
             }
 
             if (bson_iter_find (&iter, "configString")) {
                if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-                  bson_set_error (error,
-                                  MONGOC_ERROR_COMMAND,
-                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
-                                  "The \"configString\" parameter must be a string");
+                  _mongoc_set_error (error,
+                                     MONGOC_ERROR_COMMAND,
+                                     MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                     "The \"configString\" parameter must be a string");
                   return NULL;
                }
             } else {
-               bson_set_error (error,
-                               MONGOC_ERROR_COMMAND,
-                               MONGOC_ERROR_COMMAND_INVALID_ARG,
-                               "The \"wiredTiger\" option must take a document "
-                               "argument with a \"configString\" field");
+               _mongoc_set_error (error,
+                                  MONGOC_ERROR_COMMAND,
+                                  MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                  "The \"wiredTiger\" option must take a document "
+                                  "argument with a \"configString\" field");
                return NULL;
             }
          }
@@ -969,22 +894,22 @@ _mongoc_get_encryptedField_state_collect
    } else if (0 == strcmp (state_collection_suffix, "ecoc")) {
       fieldName = "ecocCollection";
    } else {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected state_collection_suffix to be 'esc' or "
-                      "'ecoc', got: %s",
-                      state_collection_suffix);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected state_collection_suffix to be 'esc' or "
+                         "'ecoc', got: %s",
+                         state_collection_suffix);
       return NULL;
    }
 
    if (bson_iter_init_find (&iter, encryptedFields, fieldName)) {
       if (!BSON_ITER_HOLDS_UTF8 (&iter)) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "expected encryptedFields.%s to be UTF-8",
-                         fieldName);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "expected encryptedFields.%s to be UTF-8",
+                            fieldName);
          return NULL;
       }
       return bson_strdup (bson_iter_utf8 (&iter, NULL));
@@ -1049,14 +974,14 @@ create_collection_with_encryptedFields (
          goto fail;
       }
       if (stream->sd->max_wire_version < WIRE_VERSION_7_0) {
-         bson_set_error (error,
-                         MONGOC_ERROR_PROTOCOL,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "Driver support of Queryable Encryption is incompatible "
-                         "with server. Upgrade server to use Queryable Encryption. "
-                         "Got maxWireVersion %" PRId32 " but need maxWireVersion >= %d",
-                         stream->sd->max_wire_version,
-                         WIRE_VERSION_7_0);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_PROTOCOL,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "Driver support of Queryable Encryption is incompatible "
+                            "with server. Upgrade server to use Queryable Encryption. "
+                            "Got maxWireVersion %" PRId32 " but need maxWireVersion >= %d",
+                            stream->sd->max_wire_version,
+                            WIRE_VERSION_7_0);
          mongoc_server_stream_cleanup (stream);
          goto fail;
       }
@@ -1073,7 +998,7 @@ create_collection_with_encryptedFields (
    /* Create data collection. */
    cc_opts = bson_copy (opts);
    if (!BSON_APPEND_DOCUMENT (cc_opts, "encryptedFields", encryptedFields)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "unable to append encryptedFields");
       goto fail;
    }
@@ -1161,7 +1086,7 @@ _mongoc_get_encryptedFields_from_server
       /* Check if the collInfo has options.encryptedFields. */
       bson_iter_t iter;
       if (!bson_iter_init (&iter, collInfo)) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "unable to iterate listCollections result");
          goto fail;
       }
@@ -1216,11 +1141,11 @@ _mongoc_get_collection_encryptedFields (
                        do (found = true)));
       if (bsonParseError) {
          // Error while parsing
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid createCollection command options: %s",
-                         bsonParseError);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid createCollection command options: %s",
+                            bsonParseError);
          return false;
       } else if (found) {
          // Found it!
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-database.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-database.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-database.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-database.h	2025-06-19 15:42:22.000000000 +0000
@@ -22,6 +22,8 @@
 #include <bson/bson.h>
 
 #include <mongoc/mongoc-macros.h>
+#include <mongoc/mongoc-change-stream.h>
+#include <mongoc/mongoc-collection.h>
 #include <mongoc/mongoc-cursor.h>
 #include <mongoc/mongoc-flags.h>
 #include <mongoc/mongoc-read-prefs.h>
@@ -36,10 +38,13 @@ typedef struct _mongoc_database_t mongoc
 
 MONGOC_EXPORT (const char *)
 mongoc_database_get_name (mongoc_database_t *database);
+
 MONGOC_EXPORT (bool)
 mongoc_database_remove_user (mongoc_database_t *database, const char *username, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_remove_all_users (mongoc_database_t *database, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_add_user (mongoc_database_t *database,
                           const char *username,
@@ -47,25 +52,19 @@ mongoc_database_add_user (mongoc_databas
                           const bson_t *roles,
                           const bson_t *custom_data,
                           bson_error_t *error);
+
 MONGOC_EXPORT (void)
 mongoc_database_destroy (mongoc_database_t *database);
+
 MONGOC_EXPORT (mongoc_cursor_t *)
 mongoc_database_aggregate (mongoc_database_t *db,
                            const bson_t *pipeline,
                            const bson_t *opts,
                            const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_database_t *)
 mongoc_database_copy (mongoc_database_t *database) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_database_command (mongoc_database_t *database,
-                         mongoc_query_flags_t flags,
-                         uint32_t skip,
-                         uint32_t limit,
-                         uint32_t batch_size,
-                         const bson_t *command,
-                         const bson_t *fields,
-                         const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_database_command_simple);
+
 MONGOC_EXPORT (bool)
 mongoc_database_read_command_with_opts (mongoc_database_t *database,
                                         const bson_t *command,
@@ -73,9 +72,11 @@ mongoc_database_read_command_with_opts (
                                         const bson_t *opts,
                                         bson_t *reply,
                                         bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_write_command_with_opts (
    mongoc_database_t *database, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_read_write_command_with_opts (mongoc_database_t *database,
                                               const bson_t *command,
@@ -83,6 +84,7 @@ mongoc_database_read_write_command_with_
                                               const bson_t *opts,
                                               bson_t *reply,
                                               bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_command_with_opts (mongoc_database_t *database,
                                    const bson_t *command,
@@ -90,56 +92,61 @@ mongoc_database_command_with_opts (mongo
                                    const bson_t *opts,
                                    bson_t *reply,
                                    bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_command_simple (mongoc_database_t *database,
                                 const bson_t *command,
                                 const mongoc_read_prefs_t *read_prefs,
                                 bson_t *reply,
                                 bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_drop (mongoc_database_t *database, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_drop_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_database_has_collection (mongoc_database_t *database, const char *name, bson_error_t *error);
+
 MONGOC_EXPORT (mongoc_collection_t *)
 mongoc_database_create_collection (mongoc_database_t *database,
                                    const char *name,
                                    const bson_t *options,
                                    bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (const mongoc_read_prefs_t *)
 mongoc_database_get_read_prefs (const mongoc_database_t *database);
+
 MONGOC_EXPORT (void)
 mongoc_database_set_read_prefs (mongoc_database_t *database, const mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (const mongoc_write_concern_t *)
 mongoc_database_get_write_concern (const mongoc_database_t *database);
+
 MONGOC_EXPORT (void)
 mongoc_database_set_write_concern (mongoc_database_t *database, const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (const mongoc_read_concern_t *)
 mongoc_database_get_read_concern (const mongoc_database_t *database);
+
 MONGOC_EXPORT (void)
 mongoc_database_set_read_concern (mongoc_database_t *database, const mongoc_read_concern_t *read_concern);
+
 MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_database_find_collections (mongoc_database_t *database,
-                                  const bson_t *filter,
-                                  bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_database_find_collections_with_opts);
-MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_database_find_collections_with_opts (mongoc_database_t *database,
-                                            const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (char **)
-mongoc_database_get_collection_names (mongoc_database_t *database, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_database_get_collection_names_with_opts);
+mongoc_database_find_collections_with_opts (mongoc_database_t *database, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (char **)
-mongoc_database_get_collection_names_with_opts (mongoc_database_t *database,
-                                                const bson_t *opts,
-                                                bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_collection_t *)
 mongoc_database_get_collection (mongoc_database_t *database, const char *name) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_change_stream_t *)
-mongoc_database_watch (const mongoc_database_t *db,
-                       const bson_t *pipeline,
-                       const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_database_watch (const mongoc_database_t *db, const bson_t *pipeline, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
 
 BSON_END_DECLS
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-error-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-error-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-error-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-error-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -19,6 +19,8 @@
 #ifndef MONGOC_ERROR_PRIVATE_H
 #define MONGOC_ERROR_PRIVATE_H
 
+#include "mongoc-error.h"
+
 #include <bson/bson.h>
 #include <stddef.h>
 
@@ -105,6 +107,34 @@ typedef enum {
 bool
 mongoc_error_append_contents_to_bson (const bson_error_t *error, bson_t *bson, mongoc_error_content_flags_t flags);
 
+void
+_mongoc_set_error (bson_error_t *error, uint32_t domain, uint32_t code, const char *format, ...)
+   BSON_GNUC_PRINTF (4, 5);
+
+void
+_mongoc_set_error_with_category (
+   bson_error_t *error, uint8_t category, uint32_t domain, uint32_t code, const char *format, ...)
+   BSON_GNUC_PRINTF (5, 6);
+
+#define MONGOC_ERROR_CATEGORY_BSON 1 // BSON_ERROR_CATEGORY
+#define MONGOC_ERROR_CATEGORY 2
+#define MONGOC_ERROR_CATEGORY_SERVER 3
+#define MONGOC_ERROR_CATEGORY_CRYPT 4
+#define MONGOC_ERROR_CATEGORY_SASL 5
+
+static BSON_INLINE void
+_mongoc_set_error_category (bson_error_t *error, uint8_t category)
+{
+   BSON_ASSERT_PARAM (error);
+   error->reserved = category;
+}
+
+#ifdef _WIN32
+// Call `mongoc_winerr_to_string` on a Windows error code (e.g. a return from GetLastError()).
+char *
+mongoc_winerr_to_string (DWORD err_code);
+#endif
+
 BSON_END_DECLS
 
 #endif /* MONGOC_ERROR_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-error.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-error.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-error.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-error.c	2025-06-19 15:42:22.000000000 +0000
@@ -338,3 +338,71 @@ mongoc_error_append_contents_to_bson (co
    }
    return true;
 }
+
+void
+_mongoc_set_error (bson_error_t *error, uint32_t domain, uint32_t code, const char *format, ...)
+{
+   if (error) {
+      error->domain = domain;
+      error->code = code;
+      _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
+
+      va_list args;
+      va_start (args, format);
+      bson_vsnprintf (error->message, sizeof error->message, format, args);
+      va_end (args);
+   }
+}
+
+void
+_mongoc_set_error_with_category (
+   bson_error_t *error, uint8_t category, uint32_t domain, uint32_t code, const char *format, ...)
+{
+   if (error) {
+      error->domain = domain;
+      error->code = code;
+      _mongoc_set_error_category (error, category);
+
+      va_list args;
+      va_start (args, format);
+      bson_vsnprintf (error->message, sizeof error->message, format, args);
+      va_end (args);
+   }
+}
+
+#ifdef _WIN32
+
+char *
+mongoc_winerr_to_string (DWORD err_code)
+{
+   LPSTR msg = NULL;
+   if (0 == FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY |
+                               FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+                            NULL,
+                            err_code,
+                            MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
+                            (LPSTR) &msg,
+                            0,
+                            NULL)) {
+      LocalFree (msg);
+      return bson_strdup_printf ("(0x%.8lX) (Failed to get error message)", err_code);
+   }
+
+   // Remove trailing newline.
+   size_t msglen = strlen (msg);
+   if (msglen >= 1 && msg[msglen - 1] == '\n') {
+      if (msglen >= 2 && msg[msglen - 2] == '\r') {
+         // Remove trailing \r\n.
+         msg[msglen - 2] = '\0';
+      } else {
+         // Just remove trailing \n.
+         msg[msglen - 1] = '\0';
+      }
+   }
+
+   char *ret = bson_strdup_printf ("(0x%.8lX) %s", err_code, msg);
+   LocalFree (msg);
+   return ret;
+}
+
+#endif // _WIN32
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-flags.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-flags.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-flags.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-flags.c	2025-06-19 15:42:22.000000000 +0000
@@ -36,12 +36,6 @@ BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_C
 BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_MORE_TO_COME == MONGOC_MSG_MORE_TO_COME);
 BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED == MONGOC_MSG_EXHAUST_ALLOWED);
 
-BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_NONE == MONGOC_REPLY_NONE);
-BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND == MONGOC_REPLY_CURSOR_NOT_FOUND);
-BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_QUERY_FAILURE == MONGOC_REPLY_QUERY_FAILURE);
-BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_SHARD_CONFIG_STALE == MONGOC_REPLY_SHARD_CONFIG_STALE);
-BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_AWAIT_CAPABLE == MONGOC_REPLY_AWAIT_CAPABLE);
-
 BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_NONE == MONGOC_UPDATE_NONE);
 BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_UPSERT == MONGOC_UPDATE_UPSERT);
 BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_MULTI_UPDATE == MONGOC_UPDATE_MULTI_UPDATE);
@@ -57,6 +51,3 @@ BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG
 BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_AWAIT_DATA == MONGOC_QUERY_AWAIT_DATA);
 BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_EXHAUST == MONGOC_QUERY_EXHAUST);
 BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_PARTIAL == MONGOC_QUERY_PARTIAL);
-
-BSON_STATIC_ASSERT (MONGOC_OP_DELETE_FLAG_NONE == MONGOC_DELETE_NONE);
-BSON_STATIC_ASSERT (MONGOC_OP_DELETE_FLAG_SINGLE_REMOVE == MONGOC_DELETE_SINGLE_REMOVE);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-flags.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-flags.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-flags.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-flags.h	2025-06-19 15:42:22.000000000 +0000
@@ -26,23 +26,6 @@ BSON_BEGIN_DECLS
 
 
 /**
- * mongoc_delete_flags_t:
- * @MONGOC_DELETE_NONE: Specify no delete flags.
- * @MONGOC_DELETE_SINGLE_REMOVE: Only remove the first document matching the
- *    document selector.
- *
- * This type is only for use with deprecated functions and should not be
- * used in new code. Use mongoc_remove_flags_t instead.
- *
- * #mongoc_delete_flags_t are used when performing a delete operation.
- */
-typedef enum {
-   MONGOC_DELETE_NONE = 0,
-   MONGOC_DELETE_SINGLE_REMOVE = 1 << 0,
-} mongoc_delete_flags_t;
-
-
-/**
  * mongoc_remove_flags_t:
  * @MONGOC_REMOVE_NONE: Specify no delete flags.
  * @MONGOC_REMOVE_SINGLE_REMOVE: Only remove the first document matching the
@@ -95,7 +78,6 @@ typedef enum {
 typedef enum {
    MONGOC_QUERY_NONE = 0,
    MONGOC_QUERY_TAILABLE_CURSOR = 1 << 1,
-   MONGOC_QUERY_SLAVE_OK = 1 << 2,
    MONGOC_QUERY_SECONDARY_OK = 1 << 2,
    MONGOC_QUERY_OPLOG_REPLAY = 1 << 3,
    MONGOC_QUERY_NO_CURSOR_TIMEOUT = 1 << 4,
@@ -106,27 +88,6 @@ typedef enum {
 
 
 /**
- * mongoc_reply_flags_t:
- * @MONGOC_REPLY_NONE: No flags set.
- * @MONGOC_REPLY_CURSOR_NOT_FOUND: Cursor was not found.
- * @MONGOC_REPLY_QUERY_FAILURE: Query failed, error document provided.
- * @MONGOC_REPLY_SHARD_CONFIG_STALE: Shard configuration is stale.
- * @MONGOC_REPLY_AWAIT_CAPABLE: Wait for data to be returned until timeout
- *    has passed. Used with %MONGOC_QUERY_TAILABLE_CURSOR.
- *
- * #mongoc_reply_flags_t contains flags supplied by the Mongo server in reply
- * to a request.
- */
-typedef enum {
-   MONGOC_REPLY_NONE = 0,
-   MONGOC_REPLY_CURSOR_NOT_FOUND = 1 << 0,
-   MONGOC_REPLY_QUERY_FAILURE = 1 << 1,
-   MONGOC_REPLY_SHARD_CONFIG_STALE = 1 << 2,
-   MONGOC_REPLY_AWAIT_CAPABLE = 1 << 3,
-} mongoc_reply_flags_t;
-
-
-/**
  * mongoc_update_flags_t:
  * @MONGOC_UPDATE_NONE: No update flags specified.
  * @MONGOC_UPDATE_UPSERT: Perform an upsert.
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,7 @@
  */
 
 #include <mongoc/mongoc.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-gridfs-bucket-file-private.h>
 #include <mongoc/mongoc-gridfs-bucket-private.h>
 #include <mongoc/mongoc-trace-private.h>
@@ -22,7 +23,7 @@
 #include <mongoc/mongoc-stream-gridfs-upload-private.h>
 #include <mongoc/mongoc-collection-private.h>
 #include <mongoc/mongoc-util-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <inttypes.h>
 
@@ -240,36 +241,36 @@ _mongoc_gridfs_bucket_read_chunk (mongoc
    }
 
    if (!r) {
-      bson_set_error (
+      _mongoc_set_error (
          &file->err, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "Missing chunk %d.", file->curr_chunk);
       return false;
    }
 
    r = bson_iter_init_find (&iter, next, "n");
    if (!r) {
-      bson_set_error (&file->err,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_CORRUPT,
-                      "Chunk %d missing a required field 'n'.",
-                      file->curr_chunk);
+      _mongoc_set_error (&file->err,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_CORRUPT,
+                         "Chunk %d missing a required field 'n'.",
+                         file->curr_chunk);
       return false;
    }
 
    n = bson_iter_int32 (&iter);
 
    if (n != file->curr_chunk) {
-      bson_set_error (
+      _mongoc_set_error (
          &file->err, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "Missing chunk %d.", file->curr_chunk);
       return false;
    }
 
    r = bson_iter_init_find (&iter, next, "data");
    if (!r) {
-      bson_set_error (&file->err,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_CORRUPT,
-                      "Chunk %d missing a required field 'data'.",
-                      file->curr_chunk);
+      _mongoc_set_error (&file->err,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_CORRUPT,
+                         "Chunk %d missing a required field 'data'.",
+                         file->curr_chunk);
       return false;
    }
 
@@ -283,13 +284,13 @@ _mongoc_gridfs_bucket_read_chunk (mongoc
    }
 
    if (data_len != expected_size) {
-      bson_set_error (&file->err,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_CORRUPT,
-                      "Chunk %d expected to have size %" PRId64 " but is size %" PRIu32 ".",
-                      file->curr_chunk,
-                      expected_size,
-                      data_len);
+      _mongoc_set_error (&file->err,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_CORRUPT,
+                         "Chunk %d expected to have size %" PRId64 " but is size %" PRIu32 ".",
+                         file->curr_chunk,
+                         expected_size,
+                         data_len);
       return false;
    }
 
@@ -315,10 +316,10 @@ _mongoc_gridfs_bucket_file_writev (mongo
    }
 
    if (file->saved) {
-      bson_set_error (&file->err,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR,
-                      "Cannot write after saving/aborting on a GridFS file.");
+      _mongoc_set_error (&file->err,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR,
+                         "Cannot write after saving/aborting on a GridFS file.");
       return -1;
    }
 
@@ -331,7 +332,7 @@ _mongoc_gridfs_bucket_file_writev (mongo
       }
    }
 
-   BSON_ASSERT (mcommon_in_range_signed (size_t, file->chunk_size));
+   BSON_ASSERT (mlib_in_range (size_t, file->chunk_size));
    const size_t chunk_size = (size_t) file->chunk_size;
 
    for (size_t i = 0u; i < iovcnt; i++) {
@@ -355,7 +356,7 @@ _mongoc_gridfs_bucket_file_writev (mongo
       }
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, total));
+   BSON_ASSERT (mlib_in_range (ssize_t, total));
    return (ssize_t) total;
 }
 
@@ -399,14 +400,14 @@ _mongoc_gridfs_bucket_file_readv (mongoc
             }
             if (file->finished) {
                /* There's nothing left to read */
-               BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, total));
+               BSON_ASSERT (mlib_in_range (ssize_t, total));
                RETURN ((ssize_t) total);
             }
          }
       }
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, total));
+   BSON_ASSERT (mlib_in_range (ssize_t, total));
    RETURN ((ssize_t) total);
 }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-cursor-private.h>
 #include <mongoc/mongoc-database-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-gridfs-bucket-private.h>
 #include <mongoc/mongoc-gridfs-bucket-file-private.h>
 #include <mongoc/mongoc-opts-private.h>
@@ -64,7 +65,7 @@ _mongoc_gridfs_find_file_with_id (mongoc
    r = mongoc_cursor_next (cursor, &doc);
    if (!r) {
       if (!mongoc_cursor_error (cursor, error)) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, "No file with given id exists");
       }
    } else {
@@ -96,12 +97,12 @@ mongoc_gridfs_bucket_new (mongoc_databas
 
    /* Initialize the bucket fields */
    if (strlen (gridfs_opts.bucketName) + strlen (".chunks") + 1 > sizeof (buf)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "bucketName \"%s\" must have fewer than %d characters",
-                      gridfs_opts.bucketName,
-                      (int) (sizeof (buf) - (strlen (".chunks") + 1)));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "bucketName \"%s\" must have fewer than %d characters",
+                         gridfs_opts.bucketName,
+                         (int) (sizeof (buf) - (strlen (".chunks") + 1)));
       return NULL;
    }
 
@@ -254,7 +255,7 @@ mongoc_gridfs_bucket_upload_from_stream_
 
    if (bytes_read < 0) {
       mongoc_gridfs_bucket_abort_upload (upload_stream);
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_STREAM, "Error occurred on the provided stream.");
       mongoc_stream_destroy (upload_stream);
       return false;
@@ -322,7 +323,7 @@ mongoc_gridfs_bucket_open_download_strea
    }
 
    if (!bson_iter_init (&iter, &file_doc)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "File document malformed");
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "File document malformed");
       return NULL;
    }
 
@@ -375,7 +376,7 @@ mongoc_gridfs_bucket_download_to_stream
    while ((bytes_read = mongoc_stream_read (download_stream, buf, 256, 1, 0)) > 0) {
       bytes_written = mongoc_stream_write (destination, buf, bytes_read, 0);
       if (bytes_written < 0) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_STREAM, "Error occurred on the provided stream.");
          mongoc_stream_destroy (download_stream);
          return false;
@@ -412,7 +413,7 @@ mongoc_gridfs_bucket_delete_by_id (mongo
    BSON_ASSERT (bson_iter_init_find (&iter, &reply, "deletedCount"));
 
    if (bson_iter_as_int64 (&iter) != 1) {
-      bson_set_error (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, "File not found");
+      _mongoc_set_error (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, "File not found");
       bson_destroy (&reply);
       return false;
    }
@@ -441,7 +442,7 @@ mongoc_gridfs_bucket_find (mongoc_gridfs
 
    cursor = mongoc_collection_find_with_opts (bucket->files, filter, opts, NULL);
    if (!cursor->error.code && opts && bson_has_field (opts, "sessionId")) {
-      bson_set_error (
+      _mongoc_set_error (
          &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot pass sessionId as an option");
    }
    return cursor;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h	2025-06-19 15:42:22.000000000 +0000
@@ -79,9 +79,8 @@ MONGOC_EXPORT (bool)
 mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, bson_error_t *error);
 
 MONGOC_EXPORT (mongoc_cursor_t *)
-mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket,
-                           const bson_t *filter,
-                           const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket, const bson_t *filter, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
 
 MONGOC_EXPORT (bool)
 mongoc_gridfs_bucket_stream_error (mongoc_stream_t *stream, bson_error_t *error);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c	2025-06-19 15:42:22.000000000 +0000
@@ -29,10 +29,6 @@
 #include <mongoc/mongoc-trace-private.h>
 
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "gridfs_file_list"
-
-
 mongoc_gridfs_file_list_t *
 _mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, const bson_t *query, uint32_t limit)
 {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-file.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-file.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs-file.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs-file.c	2025-06-19 15:42:22.000000000 +0000
@@ -34,8 +34,8 @@
 #include <mongoc/mongoc-iovec.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-util-private.h>
-#include <mongoc/mongoc-error.h>
-#include <common-cmp-private.h>
+#include <mongoc/mongoc-error-private.h>
+#include <mlib/cmp.h>
 
 static bool
 _mongoc_gridfs_file_refresh_page (mongoc_gridfs_file_t *file);
@@ -107,7 +107,7 @@ bool
 mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file, const bson_value_t *id, bson_error_t *error)
 {
    if (!file->is_dirty) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR, "Cannot set file id after saving file.");
       return false;
    }
@@ -435,7 +435,7 @@ mongoc_gridfs_file_readv (
    BSON_ASSERT (iovcnt);
 
    /* Reading when positioned past the end does nothing */
-   if (mcommon_cmp_greater_equal_us (file->pos, file->length)) {
+   if (mlib_cmp (file->pos, >=, file->length)) {
       return 0;
    }
 
@@ -459,7 +459,7 @@ mongoc_gridfs_file_readv (
          if (iov_pos == iov[i].iov_len) {
             /* filled a bucket, keep going */
             break;
-         } else if (file->length == file->pos) {
+         } else if (mlib_cmp (file->length, ==, file->pos)) {
             /* we're at the end of the file.  So we're done */
             RETURN (bytes_read);
          } else if (bytes_read >= min_bytes) {
@@ -499,7 +499,7 @@ mongoc_gridfs_file_writev (mongoc_gridfs
    }
 
    /* When writing past the end-of-file, fill the gap with zeros */
-   if (mcommon_cmp_greater_us (file->pos, file->length) && !_mongoc_gridfs_file_extend (file)) {
+   if (mlib_cmp (file->pos, >, file->length) && !_mongoc_gridfs_file_extend (file)) {
       return -1;
    }
 
@@ -564,13 +564,13 @@ _mongoc_gridfs_file_extend (mongoc_gridf
 
    BSON_ASSERT (file);
 
-   if (mcommon_cmp_greater_equal_su (file->length, file->pos)) {
+   if (mlib_cmp (file->length, >=, file->pos)) {
       RETURN (0);
    }
 
    const uint64_t target_length = file->pos;
 
-   BSON_ASSERT (mcommon_in_range_signed (uint64_t, file->length));
+   BSON_ASSERT (mlib_in_range (uint64_t, file->length));
    const uint64_t diff = file->pos - (uint64_t) file->length;
 
    if (-1 == mongoc_gridfs_file_seek (file, 0, SEEK_END)) {
@@ -585,7 +585,7 @@ _mongoc_gridfs_file_extend (mongoc_gridf
       /* Set bytes until we reach the limit or fill a page */
       {
          const uint64_t len = target_length - file->pos;
-         BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, len));
+         BSON_ASSERT (mlib_in_range (uint32_t, len));
          file->pos += _mongoc_gridfs_file_page_memset0 (file->page, (uint32_t) len);
       }
 
@@ -598,11 +598,11 @@ _mongoc_gridfs_file_extend (mongoc_gridf
       }
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int64_t, target_length));
+   BSON_ASSERT (mlib_in_range (int64_t, target_length));
    file->length = (int64_t) target_length;
    file->is_dirty = true;
 
-   BSON_ASSERT (mcommon_in_range_unsigned (ssize_t, diff));
+   BSON_ASSERT (mlib_in_range (ssize_t, diff));
    RETURN ((ssize_t) diff);
 }
 
@@ -710,7 +710,7 @@ divide_round_up (int64_t num, int64_t de
 static void
 missing_chunk (mongoc_gridfs_file_t *file)
 {
-   bson_set_error (
+   _mongoc_set_error (
       &file->error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "missing chunk number %" PRId32, file->n);
 
    if (file->cursor) {
@@ -812,7 +812,7 @@ _mongoc_gridfs_file_refresh_page (mongoc
 
       /* we might have had a cursor before, then seeked ahead past a chunk.
        * iterate until we're on the right chunk */
-      while (mcommon_cmp_less_equal_us (file->cursor_range[0], file->n)) {
+      while (mlib_cmp (file->cursor_range[0], <=, file->n)) {
          if (!mongoc_cursor_next (file->cursor, &chunk)) {
             /* copy cursor error; if there's none, we're missing a chunk */
             if (!mongoc_cursor_error (file->cursor, &file->error)) {
@@ -842,13 +842,13 @@ _mongoc_gridfs_file_refresh_page (mongoc
             // If this not the last chunk, ensure length is equal to chunk size.
             bool is_last_chunk = ((file->n + 1) == existing_chunks);
             // If this is not the last chunk, error.
-            if (!is_last_chunk && mcommon_cmp_not_equal_us (len, file->chunk_size)) {
-               bson_set_error (&file->error,
-                               MONGOC_ERROR_GRIDFS,
-                               MONGOC_ERROR_GRIDFS_CORRUPT,
-                               "corrupt chunk number %" PRId32 ": not equal to chunk size: %" PRId32,
-                               file->n,
-                               file->chunk_size);
+            if (!is_last_chunk && mlib_cmp (len, !=, file->chunk_size)) {
+               _mongoc_set_error (&file->error,
+                                  MONGOC_ERROR_GRIDFS,
+                                  MONGOC_ERROR_GRIDFS_CORRUPT,
+                                  "corrupt chunk number %" PRId32 ": not equal to chunk size: %" PRId32,
+                                  file->n,
+                                  file->chunk_size);
                RETURN (0);
             }
          } else {
@@ -857,27 +857,27 @@ _mongoc_gridfs_file_refresh_page (mongoc
          }
       }
 
-      if (file->n != file->pos / file->chunk_size) {
+      if (mlib_cmp (file->n, !=, file->pos / file->chunk_size)) {
          return 0;
       }
    }
 
    if (!data) {
-      bson_set_error (&file->error,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_CHUNK_MISSING,
-                      "corrupt chunk number %" PRId32 ": no data",
-                      file->n);
+      _mongoc_set_error (&file->error,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_CHUNK_MISSING,
+                         "corrupt chunk number %" PRId32 ": no data",
+                         file->n);
       RETURN (0);
    }
 
-   if (mcommon_cmp_greater_us (len, file->chunk_size)) {
-      bson_set_error (&file->error,
-                      MONGOC_ERROR_GRIDFS,
-                      MONGOC_ERROR_GRIDFS_CORRUPT,
-                      "corrupt chunk number %" PRId32 ": greater than chunk size: %" PRId32,
-                      file->n,
-                      file->chunk_size);
+   if (mlib_cmp (len, >, file->chunk_size)) {
+      _mongoc_set_error (&file->error,
+                         MONGOC_ERROR_GRIDFS,
+                         MONGOC_ERROR_GRIDFS_CORRUPT,
+                         "corrupt chunk number %" PRId32 ": greater than chunk size: %" PRId32,
+                         file->n,
+                         file->chunk_size);
       RETURN (0);
    }
 
@@ -931,7 +931,7 @@ mongoc_gridfs_file_seek (mongoc_gridfs_f
       offset = delta;
       break;
    case SEEK_CUR:
-      BSON_ASSERT (mcommon_in_range_unsigned (int64_t, file->pos));
+      BSON_ASSERT (mlib_in_range (int64_t, file->pos));
       offset = (int64_t) file->pos + delta;
       break;
    case SEEK_END:
@@ -965,15 +965,15 @@ mongoc_gridfs_file_seek (mongoc_gridfs_f
        * lazily load */
    } else if (file->page) {
       const int64_t n = offset % file->chunk_size;
-      BSON_ASSERT (mcommon_in_range_signed (uint32_t, n));
+      BSON_ASSERT (mlib_in_range (uint32_t, n));
       BSON_ASSERT (_mongoc_gridfs_file_page_seek (file->page, (uint32_t) n));
    }
 
    file->pos = (uint64_t) offset;
 
-   BSON_ASSERT (mcommon_in_range_signed (uint64_t, file->chunk_size));
+   BSON_ASSERT (mlib_in_range (uint64_t, file->chunk_size));
    const uint64_t n = file->pos / (uint64_t) file->chunk_size;
-   BSON_ASSERT (mcommon_in_range_unsigned (int32_t, n));
+   BSON_ASSERT (mlib_in_range (int32_t, n));
    file->n = (int32_t) n;
 
    return 0;
@@ -994,7 +994,9 @@ mongoc_gridfs_file_error (mongoc_gridfs_
    BSON_ASSERT (error);
 
    if (BSON_UNLIKELY (file->error.domain)) {
-      bson_set_error (error, file->error.domain, file->error.code, "%s", file->error.message);
+      if (error) {
+         *error = file->error;
+      }
       RETURN (true);
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,8 +22,7 @@
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-collection.h>
 #include <mongoc/mongoc-collection-private.h>
-#include <mongoc/mongoc-error.h>
-#include <mongoc/mongoc-index.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-gridfs.h>
 #include <mongoc/mongoc-gridfs-private.h>
 #include <mongoc/mongoc-gridfs-file.h>
@@ -177,37 +176,6 @@ mongoc_gridfs_destroy (mongoc_gridfs_t *
 
 /** find all matching gridfs files */
 mongoc_gridfs_file_list_t *
-mongoc_gridfs_find (mongoc_gridfs_t *gridfs, const bson_t *query)
-{
-   return _mongoc_gridfs_file_list_new (gridfs, query, 0);
-}
-
-
-/** find a single gridfs file */
-mongoc_gridfs_file_t *
-mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, const bson_t *query, bson_error_t *error)
-{
-   mongoc_gridfs_file_list_t *list;
-   mongoc_gridfs_file_t *file;
-
-   ENTRY;
-
-   list = _mongoc_gridfs_file_list_new (gridfs, query, 1);
-
-   file = mongoc_gridfs_file_list_next (list);
-   if (!mongoc_gridfs_file_list_error (list, error) && error) {
-      /* no error, but an error out-pointer was provided - clear it */
-      memset (error, 0, sizeof (*error));
-   }
-
-   mongoc_gridfs_file_list_destroy (list);
-
-   RETURN (file);
-}
-
-
-/** find all matching gridfs files */
-mongoc_gridfs_file_list_t *
 mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts)
 {
    return _mongoc_gridfs_file_list_new_with_opts (gridfs, filter, opts);
@@ -385,7 +353,7 @@ mongoc_gridfs_remove_by_filename (mongoc
    BSON_ASSERT (gridfs);
 
    if (!filename) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_INVALID_FILENAME, "A non-NULL filename must be specified.");
       return false;
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-gridfs.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-gridfs.h	2025-06-19 15:42:22.000000000 +0000
@@ -33,40 +33,39 @@ BSON_BEGIN_DECLS
 
 typedef struct _mongoc_gridfs_t mongoc_gridfs_t;
 
-
 MONGOC_EXPORT (mongoc_gridfs_file_t *)
-mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs,
-                                       mongoc_stream_t *stream,
-                                       mongoc_gridfs_file_opt_t *opt) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, mongoc_stream_t *stream, mongoc_gridfs_file_opt_t *opt)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_gridfs_file_t *)
 mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs, mongoc_gridfs_file_opt_t *opt) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_gridfs_file_list_t *)
-mongoc_gridfs_find (mongoc_gridfs_t *gridfs, const bson_t *query) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_gridfs_find_with_opts);
-MONGOC_EXPORT (mongoc_gridfs_file_t *)
-mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, const bson_t *query, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_gridfs_find_one_with_opts);
-MONGOC_EXPORT (mongoc_gridfs_file_list_t *)
-mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs,
-                              const bson_t *filter,
-                              const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_gridfs_file_t *)
 mongoc_gridfs_find_one_with_opts (mongoc_gridfs_t *gridfs,
                                   const bson_t *filter,
                                   const bson_t *opts,
                                   bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_gridfs_file_t *)
-mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs,
-                                    const char *filename,
-                                    bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs, const char *filename, bson_error_t *error)
+   BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (bool)
 mongoc_gridfs_drop (mongoc_gridfs_t *gridfs, bson_error_t *error);
+
 MONGOC_EXPORT (void)
 mongoc_gridfs_destroy (mongoc_gridfs_t *gridfs);
+
 MONGOC_EXPORT (mongoc_collection_t *)
 mongoc_gridfs_get_files (mongoc_gridfs_t *gridfs);
+
 MONGOC_EXPORT (mongoc_collection_t *)
 mongoc_gridfs_get_chunks (mongoc_gridfs_t *gridfs);
+
 MONGOC_EXPORT (bool)
 mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, const char *filename, bson_error_t *error);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-handshake-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-handshake-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-handshake-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-handshake-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -61,8 +61,8 @@ typedef enum {
    MONGOC_MD_FLAG_EXPERIMENTAL_FEATURES = 10,
    MONGOC_MD_FLAG_HAVE_SASL_CLIENT_DONE = 11,
    MONGOC_MD_FLAG_HAVE_WEAK_SYMBOLS = 12,
-   MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS = 13,
-   MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL = 14,
+   MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS_UNUSED = 13, // Removed in CDRIVER-1330.
+   MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL_UNUSED = 14,  // Removed in CDRIVER-5693.
    MONGOC_MD_FLAG_ENABLE_SASL_CYRUS = 15,
    MONGOC_MD_FLAG_ENABLE_SASL_SSPI = 16,
    MONGOC_MD_FLAG_HAVE_SOCKLEN = 17,
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-handshake.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-handshake.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-handshake.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-handshake.c	2025-06-19 15:42:22.000000000 +0000
@@ -32,13 +32,14 @@
 #include <mongoc/mongoc-client.h>
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-version.h>
 #include <mongoc/mongoc-util-private.h>
 
 #include <common-bson-dsl-private.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 /*
  * Global handshake data instance. Initialized at startup from mongoc_init
@@ -117,18 +118,10 @@ _mongoc_handshake_get_config_hex_string
    _set_bit (bf, byte_count, MONGOC_MD_FLAG_HAVE_SASL_CLIENT_DONE);
 #endif
 
-#ifdef MONGOC_NO_AUTOMATIC_GLOBALS
-   _set_bit (bf, byte_count, MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS);
-#endif
-
 #ifdef MONGOC_EXPERIMENTAL_FEATURES
    _set_bit (bf, byte_count, MONGOC_MD_FLAG_EXPERIMENTAL_FEATURES);
 #endif
 
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-   _set_bit (bf, byte_count, MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL);
-#endif
-
 #ifdef MONGOC_ENABLE_SASL_CYRUS
    _set_bit (bf, byte_count, MONGOC_MD_FLAG_ENABLE_SASL_CYRUS);
 #endif
@@ -313,7 +306,9 @@ _get_os_version (void)
       BSON_ASSERT (req > 0);
       found = true;
    } else {
-      MONGOC_WARNING ("Error with GetVersionEx(): %lu", GetLastError ());
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_WARNING ("Error with GetVersionEx(): %s", msg);
+      bson_free (msg);
    }
 
 #elif defined(_POSIX_VERSION)
@@ -434,7 +429,7 @@ _get_env_info (mongoc_handshake_t *hands
       char *endptr;
       int64_t env_memory_mb = bson_ascii_strtoll (memory_str, &endptr, 10);
       bool parse_ok = endptr == memory_str + (strlen (memory_str));
-      bool in_range = mcommon_in_range_int32_t_signed (env_memory_mb);
+      bool in_range = mlib_in_range (int32_t, env_memory_mb);
 
       if (parse_ok && in_range) {
          handshake->env_memory_mb.set = true;
@@ -445,7 +440,7 @@ _get_env_info (mongoc_handshake_t *hands
       char *endptr;
       int64_t env_timeout_sec = bson_ascii_strtoll (timeout_str, &endptr, 10);
       bool parse_ok = endptr == timeout_str + (strlen (timeout_str));
-      bool in_range = mcommon_in_range_int32_t_signed (env_timeout_sec);
+      bool in_range = mlib_in_range (int32_t, env_timeout_sec);
 
       if (parse_ok && in_range) {
          handshake->env_timeout_sec.set = true;
@@ -748,7 +743,7 @@ _append_and_truncate (char **s, const ch
    }
 
    const size_t space_for_suffix = max_len - required_space;
-   BSON_ASSERT (mcommon_in_range_unsigned (int, space_for_suffix));
+   BSON_ASSERT (mlib_in_range (int, space_for_suffix));
 
    *s = bson_strdup_printf ("%s / %.*s", prefix, (int) space_for_suffix, suffix);
    BSON_ASSERT (strlen (*s) <= max_len);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-host-list.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-host-list.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-host-list.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-host-list.c	2025-06-19 15:42:22.000000000 +0000
@@ -17,10 +17,11 @@
 #include <inttypes.h> // PRIu16
 
 #include <mongoc/mongoc-host-list-private.h>
+#include <mongoc/mongoc-error-private.h>
 /* strcasecmp on windows */
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/utlist.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 static mongoc_host_list_t *
 _mongoc_host_list_find_host_and_port (mongoc_host_list_t *hosts, const char *host_and_port)
@@ -197,26 +198,26 @@ _mongoc_host_list_from_string_with_err (
       /* if present, the port should immediately follow after ] */
       sport = strchr (close_bracket, ':');
       if (sport > close_bracket + 1) {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "If present, port should immediately follow the \"]\""
-                         "in an IPv6 address");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "If present, port should immediately follow the \"]\""
+                            "in an IPv6 address");
          return false;
       }
 
       /* otherwise ] should be the last char. */
       if (!sport && *(close_bracket + 1) != '\0') {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "If port is not supplied, \"[\" should be the last"
-                         "character");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "If port is not supplied, \"[\" should be the last"
+                            "character");
          return false;
       }
 
       if (*address != '[') {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Missing matching bracket \"[\"");
          return false;
       }
@@ -232,15 +233,15 @@ _mongoc_host_list_from_string_with_err (
    if (sport) {
       if (sport == address) {
          /* bad address like ":27017" */
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Bad address, \":\" should not be first character");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Bad address, \":\" should not be first character");
          return false;
       }
 
       if (!mongoc_parse_port (&port, sport + 1)) {
-         bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Port could not be parsed");
+         _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Port could not be parsed");
          return false;
       }
 
@@ -282,16 +283,16 @@ _mongoc_host_list_from_hostport_with_err
    };
 
    if (host_len == 0) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Empty hostname in URI");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Empty hostname in URI");
       return false;
    }
 
    if (host_len > BSON_HOST_NAME_MAX) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_NAME_RESOLUTION,
-                      "Hostname provided in URI is too long, max is %d chars",
-                      BSON_HOST_NAME_MAX);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_NAME_RESOLUTION,
+                         "Hostname provided in URI is too long, max is %d chars",
+                         BSON_HOST_NAME_MAX);
       return false;
    }
 
@@ -304,18 +305,18 @@ _mongoc_host_list_from_hostport_with_err
       // Check that IPv6 literal is two less than the max to account for `[` and
       // `]` added below.
       if (host_len > BSON_HOST_NAME_MAX - 2) {
-         bson_set_error (error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_NAME_RESOLUTION,
-                         "IPv6 literal provided in URI is too long, max is %d chars",
-                         BSON_HOST_NAME_MAX - 2);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_NAME_RESOLUTION,
+                            "IPv6 literal provided in URI is too long, max is %d chars",
+                            BSON_HOST_NAME_MAX - 2);
          return false;
       }
 
       mongoc_lowercase (link_->host, link_->host);
       int req =
          bson_snprintf (link_->host_and_port, sizeof link_->host_and_port, "[%s]:%" PRIu16, link_->host, link_->port);
-      BSON_ASSERT (mcommon_in_range_size_t_signed (req));
+      BSON_ASSERT (mlib_in_range (size_t, req));
       // Use `<`, not `<=` to account for NULL byte.
       BSON_ASSERT ((size_t) req < sizeof link_->host_and_port);
    } else if (strchr (host, '/') && strstr (host, ".sock")) {
@@ -328,7 +329,7 @@ _mongoc_host_list_from_hostport_with_err
       mongoc_lowercase (link_->host, link_->host);
       int req =
          bson_snprintf (link_->host_and_port, sizeof link_->host_and_port, "%s:%" PRIu16, link_->host, link_->port);
-      BSON_ASSERT (mcommon_in_range_size_t_signed (req));
+      BSON_ASSERT (mlib_in_range (size_t, req));
       // Use `<`, not `<=` to account for NULL byte.
       BSON_ASSERT ((size_t) req < sizeof link_->host_and_port);
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-http.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-http.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-http.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-http.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,12 +18,13 @@
 
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-host-list-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-stream-tls.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-buffer-private.h>
 #include <mongoc/mcd-time.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 void
 _mongoc_http_request_init (mongoc_http_request_t *request)
@@ -90,7 +91,7 @@ static int32_t
 _mongoc_http_msec_remaining (mcd_timer timer)
 {
    const int64_t msec = mcd_get_milliseconds (mcd_timer_remaining (timer));
-   BSON_ASSERT (mcommon_in_range_signed (int32_t, msec));
+   BSON_ASSERT (mlib_in_range (int32_t, msec));
    return (int32_t) msec;
 }
 
@@ -130,17 +131,17 @@ _mongoc_http_send (const mongoc_http_req
       &host_list,
       error);
    if (!stream) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to connect to: %s", req->host);
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to connect to: %s", req->host);
       goto fail;
    }
 
 #ifndef MONGOC_ENABLE_SSL
    if (use_tls) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Failed to connect to %s: libmongoc not built with TLS support",
-                      req->host);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Failed to connect to %s: libmongoc not built with TLS support",
+                         req->host);
       goto fail;
    }
 #else
@@ -150,7 +151,7 @@ _mongoc_http_send (const mongoc_http_req
       BSON_ASSERT (ssl_opts);
       tls_stream = mongoc_stream_tls_new_with_hostname (stream, req->host, ssl_opts, true);
       if (!tls_stream) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed create TLS stream to: %s", req->host);
          goto fail;
       }
@@ -198,18 +199,19 @@ _mongoc_http_send (const mongoc_http_req
          break;
       }
       if (http_response_buf.len > 1024 * 1024 * 8) {
-         bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "HTTP response message is too large");
+         _mongoc_set_error (
+            error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "HTTP response message is too large");
          goto fail;
       }
    }
 
    if (mongoc_stream_timed_out (stream)) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout reading from stream");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout reading from stream");
       goto fail;
    }
 
    if (http_response_buf.len == 0) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "No response received");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "No response received");
       goto fail;
    }
 
@@ -225,12 +227,12 @@ _mongoc_http_send (const mongoc_http_req
    }
 
    if (!ptr) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "No HTTP version leader in HTTP response. Expected '%s' or '%s'",
-                      proto_leader_10,
-                      proto_leader_11);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "No HTTP version leader in HTTP response. Expected '%s' or '%s'",
+                         proto_leader_10,
+                         proto_leader_11);
       goto fail;
    }
 
@@ -238,7 +240,7 @@ _mongoc_http_send (const mongoc_http_req
    ptr += strlen (proto_leader_10);
    ssize_t remain = resp_end_ptr - ptr;
    if (remain < 4) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Short read in HTTP response");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Short read in HTTP response");
       goto fail;
    }
 
@@ -247,30 +249,30 @@ _mongoc_http_send (const mongoc_http_req
    char *status_endptr;
    res->status = strtol (status_buf, &status_endptr, 10);
    if (status_endptr != status_buf + 3) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Invalid HTTP response status string %*.s",
-                      4,
-                      status_buf);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Invalid HTTP response status string %*.s",
+                         4,
+                         status_buf);
       goto fail;
    }
 
    /* Find the end of the headers. */
    ptr = strstr (http_response_str, header_delimiter);
    if (NULL == ptr) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Error occurred reading response: end of headers not found");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Error occurred reading response: end of headers not found");
       goto fail;
    }
 
    const size_t headers_len = (size_t) (ptr - http_response_str);
-   BSON_ASSERT (mcommon_in_range_unsigned (int, headers_len));
+   BSON_ASSERT (mlib_in_range (int, headers_len));
 
    const size_t body_len = http_response_buf.len - headers_len - strlen (header_delimiter);
-   BSON_ASSERT (mcommon_in_range_unsigned (int, body_len));
+   BSON_ASSERT (mlib_in_range (int, body_len));
 
    res->headers_len = (int) headers_len;
    res->headers = bson_strndup (http_response_str, (size_t) headers_len);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-index.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-index.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-index.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-index.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,100 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <mongoc/mongoc-index.h>
-#include <mongoc/mongoc-trace-private.h>
-
-
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "gridfs_index"
-
-
-static mongoc_index_opt_t gMongocIndexOptDefault = {
-   1,     /* is_initialized */
-   0,     /* background */
-   0,     /* unique */
-   NULL,  /* name */
-   0,     /* drop_dups */
-   0,     /* sparse  */
-   -1,    /* expire_after_seconds */
-   -1,    /* v */
-   NULL,  /* weights */
-   NULL,  /* default_language */
-   NULL,  /* language_override */
-   NULL,  /* mongoc_index_opt_geo_t geo_options */
-   NULL,  /* mongoc_index_opt_storage_t storage_options */
-   NULL,  /* partial_filter_expression */
-   NULL,  /* collation */
-   {NULL} /* struct padding */
-};
-
-static mongoc_index_opt_geo_t gMongocIndexOptGeoDefault = {
-   26,    /* twod_sphere_version */
-   -90,   /* twod_bits_precision */
-   90,    /* twod_location_min */
-   -1,    /* twod_location_max */
-   2,     /* haystack_bucket_size */
-   {NULL} /* struct padding */
-};
-
-static mongoc_index_opt_wt_t gMongocIndexOptWTDefault = {
-   {MONGOC_INDEX_STORAGE_OPT_WIREDTIGER}, /* mongoc_index_opt_storage_t */
-   "",                                    /* config_str */
-   {NULL}                                 /* struct padding */
-};
-
-const mongoc_index_opt_t *
-mongoc_index_opt_get_default (void)
-{
-   return &gMongocIndexOptDefault;
-}
-
-const mongoc_index_opt_geo_t *
-mongoc_index_opt_geo_get_default (void)
-{
-   return &gMongocIndexOptGeoDefault;
-}
-
-const mongoc_index_opt_wt_t *
-mongoc_index_opt_wt_get_default (void)
-{
-   return &gMongocIndexOptWTDefault;
-}
-
-void
-mongoc_index_opt_init (mongoc_index_opt_t *opt)
-{
-   BSON_ASSERT (opt);
-
-   memcpy (opt, &gMongocIndexOptDefault, sizeof *opt);
-}
-
-void
-mongoc_index_opt_geo_init (mongoc_index_opt_geo_t *opt)
-{
-   BSON_ASSERT (opt);
-
-   memcpy (opt, &gMongocIndexOptGeoDefault, sizeof *opt);
-}
-
-void
-mongoc_index_opt_wt_init (mongoc_index_opt_wt_t *opt)
-{
-   BSON_ASSERT (opt);
-
-   memcpy (opt, &gMongocIndexOptWTDefault, sizeof *opt);
-}
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-index.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-index.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-index.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-index.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,89 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_INDEX_H
-#define MONGOC_INDEX_H
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-macros.h>
-
-
-BSON_BEGIN_DECLS
-
-typedef struct {
-   uint8_t twod_sphere_version;
-   uint8_t twod_bits_precision;
-   double twod_location_min;
-   double twod_location_max;
-   double haystack_bucket_size;
-   uint8_t *padding[32];
-} mongoc_index_opt_geo_t;
-
-typedef struct {
-   int type;
-} mongoc_index_opt_storage_t;
-
-typedef enum {
-   MONGOC_INDEX_STORAGE_OPT_MMAPV1,
-   MONGOC_INDEX_STORAGE_OPT_WIREDTIGER,
-} mongoc_index_storage_opt_type_t;
-
-typedef struct {
-   mongoc_index_opt_storage_t base;
-   const char *config_str;
-   void *padding[8];
-} mongoc_index_opt_wt_t;
-
-typedef struct {
-   bool is_initialized;
-   bool background;
-   bool unique;
-   const char *name;
-   bool drop_dups;
-   bool sparse;
-   int32_t expire_after_seconds;
-   int32_t v;
-   const bson_t *weights;
-   const char *default_language;
-   const char *language_override;
-   mongoc_index_opt_geo_t *geo_options;
-   mongoc_index_opt_storage_t *storage_options;
-   const bson_t *partial_filter_expression;
-   const bson_t *collation;
-   void *padding[4];
-} mongoc_index_opt_t;
-
-
-MONGOC_EXPORT (const mongoc_index_opt_t *)
-mongoc_index_opt_get_default (void) BSON_GNUC_PURE;
-MONGOC_EXPORT (const mongoc_index_opt_geo_t *)
-mongoc_index_opt_geo_get_default (void) BSON_GNUC_PURE;
-MONGOC_EXPORT (const mongoc_index_opt_wt_t *)
-mongoc_index_opt_wt_get_default (void) BSON_GNUC_PURE;
-MONGOC_EXPORT (void)
-mongoc_index_opt_init (mongoc_index_opt_t *opt);
-MONGOC_EXPORT (void)
-mongoc_index_opt_geo_init (mongoc_index_opt_geo_t *opt);
-MONGOC_EXPORT (void)
-mongoc_index_opt_wt_init (mongoc_index_opt_wt_t *opt);
-
-BSON_END_DECLS
-
-
-#endif /* MONGOC_INDEX_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-init.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-init.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-init.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-init.c	2025-06-19 15:42:22.000000000 +0000
@@ -27,8 +27,6 @@
 
 #ifdef MONGOC_ENABLE_SSL_OPENSSL
 #include <mongoc/mongoc-openssl-private.h>
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-#include <tls.h>
 #endif
 #include <mongoc/mongoc-thread-private.h>
 #include <common-b64-private.h>
@@ -45,14 +43,13 @@
 #include <mongoc/mongoc-ocsp-cache-private.h>
 #endif
 
-#ifndef MONGOC_NO_AUTOMATIC_GLOBALS
-#pragma message("Configure the driver with ENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF.\
- Automatic cleanup is deprecated and will be removed in version 2.0.")
-#endif
+// CDRIVER-2722: Cyrus SASL is deprecated on MacOS.
+#if defined(MONGOC_ENABLE_SASL_CYRUS) && defined(__APPLE__)
+BEGIN_IGNORE_DEPRECATIONS
+#endif // defined(MONGOC_ENABLE_SASL_CYRUS) && defined(__APPLE__)
 
 #ifdef MONGOC_ENABLE_SASL_CYRUS
 #include <sasl/sasl.h>
-#include <mongoc/mongoc-cyrus-private.h> // _mongoc_cyrus_verifyfile_cb
 
 static void *
 mongoc_cyrus_mutex_alloc (void)
@@ -93,16 +90,21 @@ mongoc_cyrus_mutex_free (void *mutex)
 
 #endif /* MONGOC_ENABLE_SASL_CYRUS */
 
+static bool mongoc_init_called;
+bool
+mongoc_get_init_called (void)
+{
+   return mongoc_init_called;
+}
 
 static BSON_ONCE_FUN (_mongoc_do_init)
 {
+   mongoc_init_called = true;
 #ifdef MONGOC_ENABLE_SASL_CYRUS
    int status;
 #endif
 #ifdef MONGOC_ENABLE_SSL_OPENSSL
    _mongoc_openssl_init ();
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-   tls_init ();
 #endif
 
 #ifdef MONGOC_ENABLE_SASL_CYRUS
@@ -111,13 +113,7 @@ static BSON_ONCE_FUN (_mongoc_do_init)
    sasl_set_mutex (
       mongoc_cyrus_mutex_alloc, mongoc_cyrus_mutex_lock, mongoc_cyrus_mutex_unlock, mongoc_cyrus_mutex_free);
 
-   MC_DISABLE_CAST_FUNCTION_TYPE_STRICT_WARNING_BEGIN
-   sasl_callback_t callbacks[] = {// Include callback to disable loading plugins.
-                                  {SASL_CB_VERIFYFILE, SASL_CALLBACK_FN (_mongoc_cyrus_verifyfile_cb), NULL},
-                                  {SASL_CB_LIST_END}};
-   MC_DISABLE_CAST_FUNCTION_TYPE_STRICT_WARNING_END
-
-   status = sasl_client_init (callbacks);
+   status = sasl_client_init (NULL);
    BSON_ASSERT (status == SASL_OK);
 #endif
 
@@ -210,25 +206,7 @@ mongoc_cleanup (void)
    bson_once (&once, _mongoc_do_cleanup);
 }
 
-/*
- * On GCC, just use __attribute__((constructor)) to perform initialization
- * automatically for the application.
- */
-#if defined(__GNUC__) && !defined(MONGOC_NO_AUTOMATIC_GLOBALS)
-static void
-_mongoc_init_ctor (void) __attribute__ ((constructor));
-static void
-_mongoc_init_ctor (void)
-{
-   mongoc_init ();
-}
-
-static void
-_mongoc_init_dtor (void) __attribute__ ((destructor));
-static void
-_mongoc_init_dtor (void)
-{
-   bson_mem_restore_vtable ();
-   mongoc_cleanup ();
-}
-#endif
+// CDRIVER-2722: Cyrus SASL is deprecated on MacOS.
+#if defined(MONGOC_ENABLE_SASL_CYRUS) && defined(__APPLE__)
+BEGIN_IGNORE_DEPRECATIONS
+#endif // defined(MONGOC_ENABLE_SASL_CYRUS) && defined(__APPLE__)
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-libressl-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-libressl-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-libressl-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-libressl-private.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,40 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_LIBRESSL_PRIVATE_H
-#define MONGOC_LIBRESSL_PRIVATE_H
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-ssl.h>
-#include <mongoc/mongoc-stream-tls-libressl-private.h>
-#include <tls.h>
-
-
-BSON_BEGIN_DECLS
-
-
-bool
-mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt);
-bool
-mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt);
-
-BSON_END_DECLS
-
-
-#endif /* MONGOC_LIBRESSL_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-libressl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-libressl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-libressl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-libressl.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,75 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-config.h>
-
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-log.h>
-#include <mongoc/mongoc-trace-private.h>
-#include <mongoc/mongoc-ssl.h>
-#include <mongoc/mongoc-stream-tls.h>
-#include <mongoc/mongoc-stream-tls-private.h>
-#include <mongoc/mongoc-libressl-private.h>
-#include <mongoc/mongoc-stream-tls-libressl-private.h>
-
-#include <tls.h>
-
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "stream-libressl"
-
-
-bool
-mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt)
-{
-   uint8_t *file;
-   size_t file_len;
-
-   if (!opt->pem_file) {
-      return false;
-   }
-
-   file = tls_load_file (opt->pem_file, &file_len, (char *) opt->pem_pwd);
-   if (!file) {
-      MONGOC_ERROR ("Cannot load private key: '%s'", opt->pem_file);
-      return false;
-   }
-
-   if (tls_config_set_keypair_mem (libressl->config, file, file_len, file, file_len) == -1) {
-      MONGOC_ERROR ("%s", tls_config_error (libressl->config));
-      return false;
-   }
-
-   return true;
-}
-
-bool
-mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt)
-{
-   if (opt->ca_file) {
-      tls_config_set_ca_file (libressl->config, opt->ca_file);
-   }
-   if (opt->ca_dir) {
-      tls_config_set_ca_path (libressl->config, opt->ca_dir);
-   }
-
-
-   return true;
-}
-
-#endif
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-log.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-log.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-log.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-log.h	2025-06-19 15:42:22.000000000 +0000
@@ -61,10 +61,10 @@ typedef enum {
  * libmongoc library. This is useful if you would like to show them in a
  * user interface or alternate storage.
  */
-typedef void (*mongoc_log_func_t) (mongoc_log_level_t log_level,
-                                   const char *log_domain,
-                                   const char *message,
-                                   void *user_data);
+typedef void (BSON_CALL *mongoc_log_func_t) (mongoc_log_level_t log_level,
+                                             const char *log_domain,
+                                             const char *message,
+                                             void *user_data);
 
 
 /**
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,126 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_MATCHER_OP_PRIVATE_H
-#define MONGOC_MATCHER_OP_PRIVATE_H
-
-#include <bson/bson.h>
-
-
-BSON_BEGIN_DECLS
-
-
-typedef union _mongoc_matcher_op_t mongoc_matcher_op_t;
-typedef struct _mongoc_matcher_op_base_t mongoc_matcher_op_base_t;
-typedef struct _mongoc_matcher_op_logical_t mongoc_matcher_op_logical_t;
-typedef struct _mongoc_matcher_op_compare_t mongoc_matcher_op_compare_t;
-typedef struct _mongoc_matcher_op_exists_t mongoc_matcher_op_exists_t;
-typedef struct _mongoc_matcher_op_type_t mongoc_matcher_op_type_t;
-typedef struct _mongoc_matcher_op_not_t mongoc_matcher_op_not_t;
-
-
-typedef enum {
-   MONGOC_MATCHER_OPCODE_EQ,
-   MONGOC_MATCHER_OPCODE_GT,
-   MONGOC_MATCHER_OPCODE_GTE,
-   MONGOC_MATCHER_OPCODE_IN,
-   MONGOC_MATCHER_OPCODE_LT,
-   MONGOC_MATCHER_OPCODE_LTE,
-   MONGOC_MATCHER_OPCODE_NE,
-   MONGOC_MATCHER_OPCODE_NIN,
-   MONGOC_MATCHER_OPCODE_OR,
-   MONGOC_MATCHER_OPCODE_AND,
-   MONGOC_MATCHER_OPCODE_NOT,
-   MONGOC_MATCHER_OPCODE_NOR,
-   MONGOC_MATCHER_OPCODE_EXISTS,
-   MONGOC_MATCHER_OPCODE_TYPE,
-} mongoc_matcher_opcode_t;
-
-
-struct _mongoc_matcher_op_base_t {
-   mongoc_matcher_opcode_t opcode;
-};
-
-
-struct _mongoc_matcher_op_logical_t {
-   mongoc_matcher_op_base_t base;
-   mongoc_matcher_op_t *left;
-   mongoc_matcher_op_t *right;
-};
-
-
-struct _mongoc_matcher_op_compare_t {
-   mongoc_matcher_op_base_t base;
-   char *path;
-   bson_iter_t iter;
-};
-
-
-struct _mongoc_matcher_op_exists_t {
-   mongoc_matcher_op_base_t base;
-   char *path;
-   bool exists;
-};
-
-
-struct _mongoc_matcher_op_type_t {
-   mongoc_matcher_op_base_t base;
-   bson_type_t type;
-   char *path;
-};
-
-
-struct _mongoc_matcher_op_not_t {
-   mongoc_matcher_op_base_t base;
-   mongoc_matcher_op_t *child;
-   char *path;
-};
-
-
-union _mongoc_matcher_op_t {
-   mongoc_matcher_op_base_t base;
-   mongoc_matcher_op_logical_t logical;
-   mongoc_matcher_op_compare_t compare;
-   mongoc_matcher_op_exists_t exists;
-   mongoc_matcher_op_type_t type;
-   mongoc_matcher_op_not_t not_;
-};
-
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_logical_new (mongoc_matcher_opcode_t opcode, mongoc_matcher_op_t *left, mongoc_matcher_op_t *right);
-mongoc_matcher_op_t *
-_mongoc_matcher_op_compare_new (mongoc_matcher_opcode_t opcode, const char *path, const bson_iter_t *iter);
-mongoc_matcher_op_t *
-_mongoc_matcher_op_exists_new (const char *path, bool exists);
-mongoc_matcher_op_t *
-_mongoc_matcher_op_type_new (const char *path, bson_type_t type);
-mongoc_matcher_op_t *
-_mongoc_matcher_op_not_new (const char *path, mongoc_matcher_op_t *child);
-bool
-_mongoc_matcher_op_match (mongoc_matcher_op_t *op, const bson_t *bson);
-void
-_mongoc_matcher_op_destroy (mongoc_matcher_op_t *op);
-void
-_mongoc_matcher_op_to_bson (mongoc_matcher_op_t *op, bson_t *bson);
-
-
-BSON_END_DECLS
-
-
-#endif /* MONGOC_MATCHER_OP_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-op.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-op.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-op.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-op.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,1180 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <mongoc/mongoc-log.h>
-#include <mongoc/mongoc-matcher-op-private.h>
-#include <mongoc/mongoc-util-private.h>
-
-#include <inttypes.h>
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_exists_new --
- *
- *       Create a new op for checking {$exists: bool}.
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t that should be freed with
- *       _mongoc_matcher_op_destroy().
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_exists_new (const char *path, /* IN */
-                               bool exists)      /* IN */
-{
-   mongoc_matcher_op_t *op;
-
-   BSON_ASSERT (path);
-
-   op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t);
-   op->exists.base.opcode = MONGOC_MATCHER_OPCODE_EXISTS;
-   op->exists.path = bson_strdup (path);
-   op->exists.exists = exists;
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_type_new --
- *
- *       Create a new op for checking {$type: int}.
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t that should be freed with
- *       _mongoc_matcher_op_destroy().
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_type_new (const char *path, /* IN */
-                             bson_type_t type) /* IN */
-{
-   mongoc_matcher_op_t *op;
-
-   BSON_ASSERT (path);
-   BSON_ASSERT (type);
-
-   op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t);
-   op->type.base.opcode = MONGOC_MATCHER_OPCODE_TYPE;
-   op->type.path = bson_strdup (path);
-   op->type.type = type;
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_logical_new --
- *
- *       Create a new op for checking any of:
- *
- *          {$or: []}
- *          {$nor: []}
- *          {$and: []}
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t that should be freed with
- *       _mongoc_matcher_op_destroy().
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_logical_new (mongoc_matcher_opcode_t opcode, /* IN */
-                                mongoc_matcher_op_t *left,      /* IN */
-                                mongoc_matcher_op_t *right)     /* IN */
-{
-   mongoc_matcher_op_t *op;
-
-   BSON_ASSERT (left);
-   BSON_ASSERT ((opcode >= MONGOC_MATCHER_OPCODE_OR) && (opcode <= MONGOC_MATCHER_OPCODE_NOR));
-
-   op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t);
-   op->logical.base.opcode = opcode;
-   op->logical.left = left;
-   op->logical.right = right;
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_compare_new --
- *
- *       Create a new op for checking any of:
- *
- *          {"abc": "def"}
- *          {$gt: {...}
- *          {$gte: {...}
- *          {$lt: {...}
- *          {$lte: {...}
- *          {$ne: {...}
- *          {$in: [...]}
- *          {$nin: [...]}
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t that should be freed with
- *       _mongoc_matcher_op_destroy().
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_compare_new (mongoc_matcher_opcode_t opcode, /* IN */
-                                const char *path,               /* IN */
-                                const bson_iter_t *iter)        /* IN */
-{
-   mongoc_matcher_op_t *op;
-
-   BSON_ASSERT (path);
-   BSON_ASSERT (iter);
-
-   op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t);
-   op->compare.base.opcode = opcode;
-   op->compare.path = bson_strdup (path);
-   memcpy (&op->compare.iter, iter, sizeof *iter);
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_not_new --
- *
- *       Create a new op for checking {$not: {...}}
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t that should be freed with
- *       _mongoc_matcher_op_destroy().
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_op_t *
-_mongoc_matcher_op_not_new (const char *path,           /* IN */
-                            mongoc_matcher_op_t *child) /* IN */
-{
-   mongoc_matcher_op_t *op;
-
-   BSON_ASSERT (path);
-   BSON_ASSERT (child);
-
-   op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t);
-   op->not_.base.opcode = MONGOC_MATCHER_OPCODE_NOT;
-   op->not_.path = bson_strdup (path);
-   op->not_.child = child;
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_destroy --
- *
- *       Free a mongoc_matcher_op_t structure and all children structures.
- *
- * Returns:
- *       None.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-void
-_mongoc_matcher_op_destroy (mongoc_matcher_op_t *op) /* IN */
-{
-   BSON_ASSERT (op);
-
-   switch (op->base.opcode) {
-   case MONGOC_MATCHER_OPCODE_EQ:
-   case MONGOC_MATCHER_OPCODE_GT:
-   case MONGOC_MATCHER_OPCODE_GTE:
-   case MONGOC_MATCHER_OPCODE_IN:
-   case MONGOC_MATCHER_OPCODE_LT:
-   case MONGOC_MATCHER_OPCODE_LTE:
-   case MONGOC_MATCHER_OPCODE_NE:
-   case MONGOC_MATCHER_OPCODE_NIN:
-      bson_free (op->compare.path);
-      break;
-   case MONGOC_MATCHER_OPCODE_OR:
-   case MONGOC_MATCHER_OPCODE_AND:
-   case MONGOC_MATCHER_OPCODE_NOR:
-      if (op->logical.left)
-         _mongoc_matcher_op_destroy (op->logical.left);
-      if (op->logical.right)
-         _mongoc_matcher_op_destroy (op->logical.right);
-      break;
-   case MONGOC_MATCHER_OPCODE_NOT:
-      _mongoc_matcher_op_destroy (op->not_.child);
-      bson_free (op->not_.path);
-      break;
-   case MONGOC_MATCHER_OPCODE_EXISTS:
-      bson_free (op->exists.path);
-      break;
-   case MONGOC_MATCHER_OPCODE_TYPE:
-      bson_free (op->type.path);
-      break;
-   default:
-      break;
-   }
-
-   bson_free (op);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_exists_match --
- *
- *       Checks to see if @bson matches @exists requirements. The
- *       {$exists: bool} query can be either true or fase so we must
- *       handle false as "not exists".
- *
- * Returns:
- *       true if the field exists and the spec expected it.
- *       true if the field does not exist and the spec expected it to not
- *       exist.
- *       Otherwise, false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_exists_match (mongoc_matcher_op_exists_t *exists, /* IN */
-                                 const bson_t *bson)                 /* IN */
-{
-   bson_iter_t iter;
-   bson_iter_t desc;
-   bool found;
-
-   BSON_ASSERT (exists);
-   BSON_ASSERT (bson);
-
-   found = (bson_iter_init (&iter, bson) && bson_iter_find_descendant (&iter, exists->path, &desc));
-
-   return (found == exists->exists);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_type_match --
- *
- *       Checks if @bson matches the {$type: ...} op.
- *
- * Returns:
- *       true if the requested field was found and the type matched
- *       the requested type.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_type_match (mongoc_matcher_op_type_t *type, /* IN */
-                               const bson_t *bson)             /* IN */
-{
-   bson_iter_t iter;
-   bson_iter_t desc;
-
-   BSON_ASSERT (type);
-   BSON_ASSERT (bson);
-
-   if (bson_iter_init (&iter, bson) && bson_iter_find_descendant (&iter, type->path, &desc)) {
-      return (bson_iter_type (&iter) == type->type);
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_not_match --
- *
- *       Checks if the {$not: ...} expression matches by negating the
- *       child expression.
- *
- * Returns:
- *       true if the child expression returned false.
- *       Otherwise false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_not_match (mongoc_matcher_op_not_t *not_, /* IN */
-                              const bson_t *bson)            /* IN */
-{
-   BSON_ASSERT (not_);
-   BSON_ASSERT (bson);
-
-   return !_mongoc_matcher_op_match (not_->child, bson);
-}
-
-
-#define _TYPE_CODE(l, r) ((((int) (l)) << 8) | ((int) (r)))
-#define _NATIVE_COMPARE(op, t1, t2) (bson_iter##t2 (iter) op bson_iter##t1 (compare_iter))
-#define _EQ_COMPARE(t1, t2) _NATIVE_COMPARE (==, t1, t2)
-#define _NE_COMPARE(t1, t2) _NATIVE_COMPARE (!=, t1, t2)
-#define _GT_COMPARE(t1, t2) _NATIVE_COMPARE (>, t1, t2)
-#define _GTE_COMPARE(t1, t2) _NATIVE_COMPARE (>=, t1, t2)
-#define _LT_COMPARE(t1, t2) _NATIVE_COMPARE (<, t1, t2)
-#define _LTE_COMPARE(t1, t2) _NATIVE_COMPARE (<=, t1, t2)
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_iter_eq_match --
- *
- *       Performs equality match for all types on either left or right
- *       side of the equation.
- *
- *       We try to default to what the compiler would do for comparing
- *       things like integers. Therefore, we just have MACRO'tized
- *       everything so that the compiler sees the native values. (Such
- *       as (double == int64).
- *
- *       The _TYPE_CODE() stuff allows us to shove the type of the left
- *       and the right into a single integer and then do a jump table
- *       with a switch/case for all our supported types.
- *
- *       I imagine a bunch more of these will need to be added, so feel
- *       free to submit patches.
- *
- * Returns:
- *       true if the equality match succeeded.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_iter_eq_match (bson_iter_t *compare_iter, /* IN */
-                               bson_iter_t *iter)         /* IN */
-{
-   int code;
-
-   BSON_ASSERT (compare_iter);
-   BSON_ASSERT (iter);
-
-   code = _TYPE_CODE (bson_iter_type (compare_iter), bson_iter_type (iter));
-
-   switch (code) {
-   /* Double on Left Side */
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_DOUBLE):
-      return _EQ_COMPARE (_double, _double);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_BOOL):
-      return _EQ_COMPARE (_double, _bool);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT32):
-      return _EQ_COMPARE (_double, _int32);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT64):
-      return _EQ_COMPARE (_double, _int64);
-
-   /* UTF8 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_UTF8, BSON_TYPE_UTF8): {
-      uint32_t llen;
-      uint32_t rlen;
-      const char *lstr;
-      const char *rstr;
-
-      lstr = bson_iter_utf8 (compare_iter, &llen);
-      rstr = bson_iter_utf8 (iter, &rlen);
-
-      return ((llen == rlen) && (0 == memcmp (lstr, rstr, llen)));
-   }
-
-   /* Int32 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_DOUBLE):
-      return _EQ_COMPARE (_int32, _double);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_BOOL):
-      return _EQ_COMPARE (_int32, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT32):
-      return _EQ_COMPARE (_int32, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT64):
-      return _EQ_COMPARE (_int32, _int64);
-
-   /* Int64 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_DOUBLE):
-      return _EQ_COMPARE (_int64, _double);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_BOOL):
-      return _EQ_COMPARE (_int64, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT32):
-      return _EQ_COMPARE (_int64, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT64):
-      return _EQ_COMPARE (_int64, _int64);
-
-   /* Null on Left Side */
-   case _TYPE_CODE (BSON_TYPE_NULL, BSON_TYPE_NULL):
-   case _TYPE_CODE (BSON_TYPE_NULL, BSON_TYPE_UNDEFINED):
-      return true;
-
-   case _TYPE_CODE (BSON_TYPE_ARRAY, BSON_TYPE_ARRAY): {
-      bson_iter_t left_array;
-      bson_iter_t right_array;
-      BSON_ASSERT (bson_iter_recurse (compare_iter, &left_array));
-      BSON_ASSERT (bson_iter_recurse (iter, &right_array));
-
-      while (true) {
-         bool left_has_next = bson_iter_next (&left_array);
-         bool right_has_next = bson_iter_next (&right_array);
-
-         if (left_has_next != right_has_next) {
-            /* different lengths */
-            return false;
-         }
-
-         if (!left_has_next) {
-            /* finished */
-            return true;
-         }
-
-         if (!_mongoc_matcher_iter_eq_match (&left_array, &right_array)) {
-            return false;
-         }
-      }
-   }
-
-   case _TYPE_CODE (BSON_TYPE_DOCUMENT, BSON_TYPE_DOCUMENT): {
-      uint32_t llen;
-      uint32_t rlen;
-      const uint8_t *ldoc;
-      const uint8_t *rdoc;
-
-      bson_iter_document (compare_iter, &llen, &ldoc);
-      bson_iter_document (iter, &rlen, &rdoc);
-
-      return ((llen == rlen) && (0 == memcmp (ldoc, rdoc, llen)));
-   }
-
-   default:
-      return false;
-   }
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_eq_match --
- *
- *       Performs equality match for all types on either left or right
- *       side of the equation.
- *
- * Returns:
- *       true if the equality match succeeded.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_eq_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                             bson_iter_t *iter)                    /* IN */
-{
-   BSON_ASSERT (compare);
-   BSON_ASSERT (iter);
-
-   return _mongoc_matcher_iter_eq_match (&compare->iter, iter);
-}
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_gt_match --
- *
- *       Perform {$gt: ...} match using @compare.
- *
- *       In general, we try to default to what the compiler would do
- *       for comparison between different types.
- *
- * Returns:
- *       true if the document field was > the spec value.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_gt_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                             bson_iter_t *iter)                    /* IN */
-{
-   int code;
-   bson_iter_t *compare_iter = &compare->iter;
-
-   BSON_ASSERT (compare);
-   BSON_ASSERT (iter);
-
-   code = _TYPE_CODE (bson_iter_type (compare_iter), bson_iter_type (iter));
-
-   switch (code) {
-   /* Double on Left Side */
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_DOUBLE):
-      return _GT_COMPARE (_double, _double);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_BOOL):
-      return _GT_COMPARE (_double, _bool);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT32):
-      return _GT_COMPARE (_double, _int32);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT64):
-      return _GT_COMPARE (_double, _int64);
-
-   /* Int32 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_DOUBLE):
-      return _GT_COMPARE (_int32, _double);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_BOOL):
-      return _GT_COMPARE (_int32, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT32):
-      return _GT_COMPARE (_int32, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT64):
-      return _GT_COMPARE (_int32, _int64);
-
-   /* Int64 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_DOUBLE):
-      return _GT_COMPARE (_int64, _double);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_BOOL):
-      return _GT_COMPARE (_int64, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT32):
-      return _GT_COMPARE (_int64, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT64):
-      return _GT_COMPARE (_int64, _int64);
-
-   default:
-      MONGOC_WARNING (
-         "Implement for (Type(%d) > Type(%d))", (int) bson_iter_type (compare_iter), (int) bson_iter_type (iter));
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_gte_match --
- *
- *       Perform a match of {"path": {"$gte": value}}.
- *
- * Returns:
- *       true if the spec matches, otherwise false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_gte_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                              bson_iter_t *iter)                    /* IN */
-{
-   bson_iter_t *compare_iter;
-   int code;
-
-   BSON_ASSERT (compare);
-   BSON_ASSERT (iter);
-
-   compare_iter = &compare->iter;
-   code = _TYPE_CODE (bson_iter_type (compare_iter), bson_iter_type (iter));
-
-   switch (code) {
-   /* Double on Left Side */
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_DOUBLE):
-      return _GTE_COMPARE (_double, _double);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_BOOL):
-      return _GTE_COMPARE (_double, _bool);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT32):
-      return _GTE_COMPARE (_double, _int32);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT64):
-      return _GTE_COMPARE (_double, _int64);
-
-   /* Int32 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_DOUBLE):
-      return _GTE_COMPARE (_int32, _double);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_BOOL):
-      return _GTE_COMPARE (_int32, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT32):
-      return _GTE_COMPARE (_int32, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT64):
-      return _GTE_COMPARE (_int32, _int64);
-
-   /* Int64 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_DOUBLE):
-      return _GTE_COMPARE (_int64, _double);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_BOOL):
-      return _GTE_COMPARE (_int64, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT32):
-      return _GTE_COMPARE (_int64, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT64):
-      return _GTE_COMPARE (_int64, _int64);
-
-   default:
-      MONGOC_WARNING (
-         "Implement for (Type(%d) >= Type(%d))", (int) bson_iter_type (compare_iter), (int) bson_iter_type (iter));
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_in_match --
- *
- *       Checks the spec {"path": {"$in": [value1, value2, ...]}}.
- *
- * Returns:
- *       true if the spec matched, otherwise false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_in_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                             bson_iter_t *iter)                    /* IN */
-{
-   mongoc_matcher_op_compare_t op;
-
-   op.base.opcode = MONGOC_MATCHER_OPCODE_EQ;
-   op.path = compare->path;
-
-   if (!BSON_ITER_HOLDS_ARRAY (&compare->iter) || !bson_iter_recurse (&compare->iter, &op.iter)) {
-      return false;
-   }
-
-   while (bson_iter_next (&op.iter)) {
-      if (_mongoc_matcher_op_eq_match (&op, iter)) {
-         return true;
-      }
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_lt_match --
- *
- *       Perform a {"path": "$lt": {value}} match.
- *
- * Returns:
- *       true if the spec matched, otherwise false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_lt_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                             bson_iter_t *iter)                    /* IN */
-{
-   bson_iter_t *compare_iter;
-   int code;
-
-   BSON_ASSERT (compare);
-   BSON_ASSERT (iter);
-
-   compare_iter = &compare->iter;
-   code = _TYPE_CODE (bson_iter_type (compare_iter), bson_iter_type (iter));
-
-   switch (code) {
-   /* Double on Left Side */
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_DOUBLE):
-      return _LT_COMPARE (_double, _double);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_BOOL):
-      return _LT_COMPARE (_double, _bool);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT32):
-      return _LT_COMPARE (_double, _int32);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT64):
-      return _LT_COMPARE (_double, _int64);
-
-   /* Int32 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_DOUBLE):
-      return _LT_COMPARE (_int32, _double);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_BOOL):
-      return _LT_COMPARE (_int32, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT32):
-      return _LT_COMPARE (_int32, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT64):
-      return _LT_COMPARE (_int32, _int64);
-
-   /* Int64 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_DOUBLE):
-      return _LT_COMPARE (_int64, _double);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_BOOL):
-      return _LT_COMPARE (_int64, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT32):
-      return _LT_COMPARE (_int64, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT64):
-      return _LT_COMPARE (_int64, _int64);
-
-   default:
-      MONGOC_WARNING (
-         "Implement for (Type(%d) < Type(%d))", (int) bson_iter_type (compare_iter), (int) bson_iter_type (iter));
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_lte_match --
- *
- *       Perform a {"$path": {"$lte": value}} match.
- *
- * Returns:
- *       true if the spec matched, otherwise false.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_lte_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                              bson_iter_t *iter)                    /* IN */
-{
-   bson_iter_t *compare_iter;
-   int code;
-
-   BSON_ASSERT (compare);
-   BSON_ASSERT (iter);
-
-   compare_iter = &compare->iter;
-   code = _TYPE_CODE (bson_iter_type (compare_iter), bson_iter_type (iter));
-
-   switch (code) {
-   /* Double on Left Side */
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_DOUBLE):
-      return _LTE_COMPARE (_double, _double);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_BOOL):
-      return _LTE_COMPARE (_double, _bool);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT32):
-      return _LTE_COMPARE (_double, _int32);
-   case _TYPE_CODE (BSON_TYPE_DOUBLE, BSON_TYPE_INT64):
-      return _LTE_COMPARE (_double, _int64);
-
-   /* Int32 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_DOUBLE):
-      return _LTE_COMPARE (_int32, _double);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_BOOL):
-      return _LTE_COMPARE (_int32, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT32):
-      return _LTE_COMPARE (_int32, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT32, BSON_TYPE_INT64):
-      return _LTE_COMPARE (_int32, _int64);
-
-   /* Int64 on Left Side */
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_DOUBLE):
-      return _LTE_COMPARE (_int64, _double);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_BOOL):
-      return _LTE_COMPARE (_int64, _bool);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT32):
-      return _LTE_COMPARE (_int64, _int32);
-   case _TYPE_CODE (BSON_TYPE_INT64, BSON_TYPE_INT64):
-      return _LTE_COMPARE (_int64, _int64);
-
-   default:
-      MONGOC_WARNING (
-         "Implement for (Type(%d) <= Type(%d))", (int) bson_iter_type (compare_iter), (int) bson_iter_type (iter));
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_ne_match --
- *
- *       Perform a {"path": {"$ne": value}} match.
- *
- * Returns:
- *       true if the field "path" was not found or the value is not-equal
- *       to value.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_ne_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                             bson_iter_t *iter)                    /* IN */
-{
-   return !_mongoc_matcher_op_eq_match (compare, iter);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_nin_match --
- *
- *       Perform a {"path": {"$nin": value}} match.
- *
- * Returns:
- *       true if value was not found in the array at "path".
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_nin_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                              bson_iter_t *iter)                    /* IN */
-{
-   return !_mongoc_matcher_op_in_match (compare, iter);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_compare_match --
- *
- *       Dispatch function for mongoc_matcher_op_compare_t operations
- *       to perform a match.
- *
- * Returns:
- *       Opcode dependent.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_compare_match (mongoc_matcher_op_compare_t *compare, /* IN */
-                                  const bson_t *bson)                   /* IN */
-{
-   bson_iter_t tmp;
-   bson_iter_t iter;
-
-   BSON_ASSERT (compare);
-   BSON_ASSERT (bson);
-
-   if (strchr (compare->path, '.')) {
-      if (!bson_iter_init (&tmp, bson) || !bson_iter_find_descendant (&tmp, compare->path, &iter)) {
-         return false;
-      }
-   } else if (!bson_iter_init_find (&iter, bson, compare->path)) {
-      return false;
-   }
-
-   switch ((int) compare->base.opcode) {
-   case MONGOC_MATCHER_OPCODE_EQ:
-      return _mongoc_matcher_op_eq_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_GT:
-      return _mongoc_matcher_op_gt_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_GTE:
-      return _mongoc_matcher_op_gte_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_IN:
-      return _mongoc_matcher_op_in_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_LT:
-      return _mongoc_matcher_op_lt_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_LTE:
-      return _mongoc_matcher_op_lte_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_NE:
-      return _mongoc_matcher_op_ne_match (compare, &iter);
-   case MONGOC_MATCHER_OPCODE_NIN:
-      return _mongoc_matcher_op_nin_match (compare, &iter);
-   default:
-      BSON_ASSERT (false);
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_logical_match --
- *
- *       Dispatch function for mongoc_matcher_op_logical_t operations
- *       to perform a match.
- *
- * Returns:
- *       Opcode specific.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-static bool
-_mongoc_matcher_op_logical_match (mongoc_matcher_op_logical_t *logical, /* IN */
-                                  const bson_t *bson)                   /* IN */
-{
-   BSON_ASSERT (logical);
-   BSON_ASSERT (bson);
-
-   switch ((int) logical->base.opcode) {
-   case MONGOC_MATCHER_OPCODE_OR:
-      return (_mongoc_matcher_op_match (logical->left, bson) || _mongoc_matcher_op_match (logical->right, bson));
-   case MONGOC_MATCHER_OPCODE_AND:
-      return (_mongoc_matcher_op_match (logical->left, bson) && _mongoc_matcher_op_match (logical->right, bson));
-   case MONGOC_MATCHER_OPCODE_NOR:
-      return !(_mongoc_matcher_op_match (logical->left, bson) || _mongoc_matcher_op_match (logical->right, bson));
-   default:
-      BSON_ASSERT (false);
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_match --
- *
- *       Dispatch function for all operation types to perform a match.
- *
- * Returns:
- *       Opcode specific.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-_mongoc_matcher_op_match (mongoc_matcher_op_t *op, /* IN */
-                          const bson_t *bson)      /* IN */
-{
-   BSON_ASSERT (op);
-   BSON_ASSERT (bson);
-
-   switch (op->base.opcode) {
-   case MONGOC_MATCHER_OPCODE_EQ:
-   case MONGOC_MATCHER_OPCODE_GT:
-   case MONGOC_MATCHER_OPCODE_GTE:
-   case MONGOC_MATCHER_OPCODE_IN:
-   case MONGOC_MATCHER_OPCODE_LT:
-   case MONGOC_MATCHER_OPCODE_LTE:
-   case MONGOC_MATCHER_OPCODE_NE:
-   case MONGOC_MATCHER_OPCODE_NIN:
-      return _mongoc_matcher_op_compare_match (&op->compare, bson);
-   case MONGOC_MATCHER_OPCODE_OR:
-   case MONGOC_MATCHER_OPCODE_AND:
-   case MONGOC_MATCHER_OPCODE_NOR:
-      return _mongoc_matcher_op_logical_match (&op->logical, bson);
-   case MONGOC_MATCHER_OPCODE_NOT:
-      return _mongoc_matcher_op_not_match (&op->not_, bson);
-   case MONGOC_MATCHER_OPCODE_EXISTS:
-      return _mongoc_matcher_op_exists_match (&op->exists, bson);
-   case MONGOC_MATCHER_OPCODE_TYPE:
-      return _mongoc_matcher_op_type_match (&op->type, bson);
-   default:
-      break;
-   }
-
-   return false;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_op_to_bson --
- *
- *       Convert the optree specified by @op to a bson document similar
- *       to what the query would have been. This is not perfectly the
- *       same, and so should not be used as such.
- *
- * Returns:
- *       None.
- *
- * Side effects:
- *       @bson is appended to, and therefore must be initialized before
- *       calling this function.
- *
- *--------------------------------------------------------------------------
- */
-
-void
-_mongoc_matcher_op_to_bson (mongoc_matcher_op_t *op, /* IN */
-                            bson_t *bson)            /* IN */
-{
-   const char *str;
-   bson_t child;
-   bson_t child2;
-
-   BSON_ASSERT (op);
-   BSON_ASSERT (bson);
-
-   switch (op->base.opcode) {
-   case MONGOC_MATCHER_OPCODE_EQ:
-      (void) bson_append_iter (bson, op->compare.path, -1, &op->compare.iter);
-      break;
-   case MONGOC_MATCHER_OPCODE_GT:
-   case MONGOC_MATCHER_OPCODE_GTE:
-   case MONGOC_MATCHER_OPCODE_IN:
-   case MONGOC_MATCHER_OPCODE_LT:
-   case MONGOC_MATCHER_OPCODE_LTE:
-   case MONGOC_MATCHER_OPCODE_NE:
-   case MONGOC_MATCHER_OPCODE_NIN:
-      switch ((int) op->base.opcode) {
-      case MONGOC_MATCHER_OPCODE_GT:
-         str = "$gt";
-         break;
-      case MONGOC_MATCHER_OPCODE_GTE:
-         str = "$gte";
-         break;
-      case MONGOC_MATCHER_OPCODE_IN:
-         str = "$in";
-         break;
-      case MONGOC_MATCHER_OPCODE_LT:
-         str = "$lt";
-         break;
-      case MONGOC_MATCHER_OPCODE_LTE:
-         str = "$lte";
-         break;
-      case MONGOC_MATCHER_OPCODE_NE:
-         str = "$ne";
-         break;
-      case MONGOC_MATCHER_OPCODE_NIN:
-         str = "$nin";
-         break;
-      default:
-         str = "???";
-         break;
-      }
-      if (bson_append_document_begin (bson, op->compare.path, -1, &child)) {
-         (void) bson_append_iter (&child, str, -1, &op->compare.iter);
-         bson_append_document_end (bson, &child);
-      }
-      break;
-   case MONGOC_MATCHER_OPCODE_OR:
-   case MONGOC_MATCHER_OPCODE_AND:
-   case MONGOC_MATCHER_OPCODE_NOR:
-      if (op->base.opcode == MONGOC_MATCHER_OPCODE_OR) {
-         str = "$or";
-      } else if (op->base.opcode == MONGOC_MATCHER_OPCODE_AND) {
-         str = "$and";
-      } else if (op->base.opcode == MONGOC_MATCHER_OPCODE_NOR) {
-         str = "$nor";
-      } else {
-         BSON_ASSERT (false);
-         str = NULL;
-      }
-      {
-         bson_array_builder_t *bab;
-         bson_append_array_builder_begin (bson, str, -1, &bab);
-         bson_array_builder_append_document_begin (bab, &child2);
-         _mongoc_matcher_op_to_bson (op->logical.left, &child2);
-         bson_array_builder_append_document_end (bab, &child2);
-         if (op->logical.right) {
-            bson_array_builder_append_document_begin (bab, &child2);
-            _mongoc_matcher_op_to_bson (op->logical.right, &child2);
-            bson_array_builder_append_document_end (bab, &child2);
-         }
-         bson_append_array_builder_end (bson, bab);
-      }
-      break;
-   case MONGOC_MATCHER_OPCODE_NOT:
-      bson_append_document_begin (bson, op->not_.path, -1, &child);
-      bson_append_document_begin (&child, "$not", 4, &child2);
-      _mongoc_matcher_op_to_bson (op->not_.child, &child2);
-      bson_append_document_end (&child, &child2);
-      bson_append_document_end (bson, &child);
-      break;
-   case MONGOC_MATCHER_OPCODE_EXISTS:
-      BSON_APPEND_BOOL (bson, "$exists", op->exists.exists);
-      break;
-   case MONGOC_MATCHER_OPCODE_TYPE:
-      BSON_APPEND_INT32 (bson, "$type", (int) op->type.type);
-      break;
-   default:
-      BSON_ASSERT (false);
-      break;
-   }
-}
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher-private.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,39 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_MATCHER_PRIVATE_H
-#define MONGOC_MATCHER_PRIVATE_H
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-matcher-op-private.h>
-
-
-BSON_BEGIN_DECLS
-
-
-struct _mongoc_matcher_t {
-   bson_t query;
-   mongoc_matcher_op_t *optree;
-};
-
-
-BSON_END_DECLS
-
-
-#endif /* MONGOC_MATCHER_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,381 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <stdlib.h>
-
-#include <mongoc/mongoc-error.h>
-#include <mongoc/mongoc-matcher.h>
-#include <mongoc/mongoc-matcher-private.h>
-#include <mongoc/mongoc-matcher-op-private.h>
-
-
-static mongoc_matcher_op_t *
-_mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, bson_iter_t *iter, bool is_root, bson_error_t *error);
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_parse_compare --
- *
- *       Parse a compare spec such as $gt or $in.
- *
- *       See the following link for more information.
- *
- *          https://www.mongodb.com/docs/manual/reference/operator/query/
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t if successful; otherwise
- *       NULL and @error is set.
- *
- * Side effects:
- *       @error may be set.
- *
- *--------------------------------------------------------------------------
- */
-
-static mongoc_matcher_op_t *
-_mongoc_matcher_parse_compare (bson_iter_t *iter,   /* IN */
-                               const char *path,    /* IN */
-                               bson_error_t *error) /* OUT */
-{
-   const char *key;
-   mongoc_matcher_op_t *op = NULL, *op_child;
-   bson_iter_t child;
-
-   BSON_ASSERT (iter);
-   BSON_ASSERT (path);
-
-   if (bson_iter_type (iter) == BSON_TYPE_DOCUMENT) {
-      if (!bson_iter_recurse (iter, &child) || !bson_iter_next (&child)) {
-         bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Document contains no operations.");
-         return NULL;
-      }
-
-      key = bson_iter_key (&child);
-
-      if (key[0] != '$') {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_EQ, path, iter);
-      } else if (strcmp (key, "$not") == 0) {
-         if (!(op_child = _mongoc_matcher_parse_compare (&child, path, error))) {
-            return NULL;
-         }
-         op = _mongoc_matcher_op_not_new (path, op_child);
-      } else if (strcmp (key, "$gt") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_GT, path, &child);
-      } else if (strcmp (key, "$gte") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_GTE, path, &child);
-      } else if (strcmp (key, "$in") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_IN, path, &child);
-      } else if (strcmp (key, "$lt") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_LT, path, &child);
-      } else if (strcmp (key, "$lte") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_LTE, path, &child);
-      } else if (strcmp (key, "$ne") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_NE, path, &child);
-      } else if (strcmp (key, "$nin") == 0) {
-         op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_NIN, path, &child);
-      } else if (strcmp (key, "$exists") == 0) {
-         op = _mongoc_matcher_op_exists_new (path, bson_iter_bool (&child));
-      } else if (strcmp (key, "$type") == 0) {
-         op = _mongoc_matcher_op_type_new (path, bson_iter_type (&child));
-      } else {
-         bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid operator \"%s\"", key);
-         return NULL;
-      }
-   } else {
-      op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_EQ, path, iter);
-   }
-
-   BSON_ASSERT (op);
-
-   return op;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_parse --
- *
- *       Parse a query spec observed by the current key of @iter.
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t if successful; otherwise
- *       NULL an @error is set.
- *
- * Side effects:
- *       @error may be set.
- *
- *--------------------------------------------------------------------------
- */
-
-static mongoc_matcher_op_t *
-_mongoc_matcher_parse (bson_iter_t *iter,   /* IN */
-                       bson_error_t *error) /* OUT */
-{
-   bson_iter_t child;
-   const char *key;
-
-   BSON_ASSERT (iter);
-
-   key = bson_iter_key (iter);
-
-   if (*key != '$') {
-      return _mongoc_matcher_parse_compare (iter, key, error);
-   } else {
-      BSON_ASSERT (bson_iter_type (iter) == BSON_TYPE_ARRAY);
-
-      if (!bson_iter_recurse (iter, &child)) {
-         bson_set_error (
-            error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid value for operator \"%s\"", key);
-         return NULL;
-      }
-
-      if (strcmp (key, "$or") == 0) {
-         return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_OR, &child, false, error);
-      } else if (strcmp (key, "$and") == 0) {
-         return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_AND, &child, false, error);
-      } else if (strcmp (key, "$nor") == 0) {
-         return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_NOR, &child, false, error);
-      }
-   }
-
-   bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid operator \"%s\"", key);
-
-   return NULL;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * _mongoc_matcher_parse_logical --
- *
- *       Parse a query spec containing a logical operator such as
- *       $or, $and, $not, and $nor.
- *
- *       See the following link for more information.
- *
- *       https://www.mongodb.com/docs/manual/reference/operator/query/
- *
- * Returns:
- *       A newly allocated mongoc_matcher_op_t if successful; otherwise
- *       NULL and @error is set.
- *
- * Side effects:
- *       @error may be set.
- *
- *--------------------------------------------------------------------------
- */
-
-static mongoc_matcher_op_t *
-_mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, /* IN */
-                               bson_iter_t *iter,              /* IN */
-                               bool is_root,                   /* IN */
-                               bson_error_t *error)            /* OUT */
-{
-   mongoc_matcher_op_t *left;
-   mongoc_matcher_op_t *right;
-   mongoc_matcher_op_t *more;
-   mongoc_matcher_op_t *more_wrap;
-   bson_iter_t child;
-
-   BSON_ASSERT (opcode);
-   BSON_ASSERT (iter);
-   BSON_ASSERT (iter);
-
-   if (!bson_iter_next (iter)) {
-      bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid logical operator.");
-      return NULL;
-   }
-
-   if (is_root) {
-      if (!(left = _mongoc_matcher_parse (iter, error))) {
-         return NULL;
-      }
-   } else {
-      if (!BSON_ITER_HOLDS_DOCUMENT (iter)) {
-         bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Expected document in value.");
-         return NULL;
-      }
-
-      if (!bson_iter_recurse (iter, &child)) {
-         bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON");
-         return NULL;
-      }
-
-      if (!bson_iter_next (&child)) {
-         bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON");
-         return NULL;
-      }
-
-      if (!(left = _mongoc_matcher_parse (&child, error))) {
-         return NULL;
-      }
-   }
-
-   if (!bson_iter_next (iter)) {
-      return left;
-   }
-
-   if (is_root) {
-      if (!(right = _mongoc_matcher_parse (iter, error))) {
-         return NULL;
-      }
-   } else {
-      if (!BSON_ITER_HOLDS_DOCUMENT (iter)) {
-         bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Expected document in value.");
-         return NULL;
-      }
-
-      if (!bson_iter_recurse (iter, &child)) {
-         bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "bson_iter_recurse failed.");
-         return NULL;
-      }
-
-      if (!bson_iter_next (&child)) {
-         bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON");
-         return NULL;
-      }
-
-      if (!(right = _mongoc_matcher_parse (&child, error))) {
-         return NULL;
-      }
-   }
-
-   more = _mongoc_matcher_parse_logical (opcode, iter, is_root, error);
-
-   if (more) {
-      more_wrap = _mongoc_matcher_op_logical_new (opcode, right, more);
-      return _mongoc_matcher_op_logical_new (opcode, left, more_wrap);
-   }
-
-   return _mongoc_matcher_op_logical_new (opcode, left, right);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_matcher_new --
- *
- *       Create a new mongoc_matcher_t using the query specification
- *       provided in @query.
- *
- *       This will build an operation tree that can be applied to arbitrary
- *       bson documents using mongoc_matcher_match().
- *
- * Returns:
- *       A newly allocated mongoc_matcher_t if successful; otherwise NULL
- *       and @error is set.
- *
- *       The mongoc_matcher_t should be freed with
- *       mongoc_matcher_destroy().
- *
- * Side effects:
- *       @error may be set.
- *
- *--------------------------------------------------------------------------
- */
-
-mongoc_matcher_t *
-mongoc_matcher_new (const bson_t *query, /* IN */
-                    bson_error_t *error) /* OUT */
-{
-   mongoc_matcher_op_t *op;
-   mongoc_matcher_t *matcher;
-   bson_iter_t iter;
-
-   BSON_ASSERT (query);
-
-   matcher = BSON_ALIGNED_ALLOC0 (mongoc_matcher_t);
-   bson_copy_to (query, &matcher->query);
-
-   if (!bson_iter_init (&iter, &matcher->query)) {
-      goto failure;
-   }
-
-   if (!(op = _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_AND, &iter, true, error))) {
-      goto failure;
-   }
-
-   matcher->optree = op;
-
-   return matcher;
-
-failure:
-   bson_destroy (&matcher->query);
-   bson_free (matcher);
-   return NULL;
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_matcher_match --
- *
- *       Checks to see if @bson matches the query specified when creating
- *       @matcher.
- *
- * Returns:
- *       TRUE if @bson matched the query, otherwise FALSE.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-bool
-mongoc_matcher_match (const mongoc_matcher_t *matcher, /* IN */
-                      const bson_t *document)          /* IN */
-{
-   BSON_ASSERT (matcher);
-   BSON_ASSERT (matcher->optree);
-   BSON_ASSERT (document);
-
-   return _mongoc_matcher_op_match (matcher->optree, document);
-}
-
-
-/*
- *--------------------------------------------------------------------------
- *
- * mongoc_matcher_destroy --
- *
- *       Release all resources associated with @matcher.
- *
- * Returns:
- *       None.
- *
- * Side effects:
- *       None.
- *
- *--------------------------------------------------------------------------
- */
-
-void
-mongoc_matcher_destroy (mongoc_matcher_t *matcher) /* IN */
-{
-   BSON_ASSERT (matcher);
-
-   _mongoc_matcher_op_destroy (matcher->optree);
-   bson_destroy (&matcher->query);
-   bson_free (matcher);
-}
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-matcher.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-matcher.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,43 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_MATCHER_H
-#define MONGOC_MATCHER_H
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-macros.h>
-
-BSON_BEGIN_DECLS
-
-
-typedef struct _mongoc_matcher_t mongoc_matcher_t;
-
-
-MONGOC_EXPORT (mongoc_matcher_t *)
-mongoc_matcher_new (const bson_t *query, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (bool)
-mongoc_matcher_match (const mongoc_matcher_t *matcher, const bson_t *document) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (void)
-mongoc_matcher_destroy (mongoc_matcher_t *matcher) BSON_GNUC_DEPRECATED;
-
-
-BSON_END_DECLS
-
-
-#endif /* MONGOC_MATCHER_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-openssl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-openssl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-openssl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-openssl.c	2025-06-19 15:42:22.000000000 +0000
@@ -29,6 +29,7 @@
 
 #include <string.h>
 
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-http-private.h>
 #include <mongoc/mongoc-init.h>
 #include <mongoc/mongoc-openssl-private.h>
@@ -38,6 +39,7 @@
 #include <mongoc/mongoc-thread-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-util-private.h>
+#include <mlib/cmp.h>
 
 #ifdef MONGOC_ENABLE_OCSP_OPENSSL
 #include <mongoc/mongoc-ocsp-cache-private.h>
@@ -139,16 +141,9 @@ _mongoc_openssl_import_cert_store (LPWST
                                store_name);                             /* system store name. "My" or "Root" */
 
    if (cert_store == NULL) {
-      LPTSTR msg = NULL;
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
-                     NULL,
-                     GetLastError (),
-                     LANG_NEUTRAL,
-                     (LPTSTR) &msg,
-                     0,
-                     NULL);
-      MONGOC_ERROR ("Can't open CA store: 0x%.8X: '%s'", GetLastError (), msg);
-      LocalFree (msg);
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Can't open CA store: %s", msg);
+      bson_free (msg);
       return false;
    }
 
@@ -343,13 +338,13 @@ _mongoc_openssl_check_peer_hostname (SSL
                case GEN_DNS:
 
                   /* check that we don't have an embedded null byte */
-                  if ((length == bson_strnlen (check, length)) && _mongoc_openssl_hostcheck (check, host)) {
+                  if (mlib_cmp (length, ==, bson_strnlen (check, length)) && _mongoc_openssl_hostcheck (check, host)) {
                      r = 1;
                   }
 
                   break;
                case GEN_IPADD:
-                  if (length == addrlen) {
+                  if (mlib_cmp (length, ==, addrlen)) {
                      if (length == sizeof addr6 && !memcmp (check, &addr6, length)) {
                         r = 1;
                      } else if (length == sizeof addr4 && !memcmp (check, &addr4, length)) {
@@ -390,7 +385,8 @@ _mongoc_openssl_check_peer_hostname (SSL
 
                   if (length >= 0) {
                      /* check for embedded nulls */
-                     if ((length == bson_strnlen (check, length)) && _mongoc_openssl_hostcheck (check, host)) {
+                     if (mlib_cmp (length, ==, bson_strnlen (check, length)) &&
+                         _mongoc_openssl_hostcheck (check, host)) {
                         r = 1;
                      }
 
@@ -724,7 +720,6 @@ _contact_ocsp_responder (OCSP_CERTID *id
 
 #define SOFT_FAIL(...) ((stapled_response) ? MONGOC_ERROR (__VA_ARGS__) : MONGOC_DEBUG (__VA_ARGS__))
 
-#define X509_CHECK_SUCCESS 1
 #define OCSP_VERIFY_SUCCESS 1
 
 int
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-opts-helpers.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-opts-helpers.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-opts-helpers.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-opts-helpers.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,22 +16,23 @@
 
 #include <mongoc/mongoc-opts-helpers-private.h>
 #include <mongoc/mongoc-client-session-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-write-concern-private.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-read-concern-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
-#define BSON_ERR(...)                                                                    \
-   do {                                                                                  \
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, __VA_ARGS__); \
-      return false;                                                                      \
+#define BSON_ERR(...)                                                                       \
+   do {                                                                                     \
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, __VA_ARGS__); \
+      return false;                                                                         \
    } while (0)
 
 
-#define CONVERSION_ERR(...)                                                                        \
-   do {                                                                                            \
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, __VA_ARGS__); \
-      return false;                                                                                \
+#define CONVERSION_ERR(...)                                                                           \
+   do {                                                                                               \
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, __VA_ARGS__); \
+      return false;                                                                                   \
    } while (0)
 
 
@@ -58,7 +59,7 @@ void
 _mongoc_timestamp_append (mongoc_timestamp_t *timestamp, bson_t *bson, char *key)
 {
    const size_t len = strlen (key);
-   BSON_ASSERT (mcommon_in_range_unsigned (int, len));
+   BSON_ASSERT (mlib_in_range (int, len));
    bson_append_timestamp (bson, key, (int) len, timestamp->timestamp, timestamp->increment);
 }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-opts.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-opts.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-opts.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-opts.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,6 +1,6 @@
 #include <mongoc/mongoc-opts-helpers-private.h>
 #include <mongoc/mongoc-opts-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-client-private.h>
 
@@ -38,10 +38,10 @@ _mongoc_insert_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -99,10 +99,10 @@ _mongoc_insert_one_opts_parse (
                &mongoc_insert_one_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -146,10 +146,10 @@ _mongoc_insert_many_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -216,10 +216,10 @@ _mongoc_insert_many_opts_parse (
                &mongoc_insert_many_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -264,10 +264,10 @@ _mongoc_delete_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -343,10 +343,10 @@ _mongoc_delete_one_opts_parse (
                &mongoc_delete_one_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -394,10 +394,10 @@ _mongoc_delete_many_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -473,10 +473,10 @@ _mongoc_delete_many_opts_parse (
                &mongoc_delete_many_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -528,10 +528,10 @@ _mongoc_update_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -643,10 +643,10 @@ _mongoc_update_one_opts_parse (
                &mongoc_update_one_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -699,10 +699,10 @@ _mongoc_update_many_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -805,10 +805,10 @@ _mongoc_update_many_opts_parse (
                &mongoc_update_many_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -860,10 +860,10 @@ _mongoc_replace_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -966,10 +966,10 @@ _mongoc_replace_one_opts_parse (
                &mongoc_replace_one_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -1016,10 +1016,10 @@ _mongoc_bulk_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1072,11 +1072,11 @@ _mongoc_bulk_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1114,10 +1114,10 @@ _mongoc_bulk_insert_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1132,11 +1132,11 @@ _mongoc_bulk_insert_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1175,10 +1175,10 @@ _mongoc_bulk_update_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1247,11 +1247,11 @@ _mongoc_bulk_update_one_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1293,10 +1293,10 @@ _mongoc_bulk_update_many_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1356,11 +1356,11 @@ _mongoc_bulk_update_many_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1401,10 +1401,10 @@ _mongoc_bulk_replace_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1464,11 +1464,11 @@ _mongoc_bulk_replace_one_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1506,10 +1506,10 @@ _mongoc_bulk_remove_one_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1542,11 +1542,11 @@ _mongoc_bulk_remove_one_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1583,10 +1583,10 @@ _mongoc_bulk_remove_many_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1619,11 +1619,11 @@ _mongoc_bulk_remove_many_opts_parse (
          }
       }
       else {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid option '%s'",
-                         bson_iter_key (&iter));
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid option '%s'",
+                            bson_iter_key (&iter));
          return false;
       }
    }
@@ -1650,7 +1650,7 @@ _mongoc_change_stream_opts_parse (
 
    BSON_ASSERT (client || true); // client may be NULL.
 
-   mongoc_change_stream_opts->batchSize = 0;
+   mongoc_change_stream_opts->batchSize = -1;
    bson_init (&mongoc_change_stream_opts->resumeAfter);
    bson_init (&mongoc_change_stream_opts->startAfter);
    memset (&mongoc_change_stream_opts->startAtOperationTime, 0, sizeof (mongoc_timestamp_t));
@@ -1666,10 +1666,10 @@ _mongoc_change_stream_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1761,10 +1761,10 @@ _mongoc_change_stream_opts_parse (
                &mongoc_change_stream_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -1803,10 +1803,10 @@ _mongoc_create_index_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1837,10 +1837,10 @@ _mongoc_create_index_opts_parse (
                &mongoc_create_index_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -1882,10 +1882,10 @@ _mongoc_read_write_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -1943,10 +1943,10 @@ _mongoc_read_write_opts_parse (
                &mongoc_read_write_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -1989,10 +1989,10 @@ _mongoc_gridfs_bucket_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -2041,10 +2041,10 @@ _mongoc_gridfs_bucket_opts_parse (
                &mongoc_gridfs_bucket_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -2083,10 +2083,10 @@ _mongoc_gridfs_bucket_upload_opts_parse
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -2115,10 +2115,10 @@ _mongoc_gridfs_bucket_upload_opts_parse
                &mongoc_gridfs_bucket_upload_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -2164,10 +2164,10 @@ _mongoc_aggregate_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -2272,10 +2272,10 @@ _mongoc_aggregate_opts_parse (
                &mongoc_aggregate_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -2322,10 +2322,10 @@ _mongoc_find_and_modify_appended_opts_pa
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -2383,10 +2383,10 @@ _mongoc_find_and_modify_appended_opts_pa
                &mongoc_find_and_modify_appended_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
@@ -2433,10 +2433,10 @@ _mongoc_count_document_opts_parse (
    }
 
    if (!bson_iter_init (&iter, opts)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_BSON,
-                      MONGOC_ERROR_BSON_INVALID,
-                      "Invalid 'opts' parameter.");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_BSON,
+                         MONGOC_ERROR_BSON_INVALID,
+                         "Invalid 'opts' parameter.");
       return false;
    }
 
@@ -2519,10 +2519,10 @@ _mongoc_count_document_opts_parse (
                &mongoc_count_document_opts->extra,
                bson_iter_key (&iter),
                bson_iter_value (&iter))) {
-            bson_set_error (error,
-                            MONGOC_ERROR_BSON,
-                            MONGOC_ERROR_BSON_INVALID,
-                            "Invalid 'opts' parameter.");
+            _mongoc_set_error (error,
+                               MONGOC_ERROR_BSON,
+                               MONGOC_ERROR_BSON_INVALID,
+                               "Invalid 'opts' parameter.");
             return false;
          }
       }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-concern.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-concern.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-concern.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-concern.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,7 +15,7 @@
  */
 
 
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-read-concern.h>
 #include <mongoc/mongoc-read-concern-private.h>
@@ -206,7 +206,7 @@ _mongoc_read_concern_new_from_iter (cons
    return read_concern;
 
 fail:
-   bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid readConcern");
+   _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid readConcern");
 
    mongoc_read_concern_destroy (read_concern);
    return NULL;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-prefs.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-prefs.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-prefs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-prefs.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,10 +15,11 @@
  */
 
 
-#include <mongoc/mongoc-error.h>
+#include <mlib/config.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-read-prefs-private.h>
 #include <mongoc/mongoc-trace-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 mongoc_read_prefs_t *
@@ -88,7 +89,7 @@ mongoc_read_prefs_add_tag (mongoc_read_p
    key = bson_count_keys (&read_prefs->tags);
    // Expect no truncation.
    int req = bson_snprintf (str, sizeof str, "%d", key);
-   BSON_ASSERT (mcommon_cmp_less_su (req, sizeof str));
+   BSON_ASSERT (mlib_cmp (req, <, sizeof str));
 
    if (tag) {
       bson_append_document (&read_prefs->tags, str, -1, tag);
@@ -234,7 +235,10 @@ _apply_read_preferences_mongos (const mo
       max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (read_prefs);
 
       tags = mongoc_read_prefs_get_tags (read_prefs);
+      mlib_diagnostic_push ();
+      mlib_disable_deprecation_warnings ();
       hedge = mongoc_read_prefs_get_hedge (read_prefs);
+      mlib_diagnostic_pop ();
    }
 
    /* Server Selection Spec says:
@@ -308,7 +312,11 @@ mongoc_read_prefs_append_contents_to_bso
    if (read_prefs) {
       // Other content is only available for non-NULL read_prefs
       int64_t max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (read_prefs);
+
+      mlib_diagnostic_push ();
+      mlib_disable_deprecation_warnings ();
       const bson_t *hedge = mongoc_read_prefs_get_hedge (read_prefs);
+      mlib_diagnostic_pop ();
       const bson_t *tags = mongoc_read_prefs_get_tags (read_prefs);
 
       if ((flags & MONGOC_READ_PREFS_CONTENT_FLAG_TAGS) && !bson_empty (tags) &&
@@ -434,7 +442,7 @@ bool
 _mongoc_read_prefs_validate (const mongoc_read_prefs_t *read_prefs, bson_error_t *error)
 {
    if (read_prefs && !mongoc_read_prefs_is_valid (read_prefs)) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid mongoc_read_prefs_t");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid mongoc_read_prefs_t");
       return false;
    }
    return true;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-prefs.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-prefs.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-read-prefs.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-read-prefs.h	2025-06-19 15:42:22.000000000 +0000
@@ -49,28 +49,40 @@ typedef enum {
 
 MONGOC_EXPORT (mongoc_read_prefs_t *)
 mongoc_read_prefs_new (mongoc_read_mode_t read_mode) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_read_prefs_t *)
 mongoc_read_prefs_copy (const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_read_prefs_destroy (mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (mongoc_read_mode_t)
 mongoc_read_prefs_get_mode (const mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (void)
 mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs, mongoc_read_mode_t mode);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_read_prefs_get_tags (const mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (void)
 mongoc_read_prefs_set_tags (mongoc_read_prefs_t *read_prefs, const bson_t *tags);
+
 MONGOC_EXPORT (void)
 mongoc_read_prefs_add_tag (mongoc_read_prefs_t *read_prefs, const bson_t *tag);
+
 MONGOC_EXPORT (int64_t)
 mongoc_read_prefs_get_max_staleness_seconds (const mongoc_read_prefs_t *read_prefs);
+
 MONGOC_EXPORT (void)
 mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs, int64_t max_staleness_seconds);
-MONGOC_EXPORT (const bson_t *)
-mongoc_read_prefs_get_hedge (const mongoc_read_prefs_t *read_prefs);
-MONGOC_EXPORT (void)
-mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, const bson_t *hedge);
+
+BSON_DEPRECATED ("Hedged reads are deprecated in MongoDB 8.0 and will be removed in a future release")
+MONGOC_EXPORT (const bson_t *) mongoc_read_prefs_get_hedge (const mongoc_read_prefs_t *read_prefs);
+
+BSON_DEPRECATED ("Hedged reads are deprecated in MongoDB 8.0 and will be removed in a future release")
+MONGOC_EXPORT (void) mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, const bson_t *hedge);
+
 MONGOC_EXPORT (bool)
 mongoc_read_prefs_is_valid (const mongoc_read_prefs_t *read_prefs);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-rpc.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-rpc.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-rpc.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-rpc.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,6 +18,7 @@
 #include <mongoc/mongoc-rpc-private.h>
 
 #include <mongoc/mongoc-counters-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-trace-private.h>
 
 
@@ -126,6 +127,30 @@ _parse_error_reply (const bson_t *doc, b
 }
 
 
+static void
+_mongoc_cmd_set_error (bson_error_t *error, int32_t error_api_version, uint32_t code, const char *msg)
+{
+   BSON_OPTIONAL_PARAM (error);
+   BSON_ASSERT_PARAM (msg);
+
+   uint8_t category = MONGOC_ERROR_CATEGORY_SERVER;
+
+   if (code == MONGOC_ERROR_PROTOCOL_ERROR) {
+      // Map protocolError to commandNotFound for backward compatibility (DRIVERS-192).
+      code = MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND;
+   } else if (code == 0) {
+      // Reply was "not OK" but no error code was provided. Use our own error code.
+      code = MONGOC_ERROR_QUERY_FAILURE;
+      category = MONGOC_ERROR_CATEGORY;
+   }
+
+   const mongoc_error_domain_t domain =
+      error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY;
+
+   _mongoc_set_error_with_category (error, category, domain, code, "%s", msg);
+}
+
+
 /*
  *--------------------------------------------------------------------------
  *
@@ -147,32 +172,27 @@ _parse_error_reply (const bson_t *doc, b
 bool
 _mongoc_cmd_check_ok (const bson_t *doc, int32_t error_api_version, bson_error_t *error)
 {
-   mongoc_error_domain_t domain =
-      error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY;
-   uint32_t code;
-   bson_iter_t iter;
-   const char *msg = "Unknown command error";
-
    ENTRY;
 
    BSON_ASSERT (doc);
 
-   if (bson_iter_init_find (&iter, doc, "ok") && bson_iter_as_bool (&iter)) {
-      /* no error */
-      RETURN (true);
+   {
+      bson_iter_t iter;
+
+      if (bson_iter_init_find (&iter, doc, "ok") && bson_iter_as_bool (&iter)) {
+         /* no error */
+         RETURN (true);
+      }
    }
 
+   uint32_t code;
+   const char *msg = "Unknown command error";
+
    if (!_parse_error_reply (doc, false /* check_wce */, &code, &msg)) {
       RETURN (true);
    }
 
-   if (code == MONGOC_ERROR_PROTOCOL_ERROR || code == 13390) {
-      code = MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND;
-   } else if (code == 0) {
-      code = MONGOC_ERROR_QUERY_FAILURE;
-   }
-
-   bson_set_error (error, domain, code, "%s", msg);
+   _mongoc_cmd_set_error (error, error_api_version, code, msg);
 
    /* there was a command error */
    RETURN (false);
@@ -200,26 +220,18 @@ _mongoc_cmd_check_ok (const bson_t *doc,
 bool
 _mongoc_cmd_check_ok_no_wce (const bson_t *doc, int32_t error_api_version, bson_error_t *error)
 {
-   mongoc_error_domain_t domain =
-      error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY;
-   uint32_t code;
-   const char *msg = "Unknown command error";
-
    ENTRY;
 
    BSON_ASSERT (doc);
 
+   uint32_t code;
+   const char *msg = "Unknown command error";
+
    if (!_parse_error_reply (doc, true /* check_wce */, &code, &msg)) {
       RETURN (true);
    }
 
-   if (code == MONGOC_ERROR_PROTOCOL_ERROR || code == 13390) {
-      code = MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND;
-   } else if (code == 0) {
-      code = MONGOC_ERROR_QUERY_FAILURE;
-   }
-
-   bson_set_error (error, domain, code, "%s", msg);
+   _mongoc_cmd_set_error (error, error_api_version, code, msg);
 
    /* there was a command error */
    RETURN (false);
@@ -230,18 +242,25 @@ _mongoc_cmd_check_ok_no_wce (const bson_
 static void
 _mongoc_populate_query_error (const bson_t *doc, int32_t error_api_version, bson_error_t *error)
 {
-   mongoc_error_domain_t domain =
-      error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY;
-   uint32_t code = MONGOC_ERROR_QUERY_FAILURE;
-   bson_iter_t iter;
-   const char *msg = "Unknown query failure";
-
    ENTRY;
 
    BSON_ASSERT (doc);
 
+   if (!error) {
+      return;
+   }
+
+   bson_iter_t iter;
+
+   const uint32_t domain = error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY;
+
+   uint32_t code = MONGOC_ERROR_QUERY_FAILURE;
+   uint8_t category = MONGOC_ERROR_CATEGORY;
+   const char *msg = "Unknown query failure";
+
    if (bson_iter_init_find (&iter, doc, "code") && BSON_ITER_HOLDS_NUMBER (&iter)) {
       code = (uint32_t) bson_iter_as_int64 (&iter);
+      category = MONGOC_ERROR_CATEGORY_SERVER;
       BSON_ASSERT (code);
    }
 
@@ -249,7 +268,7 @@ _mongoc_populate_query_error (const bson
       msg = bson_iter_utf8 (&iter, NULL);
    }
 
-   bson_set_error (error, domain, code, "%s", msg);
+   _mongoc_set_error_with_category (error, category, domain, code, "%s", msg);
 
    EXIT;
 }
@@ -265,7 +284,7 @@ mcd_rpc_message_check_ok (mcd_rpc_messag
    ENTRY;
 
    if (mcd_rpc_header_get_op_code (rpc) != MONGOC_OP_CODE_REPLY) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Received rpc other than OP_REPLY.");
       RETURN (false);
    }
@@ -285,14 +304,14 @@ mcd_rpc_message_check_ok (mcd_rpc_messag
 
          bson_destroy (&body);
       } else {
-         bson_set_error (error, MONGOC_ERROR_QUERY, MONGOC_ERROR_QUERY_FAILURE, "Unknown query failure.");
+         _mongoc_set_error (error, MONGOC_ERROR_QUERY, MONGOC_ERROR_QUERY_FAILURE, "Unknown query failure.");
       }
 
       RETURN (false);
    }
 
    if (flags & MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "The cursor is invalid or has expired.");
 
       RETURN (false);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sasl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sasl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sasl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sasl.c	2025-06-19 15:42:22.000000000 +0000
@@ -110,9 +110,18 @@ _mongoc_sasl_set_properties (mongoc_sasl
       canonicalize = bson_iter_bool (&iter);
    }
 
+   /* newer "authMechanismProperties" URI syntax takes precedence */
    if (bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") && BSON_ITER_HOLDS_UTF8 (&iter)) {
-      /* newer "authMechanismProperties" URI syntax takes precedence */
-      canonicalize = !strcasecmp (bson_iter_utf8 (&iter, NULL), "true");
+      const char *const value = bson_iter_utf8 (&iter, NULL);
+
+      const bool is_true = strcasecmp (value, "true") == 0;
+
+      // CDRIVER-4128: only legacy boolean values are currently supported.
+      if (!is_true && strcasecmp (value, "false") != 0) {
+         MONGOC_WARNING ("Unsupported value for \"CANONICALIZE_HOST_NAME\": \"%s\"", value);
+      } else {
+         canonicalize = is_true;
+      }
    }
 
    sasl->canonicalize_host_name = canonicalize;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-scram.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-scram.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-scram.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-scram.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,7 @@
 
 #include <string.h>
 
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-scram-private.h>
 #include <mongoc/mongoc-rand-private.h>
 #include <mongoc/mongoc-util-private.h>
@@ -31,7 +31,8 @@
 #include <mongoc/mongoc-memcmp-private.h>
 #include <common-thread-private.h>
 #include <utf8proc.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/loop.h>
 
 typedef struct _mongoc_scram_cache_entry_t {
    /* book keeping */
@@ -338,7 +339,7 @@ _mongoc_scram_start (
    BSON_ASSERT (outbuflen);
 
    if (!scram->user) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: username is not set");
       goto FAIL;
    }
@@ -354,11 +355,11 @@ _mongoc_scram_start (
 
    /* the server uses a 24 byte random nonce.  so we do as well */
    if (1 != _mongoc_rand_bytes (nonce, sizeof (nonce))) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: could not generate a cryptographically "
-                      "secure nonce in sasl step 1");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: could not generate a cryptographically "
+                         "secure nonce in sasl step 1");
       goto FAIL;
    }
 
@@ -366,7 +367,7 @@ _mongoc_scram_start (
       mcommon_b64_ntop (nonce, sizeof (nonce), scram->encoded_nonce, sizeof (scram->encoded_nonce));
 
    if (-1 == scram->encoded_nonce_len) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not encode nonce");
       goto FAIL;
    }
@@ -426,15 +427,15 @@ _mongoc_scram_start (
    goto CLEANUP;
 
 BUFFER_AUTH:
-   bson_set_error (error,
-                   MONGOC_ERROR_SCRAM,
-                   MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                   "SCRAM Failure: could not buffer auth message in sasl step1");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_SCRAM,
+                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                      "SCRAM Failure: could not buffer auth message in sasl step1");
 
    goto FAIL;
 
 BUFFER:
-   bson_set_error (
+   _mongoc_set_error (
       error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer sasl step1");
 
    goto FAIL;
@@ -602,21 +603,21 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
          current_val_len = &val_i_len;
          break;
       default:
-         bson_set_error (error,
-                         MONGOC_ERROR_SCRAM,
-                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                         "SCRAM Failure: unknown key (%c) in sasl step 2",
-                         *ptr);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_SCRAM,
+                            MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                            "SCRAM Failure: unknown key (%c) in sasl step 2",
+                            *ptr);
          goto FAIL;
       }
 
       ptr++;
 
       if (*ptr != '=') {
-         bson_set_error (error,
-                         MONGOC_ERROR_SCRAM,
-                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                         "SCRAM Failure: invalid parse state in sasl step 2");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_SCRAM,
+                            MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                            "SCRAM Failure: invalid parse state in sasl step 2");
 
          goto FAIL;
       }
@@ -643,33 +644,33 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
    }
 
    if (!val_r) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no r param in sasl step 2");
 
       goto FAIL;
    }
 
    if (!val_s) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no s param in sasl step 2");
 
       goto FAIL;
    }
 
    if (!val_i) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no i param in sasl step 2");
 
       goto FAIL;
    }
 
    /* verify our nonce */
-   if (mcommon_cmp_less_us (val_r_len, scram->encoded_nonce_len) ||
+   if (mlib_cmp (val_r_len, <, scram->encoded_nonce_len) ||
        mongoc_memcmp (val_r, scram->encoded_nonce, scram->encoded_nonce_len)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: client nonce not repeated in sasl step 2");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: client nonce not repeated in sasl step 2");
    }
 
    *outbuflen = 0;
@@ -694,19 +695,19 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
    decoded_salt_len = mcommon_b64_pton ((char *) val_s, decoded_salt, sizeof (decoded_salt));
 
    if (-1 == decoded_salt_len) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: unable to decode salt in sasl step2");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: unable to decode salt in sasl step2");
       goto FAIL;
    }
 
    if (expected_salt_length != decoded_salt_len) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: invalid salt length of %d in sasl step2",
-                      decoded_salt_len);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: invalid salt length of %d in sasl step2",
+                         decoded_salt_len);
       goto FAIL;
    }
 
@@ -715,18 +716,18 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
     * null, we got to the end of the string and didn't have a parse error */
 
    if (*tmp) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: unable to parse iterations in sasl step2");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: unable to parse iterations in sasl step2");
       goto FAIL;
    }
 
    if (iterations < 0) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: iterations is negative in sasl step2");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: iterations is negative in sasl step2");
       goto FAIL;
    }
 
@@ -734,10 +735,10 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
     * the authentication conversation specifies a lower count. This mitigates
     * downgrade attacks by a man-in-the-middle attacker. */
    if (iterations < 4096) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: iterations must be at least 4096");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: iterations must be at least 4096");
       goto FAIL;
    }
 
@@ -760,7 +761,7 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
                                                                  decoded_salt,
                                                                  decoded_salt_len,
                                                                  (uint32_t) iterations)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: failed to salt password");
       goto FAIL;
    }
@@ -770,15 +771,15 @@ _mongoc_scram_step2 (mongoc_scram_t *scr
    goto CLEANUP;
 
 BUFFER_AUTH:
-   bson_set_error (error,
-                   MONGOC_ERROR_SCRAM,
-                   MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                   "SCRAM Failure: could not buffer auth message in sasl step2");
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_SCRAM,
+                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                      "SCRAM Failure: could not buffer auth message in sasl step2");
 
    goto FAIL;
 
 BUFFER:
-   bson_set_error (
+   _mongoc_set_error (
       error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer sasl step2");
 
    goto FAIL;
@@ -808,7 +809,7 @@ _mongoc_scram_verify_server_signature (m
 
    if (!*scram->server_key) {
       const size_t key_len = strlen (MONGOC_SCRAM_SERVER_KEY);
-      BSON_ASSERT (mcommon_in_range_unsigned (int, key_len));
+      BSON_ASSERT (mlib_in_range (int, key_len));
 
       /* ServerKey := HMAC(SaltedPassword, "Server Key") */
       mongoc_crypto_hmac (&scram->crypto,
@@ -833,7 +834,8 @@ _mongoc_scram_verify_server_signature (m
       return false;
    }
 
-   return (len == encoded_server_signature_len) && (mongoc_memcmp (verification, encoded_server_signature, len) == 0);
+   return mlib_cmp (len, ==, encoded_server_signature_len) &&
+          (mongoc_memcmp (verification, encoded_server_signature, len) == 0);
 }
 
 
@@ -872,21 +874,21 @@ _mongoc_scram_step3 (mongoc_scram_t *scr
          current_val_len = &val_v_len;
          break;
       default:
-         bson_set_error (error,
-                         MONGOC_ERROR_SCRAM,
-                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                         "SCRAM Failure: unknown key (%c) in sasl step 3",
-                         *ptr);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_SCRAM,
+                            MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                            "SCRAM Failure: unknown key (%c) in sasl step 3",
+                            *ptr);
          goto FAIL;
       }
 
       ptr++;
 
       if (*ptr != '=') {
-         bson_set_error (error,
-                         MONGOC_ERROR_SCRAM,
-                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                         "SCRAM Failure: invalid parse state in sasl step 3");
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_SCRAM,
+                            MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                            "SCRAM Failure: invalid parse state in sasl step 3");
          goto FAIL;
       }
 
@@ -914,25 +916,25 @@ _mongoc_scram_step3 (mongoc_scram_t *scr
    *outbuflen = 0;
 
    if (val_e) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: authentication failure in sasl step 3 : %s",
-                      val_e);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: authentication failure in sasl step 3 : %s",
+                         val_e);
       goto FAIL;
    }
 
    if (!val_v) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no v param in sasl step 3");
       goto FAIL;
    }
 
    if (!_mongoc_scram_verify_server_signature (scram, val_v, val_v_len)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SCRAM,
-                      MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
-                      "SCRAM Failure: could not verify server signature in sasl step 3");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SCRAM,
+                         MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
+                         "SCRAM Failure: could not verify server signature in sasl step 3");
       goto FAIL;
    }
 
@@ -976,7 +978,8 @@ _mongoc_scram_step (mongoc_scram_t *scra
    case 3:
       return _mongoc_scram_step3 (scram, inbuf, inbuflen, outbuf, outbufmax, outbuflen, error);
    default:
-      bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_NOT_DONE, "SCRAM Failure: maximum steps detected");
+      _mongoc_set_error (
+         error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_NOT_DONE, "SCRAM Failure: maximum steps detected");
       return false;
    }
 }
@@ -1009,10 +1012,10 @@ _mongoc_sasl_prep_impl (const char *name
    ssize_t num_chars;
    uint8_t *out_utf8;
 
-#define SASL_PREP_ERR_RETURN(msg)                                                               \
-   do {                                                                                         \
-      bson_set_error (err, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, (msg), name); \
-      return NULL;                                                                              \
+#define SASL_PREP_ERR_RETURN(msg)                                                                  \
+   do {                                                                                            \
+      _mongoc_set_error (err, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, (msg), name); \
+      return NULL;                                                                                 \
    } while (0)
 
    /* 1. convert str to Unicode codepoints. */
@@ -1023,11 +1026,11 @@ _mongoc_sasl_prep_impl (const char *name
    }
 
    /* convert to unicode. */
-   BSON_ASSERT (mcommon_cmp_less_equal_su (num_chars, SIZE_MAX / sizeof (uint32_t) - 1u));
+   BSON_ASSERT (mlib_cmp (num_chars, <=, SIZE_MAX / sizeof (uint32_t) - 1));
    utf8_codepoints = bson_malloc (sizeof (uint32_t) * ((size_t) num_chars + 1u)); /* add one for trailing 0 value. */
    const char *c = in_utf8;
 
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       const size_t utf8_char_length = _mongoc_utf8_char_length (c);
       utf8_codepoints[i] = _mongoc_utf8_get_first_code_point (c, utf8_char_length);
 
@@ -1046,7 +1049,7 @@ _mongoc_sasl_prep_impl (const char *name
    // pointers: one for reading the original characters (i) and one for writing
    // the new characters (curr). i will always be >= curr.
    size_t curr = 0;
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       if (_mongoc_utf8_code_point_is_in_table (utf8_codepoints[i],
                                                non_ascii_space_character_ranges,
                                                sizeof (non_ascii_space_character_ranges) / sizeof (uint32_t)))
@@ -1072,7 +1075,7 @@ _mongoc_sasl_prep_impl (const char *name
 
    // preflight for length
    size_t utf8_pre_norm_len = 0;
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       const ssize_t len = _mongoc_utf8_code_point_length (utf8_codepoints[i]);
       if (len == -1) {
          bson_free (utf8_codepoints);
@@ -1084,7 +1087,7 @@ _mongoc_sasl_prep_impl (const char *name
    char *utf8_pre_norm = (char *) bson_malloc (sizeof (char) * (utf8_pre_norm_len + 1));
 
    char *loc = utf8_pre_norm;
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       const ssize_t utf8_char_length = _mongoc_utf8_code_point_to_str (utf8_codepoints[i], loc);
       if (utf8_char_length == -1) {
          bson_free (utf8_pre_norm);
@@ -1106,7 +1109,7 @@ _mongoc_sasl_prep_impl (const char *name
    // c. Prohibit -- Check for any characters
    // that are not allowed in the output. If any are found, return an error.
 
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       if (_mongoc_utf8_code_point_is_in_table (
              utf8_codepoints[i], prohibited_output_ranges, sizeof (prohibited_output_ranges) / sizeof (uint32_t)) ||
           _mongoc_utf8_code_point_is_in_table (utf8_codepoints[i],
@@ -1136,8 +1139,7 @@ _mongoc_sasl_prep_impl (const char *name
    bool contains_LCat = false;
    bool contains_RandALCar = false;
 
-
-   for (size_t i = 0; i < num_chars; ++i) {
+   mlib_foreach_irange (i, num_chars) {
       if (_mongoc_utf8_code_point_is_in_table (
              utf8_codepoints[i], LCat_bidi_ranges, sizeof (LCat_bidi_ranges) / sizeof (uint32_t))) {
          contains_LCat = true;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -33,10 +33,14 @@
 BSON_BEGIN_DECLS
 
 bool
-mongoc_secure_channel_setup_ca (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt);
+mongoc_secure_channel_setup_ca (mongoc_ssl_opt_t *opt);
 
 bool
-mongoc_secure_channel_setup_crl (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt);
+mongoc_secure_channel_setup_crl (mongoc_ssl_opt_t *opt);
+
+// mongoc_secure_channel_load_crl is used in tests.
+PCCRL_CONTEXT
+mongoc_secure_channel_load_crl (const char *crl_file);
 
 ssize_t
 mongoc_secure_channel_read (mongoc_stream_tls_t *tls, void *data, size_t data_length);
@@ -45,7 +49,7 @@ ssize_t
 mongoc_secure_channel_write (mongoc_stream_tls_t *tls, const void *data, size_t data_length);
 
 PCCERT_CONTEXT
-mongoc_secure_channel_setup_certificate (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt);
+mongoc_secure_channel_setup_certificate (mongoc_ssl_opt_t *opt);
 
 
 /* it may require 16k + some overhead to hold one decryptable block of data - do
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-channel.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-channel.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-channel.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-channel.c	2025-06-19 15:42:22.000000000 +0000
@@ -28,9 +28,9 @@
 #include <mongoc/mongoc-secure-channel-private.h>
 #include <mongoc/mongoc-stream-tls-secure-channel-private.h>
 #include <mongoc/mongoc-errno-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 #undef MONGOC_LOG_DOMAIN
@@ -41,45 +41,201 @@
 #define SECBUFFER_ALERT 17
 #endif
 
+// `decode_pem_base64` decodes a base-64 PEM blob with headers.
+// Returns NULL on error.
+static LPBYTE
+decode_pem_base64 (const char *base64_in, DWORD *out_len, const char *descriptor, const char *filename)
+{
+   BSON_ASSERT_PARAM (base64_in);
+   BSON_ASSERT_PARAM (out_len);
+   BSON_ASSERT_PARAM (descriptor);
+   BSON_ASSERT_PARAM (filename);
+
+   // Get needed output length:
+   if (!CryptStringToBinaryA (base64_in, 0, CRYPT_STRING_BASE64HEADER, NULL, out_len, NULL, NULL)) {
+      MONGOC_ERROR (
+         "Failed to convert base64 %s from '%s'. Error 0x%.8X", descriptor, filename, (unsigned int) GetLastError ());
+      return NULL;
+   }
+
+   if (*out_len == 0) {
+      return NULL;
+   }
+
+   LPBYTE out = (LPBYTE) bson_malloc (*out_len);
+
+   if (!CryptStringToBinaryA (base64_in, 0, CRYPT_STRING_BASE64HEADER, out, out_len, NULL, NULL)) {
+      MONGOC_ERROR (
+         "Failed to convert base64 %s from '%s'. Error 0x%.8X", descriptor, filename, (unsigned int) GetLastError ());
+      bson_free (out);
+      return NULL;
+   }
+   return out;
+}
+
+// `read_file_and_null_terminate` reads a file into a NUL-terminated string.
+// On success: returns a NUL-terminated string and (optionally) sets `*out_len` excluding NUL.
+// On error: returns NULL.
+static char *
+read_file_and_null_terminate (const char *filename, size_t *out_len)
+{
+   BSON_ASSERT_PARAM (filename);
+   BSON_OPTIONAL_PARAM (out_len);
+
+   bool ok = false;
+   char *contents = NULL;
+   char errmsg_buf[BSON_ERROR_BUFFER_SIZE];
+
+   FILE *file = fopen (filename, "rb");
+   if (!file) {
+      MONGOC_ERROR ("Failed to open file: '%s' with error: '%s'",
+                    filename,
+                    bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf));
+      goto fail;
+   }
+
+   if (0 != fseek (file, 0, SEEK_END)) {
+      MONGOC_ERROR ("Failed to seek in file: '%s' with error: '%s'",
+                    filename,
+                    bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf));
+      goto fail;
+   }
+
+   const long file_len = ftell (file);
+   if (file_len < 0) {
+      MONGOC_ERROR ("Failed to get length of file: '%s' with error: '%s'",
+                    filename,
+                    bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf));
+      goto fail;
+   }
+
+   if (file_len > LONG_MAX - 1) {
+      goto fail;
+   }
+
+   if (0 != fseek (file, 0, SEEK_SET)) {
+      goto fail;
+   }
+
+   // Read the whole file into one NUL-terminated string:
+   contents = (char *) bson_malloc ((size_t) file_len + 1u);
+   contents[file_len] = '\0';
+   if ((size_t) file_len != fread (contents, 1, file_len, file)) {
+      SecureZeroMemory (contents, file_len);
+      if (feof (file)) {
+         MONGOC_ERROR ("Unexpected EOF reading file: '%s'", filename);
+         goto fail;
+      } else {
+         MONGOC_ERROR ("Failed to read file: '%s' with error: '%s'",
+                       filename,
+                       bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf));
+         goto fail;
+      }
+   }
+   if (out_len) {
+      *out_len = (size_t) file_len;
+   }
+
+   ok = true;
+fail:
+   if (file) {
+      (void) fclose (file); // Ignore error.
+   }
+   if (!ok) {
+      bson_free (contents);
+      contents = NULL;
+   }
+   return contents;
+}
+
+
+// `decode_object` decodes a cryptographic object from a blob.
+// Returns NULL on error.
+static LPBYTE
+decode_object (const char *structType,
+               const LPBYTE data,
+               DWORD data_len,
+               DWORD *out_len,
+               const char *descriptor,
+               const char *filename)
+{
+   BSON_ASSERT_PARAM (structType);
+   BSON_ASSERT_PARAM (data);
+   BSON_ASSERT_PARAM (structType);
+   BSON_ASSERT_PARAM (out_len);
+   BSON_ASSERT_PARAM (descriptor);
+   BSON_ASSERT_PARAM (filename);
+   // Get needed output length:
+   if (!CryptDecodeObjectEx (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* dwCertEncodingType */
+                             structType,                              /* lpszStructType */
+                             data,                                    /* pbEncoded */
+                             data_len,                                /* cbEncoded */
+                             0,                                       /* dwFlags */
+                             NULL,                                    /* pDecodePara */
+                             NULL,                                    /* pvStructInfo */
+                             out_len                                  /* pcbStructInfo */
+                             )) {
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Failed to decode %s from '%s': %s", descriptor, filename, msg);
+      bson_free (msg);
+      return NULL;
+   }
+
+   if (*out_len == 0) {
+      return NULL;
+   }
+   LPBYTE out = (LPBYTE) bson_malloc (*out_len);
+
+   if (!CryptDecodeObjectEx (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* dwCertEncodingType */
+                             structType,                              /* lpszStructType */
+                             data,                                    /* pbEncoded */
+                             data_len,                                /* cbEncoded */
+                             0,                                       /* dwFlags */
+                             NULL,                                    /* pDecodePara */
+                             out,                                     /* pvStructInfo */
+                             out_len                                  /* pcbStructInfo */
+                             )) {
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Failed to decode %s from '%s': %s", descriptor, filename, msg);
+      bson_free (msg);
+      bson_free (out);
+      return NULL;
+   }
+
+   return out;
+}
 
 PCCERT_CONTEXT
 mongoc_secure_channel_setup_certificate_from_file (const char *filename)
 {
    char *pem;
-   FILE *file;
+   bool ret = false;
    bool success;
-   HCRYPTKEY hKey;
-   long pem_length;
+   size_t pem_length;
    HCRYPTPROV provider;
-   CERT_BLOB public_blob;
+   DWORD encoded_cert_len;
+   LPBYTE encoded_cert = NULL;
    const char *pem_public;
    const char *pem_private;
-   LPBYTE blob_private = NULL;
    PCCERT_CONTEXT cert = NULL;
+   LPBYTE blob_private = NULL;
    DWORD blob_private_len = 0;
-   DWORD encrypted_private_len = 0;
-   LPBYTE encrypted_private = NULL;
-
+   LPBYTE blob_private_rsa = NULL;
+   DWORD blob_private_rsa_len = 0;
+   DWORD encoded_private_len = 0;
+   LPBYTE encoded_private = NULL;
 
-   file = fopen (filename, "rb");
-   if (!file) {
-      MONGOC_ERROR ("Couldn't open file '%s'", filename);
-      return NULL;
+   pem = read_file_and_null_terminate (filename, &pem_length);
+   if (!pem) {
+      goto fail;
    }
 
-   fseek (file, 0, SEEK_END);
-   pem_length = ftell (file);
-   fseek (file, 0, SEEK_SET);
-   if (pem_length < 1) {
-      MONGOC_ERROR ("Couldn't determine file size of '%s'", filename);
-      return NULL;
+   pem_public = strstr (pem, "-----BEGIN CERTIFICATE-----");
+   if (!pem_public) {
+      MONGOC_ERROR ("Can't find public certificate in '%s'", filename);
+      goto fail;
    }
 
-   pem = (char *) bson_malloc0 (pem_length);
-   fread ((void *) pem, 1, pem_length, file);
-   fclose (file);
-
-   pem_public = strstr (pem, "-----BEGIN CERTIFICATE-----");
    pem_private = strstr (pem, "-----BEGIN ENCRYPTED PRIVATE KEY-----");
 
    if (pem_private) {
@@ -87,96 +243,60 @@ mongoc_secure_channel_setup_certificate_
       goto fail;
    }
 
-   pem_private = strstr (pem, "-----BEGIN RSA PRIVATE KEY-----");
-   if (!pem_private) {
-      pem_private = strstr (pem, "-----BEGIN PRIVATE KEY-----");
-   }
-
-   if (!pem_private) {
-      MONGOC_ERROR ("Can't find private key in '%s'", filename);
+   encoded_cert = decode_pem_base64 (pem_public, &encoded_cert_len, "public key", filename);
+   if (!encoded_cert) {
       goto fail;
    }
-
-   public_blob.cbData = (DWORD) strlen (pem_public);
-   public_blob.pbData = (BYTE *) pem_public;
-
-   /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380264%28v=vs.85%29.aspx
-    */
-   CryptQueryObject (CERT_QUERY_OBJECT_BLOB,      /* dwObjectType, blob or file */
-                     &public_blob,                /* pvObject, Unicode filename */
-                     CERT_QUERY_CONTENT_FLAG_ALL, /* dwExpectedContentTypeFlags */
-                     CERT_QUERY_FORMAT_FLAG_ALL,  /* dwExpectedFormatTypeFlags */
-                     0,                           /* dwFlags, reserved for "future use" */
-                     NULL,                        /* pdwMsgAndCertEncodingType, OUT, unused */
-                     NULL,                        /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */
-                     NULL,                        /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */
-                     NULL,                        /* phCertStore, OUT, HCERTSTORE.., unused, for now */
-                     NULL,                        /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */
-                     (const void **) &cert        /* ppvContext, OUT, the Certificate Context */
-   );
+   cert = CertCreateCertificateContext (X509_ASN_ENCODING, encoded_cert, encoded_cert_len);
 
    if (!cert) {
-      MONGOC_ERROR ("Failed to extract public key from '%s'. Error 0x%.8X", filename, (unsigned int) GetLastError ());
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Failed to extract public key from '%s': %s", filename, msg);
+      bson_free (msg);
       goto fail;
    }
 
-   /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380285%28v=vs.85%29.aspx
-    */
-   success = CryptStringToBinaryA (pem_private,               /* pszString */
-                                   0,                         /* cchString */
-                                   CRYPT_STRING_BASE64HEADER, /* dwFlags */
-                                   NULL,                      /* pbBinary */
-                                   &encrypted_private_len,    /* pcBinary, IN/OUT */
-                                   NULL,                      /* pdwSkip */
-                                   NULL);                     /* pdwFlags */
-   if (!success) {
-      MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", (unsigned int) GetLastError ());
-      goto fail;
-   }
+   if (NULL != (pem_private = strstr (pem, "-----BEGIN RSA PRIVATE KEY-----"))) {
+      encoded_private = decode_pem_base64 (pem_private, &encoded_private_len, "private key", filename);
+      if (!encoded_private) {
+         goto fail;
+      }
 
-   encrypted_private = (LPBYTE) bson_malloc0 (encrypted_private_len);
-   success = CryptStringToBinaryA (
-      pem_private, 0, CRYPT_STRING_BASE64HEADER, encrypted_private, &encrypted_private_len, NULL, NULL);
-   if (!success) {
-      MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", (unsigned int) GetLastError ());
-      goto fail;
-   }
+      blob_private_rsa = decode_object (
+         PKCS_RSA_PRIVATE_KEY, encoded_private, encoded_private_len, &blob_private_rsa_len, "private key", filename);
+      if (!blob_private_rsa) {
+         goto fail;
+      }
+   } else if (NULL != (pem_private = strstr (pem, "-----BEGIN PRIVATE KEY-----"))) {
+      encoded_private = decode_pem_base64 (pem_private, &encoded_private_len, "private key", filename);
+      if (!encoded_private) {
+         goto fail;
+      }
 
-   /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa379912%28v=vs.85%29.aspx
-    */
-   success = CryptDecodeObjectEx (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* dwCertEncodingType */
-                                  PKCS_RSA_PRIVATE_KEY,                    /* lpszStructType */
-                                  encrypted_private,                       /* pbEncoded */
-                                  encrypted_private_len,                   /* cbEncoded */
-                                  0,                                       /* dwFlags */
-                                  NULL,                                    /* pDecodePara */
-                                  NULL,                                    /* pvStructInfo */
-                                  &blob_private_len);                      /* pcbStructInfo */
-   if (!success) {
-      LPTSTR msg = NULL;
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
-                     NULL,
-                     GetLastError (),
-                     LANG_NEUTRAL,
-                     (LPTSTR) &msg,
-                     0,
-                     NULL);
-      MONGOC_ERROR ("Failed to parse private key. %s (0x%.8X)", msg, (unsigned int) GetLastError ());
-      LocalFree (msg);
-      goto fail;
-   }
+      blob_private = decode_object (
+         PKCS_PRIVATE_KEY_INFO, encoded_private, encoded_private_len, &blob_private_len, "private key", filename);
+      if (!blob_private) {
+         goto fail;
+      }
 
-   blob_private = (LPBYTE) bson_malloc0 (blob_private_len);
-   success = CryptDecodeObjectEx (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
-                                  PKCS_RSA_PRIVATE_KEY,
-                                  encrypted_private,
-                                  encrypted_private_len,
-                                  0,
-                                  NULL,
-                                  blob_private,
-                                  &blob_private_len);
-   if (!success) {
-      MONGOC_ERROR ("Failed to parse private key. Error 0x%.8X", (unsigned int) GetLastError ());
+      // Have PrivateKey. Get RSA key from it.
+      CRYPT_PRIVATE_KEY_INFO *privateKeyInfo = (CRYPT_PRIVATE_KEY_INFO *) blob_private;
+      if (strcmp (privateKeyInfo->Algorithm.pszObjId, szOID_RSA_RSA) != 0) {
+         MONGOC_ERROR ("Non-RSA private keys are not supported");
+         goto fail;
+      }
+
+      blob_private_rsa = decode_object (PKCS_RSA_PRIVATE_KEY,
+                                        privateKeyInfo->PrivateKey.pbData,
+                                        privateKeyInfo->PrivateKey.cbData,
+                                        &blob_private_rsa_len,
+                                        "private key",
+                                        filename);
+      if (!blob_private_rsa) {
+         goto fail;
+      }
+   } else {
+      MONGOC_ERROR ("Can't find private key in '%s'", filename);
       goto fail;
    }
 
@@ -188,42 +308,61 @@ mongoc_secure_channel_setup_certificate_
                                   PROV_RSA_FULL,        /* dwProvType */
                                   CRYPT_VERIFYCONTEXT); /* dwFlags */
    if (!success) {
-      MONGOC_ERROR ("CryptAcquireContext failed with error 0x%.8X", (unsigned int) GetLastError ());
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("CryptAcquireContext failed: %s", msg);
+      bson_free (msg);
       goto fail;
    }
 
+   HCRYPTKEY hKey;
    /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380207%28v=vs.85%29.aspx
     */
-   success = CryptImportKey (provider,         /* hProv */
-                             blob_private,     /* pbData */
-                             blob_private_len, /* dwDataLen */
-                             0,                /* hPubKey */
-                             0,                /* dwFlags */
-                             &hKey);           /* phKey, OUT */
+   success = CryptImportKey (provider,             /* hProv */
+                             blob_private_rsa,     /* pbData */
+                             blob_private_rsa_len, /* dwDataLen */
+                             0,                    /* hPubKey */
+                             0,                    /* dwFlags */
+                             &hKey);               /* phKey, OUT */
    if (!success) {
-      MONGOC_ERROR ("CryptImportKey for private key failed with error 0x%.8X", (unsigned int) GetLastError ());
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("CryptImportKey for private key failed: %s", msg);
+      bson_free (msg);
+      CryptReleaseContext (provider, 0);
       goto fail;
    }
+   CryptDestroyKey (hKey);
 
    /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa376573%28v=vs.85%29.aspx
     */
+   // The CERT_KEY_PROV_HANDLE_PROP_ID property takes ownership of `provider`.
    success = CertSetCertificateContextProperty (cert,                         /* pCertContext */
                                                 CERT_KEY_PROV_HANDLE_PROP_ID, /* dwPropId */
                                                 0,                            /* dwFlags */
                                                 (const void *) provider);     /* pvData */
-   if (success) {
-      TRACE ("%s", "Successfully loaded client certificate");
-      return cert;
+   if (!success) {
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Can't associate private key with public key: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
 
-   MONGOC_ERROR ("Can't associate private key with public key: 0x%.8X", (unsigned int) GetLastError ());
+   TRACE ("%s", "Successfully loaded client certificate");
+   ret = true;
 
 fail:
-   SecureZeroMemory (pem, pem_length);
-   bson_free (pem);
-   if (encrypted_private) {
-      SecureZeroMemory (encrypted_private, encrypted_private_len);
-      bson_free (encrypted_private);
+   if (pem) {
+      SecureZeroMemory (pem, pem_length);
+      bson_free (pem);
+   }
+   bson_free (encoded_cert);
+   if (encoded_private) {
+      SecureZeroMemory (encoded_private, encoded_private_len);
+      bson_free (encoded_private);
+   }
+
+   if (blob_private_rsa) {
+      SecureZeroMemory (blob_private_rsa, blob_private_rsa_len);
+      bson_free (blob_private_rsa);
    }
 
    if (blob_private) {
@@ -231,69 +370,56 @@ fail:
       bson_free (blob_private);
    }
 
-   return NULL;
+   if (!ret) {
+      CertFreeCertificateContext (cert);
+      return NULL;
+   }
+
+   return cert;
 }
 
 PCCERT_CONTEXT
-mongoc_secure_channel_setup_certificate (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt)
+mongoc_secure_channel_setup_certificate (mongoc_ssl_opt_t *opt)
 {
    return mongoc_secure_channel_setup_certificate_from_file (opt->pem_file);
 }
 
 
 bool
-mongoc_secure_channel_setup_ca (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt)
+mongoc_secure_channel_setup_ca (mongoc_ssl_opt_t *opt)
 {
-   FILE *file;
-   long length;
+   bool ok = false;
+   char *pem = NULL;
    const char *pem_key;
    HCERTSTORE cert_store = NULL;
    PCCERT_CONTEXT cert = NULL;
-   DWORD encrypted_cert_len = 0;
-   LPBYTE encrypted_cert = NULL;
-
-   file = fopen (opt->ca_file, "rb");
-   if (!file) {
-      MONGOC_ERROR ("Couldn't open file '%s'", opt->ca_file);
-      return false;
-   }
+   DWORD encoded_cert_len = 0;
+   LPBYTE encoded_cert = NULL;
 
-   fseek (file, 0, SEEK_END);
-   length = ftell (file);
-   fseek (file, 0, SEEK_SET);
-   if (length < 1) {
-      MONGOC_WARNING ("Couldn't determine file size of '%s'", opt->ca_file);
+   pem = read_file_and_null_terminate (opt->ca_file, NULL);
+   if (!pem) {
       return false;
    }
 
-   pem_key = (const char *) bson_malloc0 (length);
-   fread ((void *) pem_key, 1, length, file);
-   fclose (file);
-
    /* If we have private keys or other fuzz, seek to the good stuff */
-   pem_key = strstr (pem_key, "-----BEGIN CERTIFICATE-----");
-   /*printf ("%s\n", pem_key);*/
+   pem_key = strstr (pem, "-----BEGIN CERTIFICATE-----");
 
    if (!pem_key) {
       MONGOC_WARNING ("Couldn't find certificate in '%s'", opt->ca_file);
-      return false;
-   }
-
-   if (!CryptStringToBinaryA (pem_key, 0, CRYPT_STRING_BASE64HEADER, NULL, &encrypted_cert_len, NULL, NULL)) {
-      MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", (unsigned int) GetLastError ());
-      return false;
+      goto fail;
    }
 
-   encrypted_cert = (LPBYTE) LocalAlloc (0, encrypted_cert_len);
-   if (!CryptStringToBinaryA (pem_key, 0, CRYPT_STRING_BASE64HEADER, encrypted_cert, &encrypted_cert_len, NULL, NULL)) {
-      MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", (unsigned int) GetLastError ());
-      return false;
+   encoded_cert = decode_pem_base64 (pem_key, &encoded_cert_len, "public key", opt->ca_file);
+   if (!encoded_cert) {
+      goto fail;
    }
 
-   cert = CertCreateCertificateContext (X509_ASN_ENCODING, encrypted_cert, encrypted_cert_len);
+   cert = CertCreateCertificateContext (X509_ASN_ENCODING, encoded_cert, encoded_cert_len);
    if (!cert) {
-      MONGOC_WARNING ("Could not convert certificate");
-      return false;
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_WARNING ("Could not convert certificate: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
 
 
@@ -304,59 +430,81 @@ mongoc_secure_channel_setup_ca (mongoc_s
                                L"Root");                                /* system store name. "My" or "Root" */
 
    if (cert_store == NULL) {
-      MONGOC_ERROR ("Error opening certificate store");
-      return false;
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Error opening certificate store: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
 
-   if (CertAddCertificateContextToStore (cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) {
-      TRACE ("%s", "Added the certificate !");
-      CertCloseStore (cert_store, 0);
-      return true;
+   if (!CertAddCertificateContextToStore (cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) {
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_WARNING ("Failed adding the cert: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
-   MONGOC_WARNING ("Failed adding the cert");
-   CertCloseStore (cert_store, 0);
 
-   return false;
+   TRACE ("%s", "Added the certificate !");
+   ok = true;
+fail:
+   CertCloseStore (cert_store, 0);
+   bson_free (encoded_cert);
+   CertFreeCertificateContext (cert);
+   bson_free (pem);
+   return ok;
 }
 
-bool
-mongoc_secure_channel_setup_crl (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt)
+PCCRL_CONTEXT
+mongoc_secure_channel_load_crl (const char *crl_file)
 {
-   HCERTSTORE cert_store = NULL;
-   PCCERT_CONTEXT cert = NULL;
-   LPWSTR str;
-   int chars;
+   PCCRL_CONTEXT crl = NULL;
+   bool ok = false;
+   DWORD encoded_crl_len = 0;
+   LPBYTE encoded_crl = NULL;
 
-   chars = MultiByteToWideChar (CP_ACP, 0, opt->crl_file, -1, NULL, 0);
-   if (chars < 1) {
-      MONGOC_WARNING ("Can't determine opt->crl_file length");
-      return false;
+   char *pem = read_file_and_null_terminate (crl_file, NULL);
+   if (!pem) {
+      goto fail;
    }
-   str = (LPWSTR) bson_malloc0 (chars * sizeof (*str));
-   MultiByteToWideChar (CP_ACP, 0, opt->crl_file, -1, str, chars);
 
+   const char *pem_begin = strstr (pem, "-----BEGIN X509 CRL-----");
+   if (!pem_begin) {
+      MONGOC_WARNING ("Couldn't find CRL in '%s'", crl_file);
+      goto fail;
+   }
 
-   /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380264%28v=vs.85%29.aspx
-    */
-   CryptQueryObject (CERT_QUERY_OBJECT_FILE,      /* dwObjectType, blob or file */
-                     str,                         /* pvObject, Unicode filename */
-                     CERT_QUERY_CONTENT_FLAG_CRL, /* dwExpectedContentTypeFlags */
-                     CERT_QUERY_FORMAT_FLAG_ALL,  /* dwExpectedFormatTypeFlags */
-                     0,                           /* dwFlags, reserved for "future use" */
-                     NULL,                        /* pdwMsgAndCertEncodingType, OUT, unused */
-                     NULL,                        /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */
-                     NULL,                        /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */
-                     NULL,                        /* phCertStore, OUT, HCERTSTORE.., unused, for now */
-                     NULL,                        /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */
-                     (const void **) &cert        /* ppvContext, OUT, the Certificate Context */
-   );
-   bson_free (str);
+   encoded_crl = decode_pem_base64 (pem_begin, &encoded_crl_len, "CRL", crl_file);
+   if (!encoded_crl) {
+      goto fail;
+   }
 
-   if (!cert) {
-      MONGOC_WARNING ("Can't extract CRL from '%s'", opt->crl_file);
-      return false;
+   crl = CertCreateCRLContext (X509_ASN_ENCODING, encoded_crl, encoded_crl_len);
+
+   if (!crl) {
+      MONGOC_WARNING ("Can't extract CRL from '%s'", crl_file);
+      goto fail;
+   }
+
+   ok = true;
+fail:
+   bson_free (encoded_crl);
+   bson_free (pem);
+   if (!ok) {
+      CertFreeCRLContext (crl);
+      crl = NULL;
    }
+   return crl;
+}
+
+bool
+mongoc_secure_channel_setup_crl (mongoc_ssl_opt_t *opt)
+{
+   HCERTSTORE cert_store = NULL;
+   bool ok = false;
 
+   PCCRL_CONTEXT crl = mongoc_secure_channel_load_crl (opt->crl_file);
+   if (!crl) {
+      goto fail;
+   }
 
    cert_store = CertOpenStore (CERT_STORE_PROV_SYSTEM,                  /* provider */
                                X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */
@@ -365,23 +513,26 @@ mongoc_secure_channel_setup_crl (mongoc_
                                L"Root");                                /* system store name. "My" or "Root" */
 
    if (cert_store == NULL) {
-      MONGOC_ERROR ("Error opening certificate store");
-      CertFreeCertificateContext (cert);
-      return false;
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_ERROR ("Error opening certificate store: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
 
-   if (CertAddCertificateContextToStore (cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) {
-      TRACE ("%s", "Added the certificate !");
-      CertFreeCertificateContext (cert);
-      CertCloseStore (cert_store, 0);
-      return true;
+   if (!CertAddCRLContextToStore (cert_store, crl, CERT_STORE_ADD_USE_EXISTING, NULL)) {
+      char *msg = mongoc_winerr_to_string (GetLastError ());
+      MONGOC_WARNING ("Failed adding the CRL: %s", msg);
+      bson_free (msg);
+      goto fail;
    }
 
-   MONGOC_WARNING ("Failed adding the cert");
-   CertFreeCertificateContext (cert);
-   CertCloseStore (cert_store, 0);
+   TRACE ("%s", "Added the CRL!");
+   ok = true;
 
-   return false;
+fail:
+   CertCloseStore (cert_store, 0);
+   CertFreeCRLContext (crl);
+   return ok;
 }
 
 ssize_t
@@ -389,7 +540,7 @@ mongoc_secure_channel_read (mongoc_strea
 {
    BSON_ASSERT_PARAM (tls);
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, tls->timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, tls->timeout_msec))) {
       // CDRIVER-4589
       MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec);
       return -1;
@@ -417,7 +568,7 @@ mongoc_secure_channel_write (mongoc_stre
 {
    BSON_ASSERT_PARAM (tls);
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, tls->timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, tls->timeout_msec))) {
       // CDRIVER-4589
       MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec);
       return -1;
@@ -491,10 +642,10 @@ _mongoc_secure_channel_init_sec_buffer_d
 }
 
 
-#define MONGOC_LOG_AND_SET_ERROR(ERROR, DOMAIN, CODE, ...) \
-   do {                                                    \
-      MONGOC_ERROR (__VA_ARGS__);                          \
-      bson_set_error (ERROR, DOMAIN, CODE, __VA_ARGS__);   \
+#define MONGOC_LOG_AND_SET_ERROR(ERROR, DOMAIN, CODE, ...)  \
+   do {                                                     \
+      MONGOC_ERROR (__VA_ARGS__);                           \
+      _mongoc_set_error (ERROR, DOMAIN, CODE, __VA_ARGS__); \
    } while (0)
 
 bool
@@ -533,13 +684,12 @@ mongoc_secure_channel_handshake_step_1 (
                                             &secure_channel->ret_flags,         /* pfContextAttr OUT param */
                                             &secure_channel->ctxt->time_stamp   /* ptsExpiry OUT param */
    );
-
    if (sspi_status != SEC_I_CONTINUE_NEEDED) {
-      MONGOC_LOG_AND_SET_ERROR (error,
-                                MONGOC_ERROR_STREAM,
-                                MONGOC_ERROR_STREAM_SOCKET,
-                                "initial InitializeSecurityContext failed: %ld",
-                                sspi_status);
+      // Cast signed SECURITY_STATUS to unsigned DWORD. FormatMessage expects DWORD.
+      char *msg = mongoc_winerr_to_string ((DWORD) sspi_status);
+      MONGOC_LOG_AND_SET_ERROR (
+         error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "initial InitializeSecurityContext failed: %s", msg);
+      bson_free (msg);
       return false;
    }
 
@@ -768,24 +918,14 @@ mongoc_secure_channel_handshake_step_2 (
 
 
          default: {
-            LPTSTR msg = NULL;
-
-            FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
-                           NULL,
-                           GetLastError (),
-                           LANG_NEUTRAL,
-                           (LPTSTR) &msg,
-                           0,
-                           NULL);
+            // Cast signed SECURITY_STATUS to unsigned DWORD. FormatMessage expects DWORD.
+            char *msg = mongoc_winerr_to_string ((DWORD) sspi_status);
             MONGOC_LOG_AND_SET_ERROR (error,
                                       MONGOC_ERROR_STREAM,
                                       MONGOC_ERROR_STREAM_SOCKET,
-                                      "Failed to initialize security context, error code: "
-                                      "0x%04X%04X: %s",
-                                      (unsigned int) (sspi_status >> 16) & 0xffff,
-                                      (unsigned int) sspi_status & 0xffff,
+                                      "Failed to initialize security context: %s",
                                       msg);
-            LocalFree (msg);
+            bson_free (msg);
          }
          }
          return false;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-transport.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-transport.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-secure-transport.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-secure-transport.c	2025-06-19 15:42:22.000000000 +0000
@@ -36,8 +36,12 @@
 #include <Security/Security.h>
 #include <Security/SecureTransport.h>
 #include <CoreFoundation/CoreFoundation.h>
+#include <common-macros-private.h>
 #include <common-string-private.h>
 
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+BEGIN_IGNORE_DEPRECATIONS
+
 /* Jailbreak Darwin Private API */
 /*
  * An alternative to using SecIdentityCreate is to use
@@ -386,4 +390,7 @@ CFReleaseSafe (CFTypeRef cf)
    }
 }
 
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+END_IGNORE_DEPRECATIONS
+
 #endif
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-description.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-description.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-description.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-description.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,6 +15,7 @@
  */
 
 #include <mongoc/mongoc-config.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-host-list.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-read-prefs.h>
@@ -286,13 +287,12 @@ mongoc_server_description_id (const mong
  *      Return a reference to the host associated with this server description.
  *
  * Returns:
- *      This server description's host, a mongoc_host_list_t * you must
- *      not modify or free.
+ *      This server description's host, a const mongoc_host_list_t *.
  *
  *--------------------------------------------------------------------------
  */
 
-mongoc_host_list_t *
+const mongoc_host_list_t *
 mongoc_server_description_host (const mongoc_server_description_t *description)
 {
    return &((mongoc_server_description_t *) description)->host;
@@ -391,25 +391,6 @@ mongoc_server_description_hello_response
 /*
  *--------------------------------------------------------------------------
  *
- * mongoc_server_description_ismaster --
- *
- *      Return this server's most recent "hello" command response.
- *
- * Returns:
- *      A reference to a BSON document, owned by the server description.
- *
- *--------------------------------------------------------------------------
- */
-
-const bson_t *
-mongoc_server_description_ismaster (const mongoc_server_description_t *description)
-{
-   return mongoc_server_description_hello_response (description);
-}
-
-/*
- *--------------------------------------------------------------------------
- *
  * mongoc_server_description_set_state --
  *
  *       Set the server description's server type.
@@ -498,7 +479,7 @@ _mongoc_server_description_set_error (mo
    if (error && error->code) {
       memcpy (&sd->error, error, sizeof (bson_error_t));
    } else {
-      bson_set_error (&sd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "unknown error calling hello");
+      _mongoc_set_error (&sd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "unknown error calling hello");
    }
 
    /* Server Discovery and Monitoring Spec: if the server type changes from a
@@ -570,6 +551,7 @@ mongoc_server_description_handle_hello (
              * MUST treat this an authentication error." */
             sd->error.domain = MONGOC_ERROR_CLIENT;
             sd->error.code = MONGOC_ERROR_CLIENT_AUTHENTICATE;
+            _mongoc_set_error_category (&sd->error, MONGOC_ERROR_CATEGORY);
             GOTO (authfailure);
          }
       } else if (strcmp ("isWritablePrimary", bson_iter_key (&iter)) == 0 ||
@@ -741,12 +723,12 @@ mongoc_server_description_handle_hello (
    EXIT;
 
 typefailure:
-   bson_set_error (&sd->error,
-                   MONGOC_ERROR_STREAM,
-                   MONGOC_ERROR_STREAM_INVALID_TYPE,
-                   "unexpected type %s for field %s in hello response",
-                   _mongoc_bson_type_to_str (bson_iter_type (&iter)),
-                   bson_iter_key (&iter));
+   _mongoc_set_error (&sd->error,
+                      MONGOC_ERROR_STREAM,
+                      MONGOC_ERROR_STREAM_INVALID_TYPE,
+                      "unexpected type %s for field %s in hello response",
+                      _mongoc_bson_type_to_str (bson_iter_type (&iter)),
+                      bson_iter_key (&iter));
 authfailure:
    sd->type = MONGOC_SERVER_UNKNOWN;
    sd->round_trip_time_msec = MONGOC_RTT_UNSET;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-description.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-description.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-description.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-description.h	2025-06-19 15:42:22.000000000 +0000
@@ -38,7 +38,7 @@ mongoc_server_description_new_copy (cons
 MONGOC_EXPORT (uint32_t)
 mongoc_server_description_id (const mongoc_server_description_t *description);
 
-MONGOC_EXPORT (mongoc_host_list_t *)
+MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_server_description_host (const mongoc_server_description_t *description);
 
 MONGOC_EXPORT (int64_t)
@@ -53,10 +53,6 @@ mongoc_server_description_type (const mo
 MONGOC_EXPORT (const bson_t *)
 mongoc_server_description_hello_response (const mongoc_server_description_t *description);
 
-MONGOC_EXPORT (const bson_t *)
-mongoc_server_description_ismaster (const mongoc_server_description_t *description)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_server_description_hello_response);
-
 MONGOC_EXPORT (int32_t)
 mongoc_server_description_compressor_id (const mongoc_server_description_t *description);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-monitor.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-monitor.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-monitor.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-monitor.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <mlib/intencode.h>
 #include <common-thread-private.h>
 #include <mongoc/mongoc-server-monitor-private.h>
 
@@ -123,8 +124,6 @@ static BSON_GNUC_PRINTF (3, 4) void _ser
 
 /* TODO CDRIVER-3710 use MONGOC_LOG_LEVEL_ERROR */
 #define MONITOR_LOG_ERROR(sm, ...) _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__)
-/* TODO CDRIVER-3710 use MONGOC_LOG_LEVEL_WARNING */
-#define MONITOR_LOG_WARNING(sm, ...) _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__)
 
 static void
 _server_monitor_heartbeat_started (mongoc_server_monitor_t *server_monitor, bool awaited)
@@ -259,13 +258,6 @@ _server_monitor_append_cluster_time (mon
    mc_tpld_drop_ref (&td);
 }
 
-static int32_t
-_int32_from_le (const void *data)
-{
-   BSON_ASSERT_PARAM (data);
-   return bson_iter_int32_unsafe (&(bson_iter_t){.raw = data});
-}
-
 static bool
 _server_monitor_send_and_recv_hello_opmsg (mongoc_server_monitor_t *server_monitor,
                                            const bson_t *cmd,
@@ -317,16 +309,16 @@ _server_monitor_send_and_recv_hello_opms
       goto fail;
    }
 
-   const int32_t message_length = _int32_from_le (buffer.data);
+   const int32_t message_length = mlib_read_i32le (buffer.data);
 
    // msgHeader consists of four int32 fields.
    const int32_t message_header_length = 4u * sizeof (int32_t);
 
    if (message_length < message_header_length) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: message length");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: message length");
       goto fail;
    }
 
@@ -339,29 +331,29 @@ _server_monitor_send_and_recv_hello_opms
 
    mcd_rpc_message_reset (rpc);
    if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: malformed message");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: malformed message");
       goto fail;
    }
 
    mcd_rpc_message_ingress (rpc);
 
    if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: decompression failure");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: decompression failure");
       goto fail;
    }
 
    bson_t body;
    if (!mcd_rpc_message_get_body (rpc, &body)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: malformed body");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: malformed body");
       goto fail;
    }
 
@@ -430,16 +422,16 @@ _server_monitor_send_and_recv_opquery (m
       goto fail;
    }
 
-   const int32_t message_length = _int32_from_le (buffer.data);
+   const int32_t message_length = mlib_read_i32le (buffer.data);
 
    // msgHeader consists of four int32 fields.
    const int32_t message_header_length = 4u * sizeof (int32_t);
 
    if (message_length < message_header_length) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: message length");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: message length");
       goto fail;
    }
 
@@ -452,29 +444,29 @@ _server_monitor_send_and_recv_opquery (m
 
    mcd_rpc_message_reset (rpc);
    if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: malformed message");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: malformed message");
       goto fail;
    }
 
    mcd_rpc_message_ingress (rpc);
 
    if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: decompression failure");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: decompression failure");
       goto fail;
    }
 
    bson_t body;
    if (!mcd_rpc_message_get_body (rpc, &body)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "invalid reply from server: malformed body");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "invalid reply from server: malformed body");
       goto fail;
    }
 
@@ -608,12 +600,12 @@ _server_monitor_poll_with_interrupt (mon
       ret = mongoc_stream_poll (poller, 1, (int32_t) BSON_MIN (timeleft_ms, monitor_tick_ms));
       if (ret == -1) {
          MONITOR_LOG (server_monitor, "mongoc_stream_poll error");
-         bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "poll error");
+         _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "poll error");
          return false;
       }
 
       if (poller[0].revents & (POLLERR | POLLHUP)) {
-         bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed while polling");
+         _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed while polling");
          return false;
       }
 
@@ -633,7 +625,7 @@ _server_monitor_poll_with_interrupt (mon
          return true;
       }
    }
-   bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection timeout while polling");
+   _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection timeout while polling");
    return false;
 }
 
@@ -649,7 +641,7 @@ _get_timeout_ms (int64_t expire_at_ms, b
 
    timeout_ms = expire_at_ms - _now_ms ();
    if (timeout_ms <= 0) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection timed out reading message length");
       return 0;
    }
@@ -699,18 +691,18 @@ _server_monitor_awaitable_hello_recv (mo
       GOTO (fail);
    }
 
-   const int32_t message_length = _int32_from_le (buffer.data);
+   const int32_t message_length = mlib_read_i32le (buffer.data);
 
    // msgHeader consists of four int32 fields.
    const int32_t message_header_length = 4u * sizeof (int32_t);
 
    if ((message_length < message_header_length) || (message_length > server_monitor->description->max_msg_size)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_PROTOCOL,
-                      MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
-                      "message size %" PRId32 " is not within expected range 16-%" PRId32 " bytes",
-                      message_length,
-                      server_monitor->description->max_msg_size);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_PROTOCOL,
+                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
+                         "message size %" PRId32 " is not within expected range 16-%" PRId32 " bytes",
+                         message_length,
+                         server_monitor->description->max_msg_size);
       GOTO (fail);
    }
 
@@ -727,7 +719,7 @@ _server_monitor_awaitable_hello_recv (mo
    }
 
    if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed message from server");
       GOTO (fail);
    }
@@ -735,13 +727,13 @@ _server_monitor_awaitable_hello_recv (mo
    mcd_rpc_message_ingress (rpc);
 
    if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) {
-      bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "decompression failure");
+      _mongoc_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "decompression failure");
       GOTO (fail);
    }
 
    bson_t body;
    if (!mcd_rpc_message_get_body (rpc, &body)) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed BSON payload from server");
       GOTO (fail);
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-stream.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-stream.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-server-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-server-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,9 +19,6 @@
 #include <mongoc/mongoc-server-stream-private.h>
 #include <mongoc/mongoc-util-private.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "server-stream"
-
 mongoc_server_stream_t *
 mongoc_server_stream_new (const mongoc_topology_description_t *td,
                           mongoc_server_description_t *sd,
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-set.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-set.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-set.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-set.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,10 +18,7 @@
 #include <bson/bson.h>
 
 #include <mongoc/mongoc-set-private.h>
-#include <common-cmp-private.h>
-
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "set"
+#include <mlib/cmp.h>
 
 mongoc_set_t *
 mongoc_set_new (size_t nitems, mongoc_set_item_dtor dtor, void *dtor_ctx)
@@ -202,7 +199,7 @@ mongoc_set_for_each_with_id (mongoc_set_
    BSON_ASSERT_PARAM (cb);
    BSON_ASSERT (ctx || true);
 
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, set->items_len));
+   BSON_ASSERT (mlib_in_range (uint32_t, set->items_len));
    const uint32_t items_len = (uint32_t) set->items_len;
 
    /* prevent undefined behavior of memcpy(NULL) */
@@ -231,7 +228,7 @@ mongoc_set_for_each_with_id_const (const
    BSON_ASSERT_PARAM (cb);
    BSON_ASSERT (ctx || true);
 
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, set->items_len));
+   BSON_ASSERT (mlib_in_range (uint32_t, set->items_len));
    const uint32_t items_len = (uint32_t) set->items_len;
 
    /* prevent undefined behavior of memcpy(NULL) */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sleep.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sleep.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sleep.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sleep.h	2025-06-19 15:42:22.000000000 +0000
@@ -14,7 +14,7 @@ BSON_BEGIN_DECLS
  * @usec: Number of microseconds to sleep for.
  * @user_data: User data provided to mongoc_client_set_usleep_impl().
  */
-typedef void (*mongoc_usleep_func_t) (int64_t usec, void *user_data);
+typedef void (BSON_CALL *mongoc_usleep_func_t) (int64_t usec, void *user_data);
 
 /**
  * mongoc_client_set_usleep_impl:
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-socket.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-socket.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-socket.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-socket.c	2025-06-19 15:42:22.000000000 +0000
@@ -28,7 +28,7 @@
 #include <Mstcpip.h>
 #include <process.h>
 #endif
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <inttypes.h>
 
@@ -1192,7 +1192,7 @@ _mongoc_socket_try_sendv_slow (mongoc_so
 
    for (size_t i = 0u; i < iovcnt; i++) {
 #ifdef _WIN32
-      BSON_ASSERT (mcommon_in_range_unsigned (int, iov[i].iov_len));
+      BSON_ASSERT (mlib_in_range (int, iov[i].iov_len));
       const int wrote = send (sock->sd, iov[i].iov_base, (int) iov[i].iov_len, 0);
       if (wrote == SOCKET_ERROR) {
 #else
@@ -1209,7 +1209,7 @@ _mongoc_socket_try_sendv_slow (mongoc_so
 
       ret += wrote;
 
-      if (mcommon_cmp_not_equal_su (wrote, iov[i].iov_len)) {
+      if (mlib_cmp (wrote, !=, iov[i].iov_len)) {
          RETURN (ret);
       }
    }
@@ -1259,7 +1259,7 @@ _mongoc_socket_try_sendv (mongoc_socket_
    DUMP_IOVEC (sendbuf, iov, iovcnt);
 
 #ifdef _WIN32
-   BSON_ASSERT (mcommon_in_range_unsigned (unsigned_long, iovcnt));
+   BSON_ASSERT (mlib_in_range (unsigned long, iovcnt));
    ret = WSASend (sock->sd, (LPWSABUF) iov, (DWORD) iovcnt, &dwNumberofBytesSent, 0, NULL, NULL);
    TRACE ("WSASend sent: %lu (out of: %zu), ret: %d", dwNumberofBytesSent, iov->iov_len, ret);
 #else
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-ssl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-ssl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-ssl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-ssl.c	2025-06-19 15:42:22.000000000 +0000
@@ -28,8 +28,6 @@
 
 #if defined(MONGOC_ENABLE_SSL_OPENSSL)
 #include <mongoc/mongoc-openssl-private.h>
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-#include <mongoc/mongoc-libressl-private.h>
 #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
 #include <mongoc/mongoc-secure-transport-private.h>
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sspi.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sspi.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-sspi.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-sspi.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,6 +25,7 @@
 #define CRYPT_STRING_NOCRLF 0x40000000
 #endif
 
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-sspi-private.h>
 
@@ -56,16 +57,9 @@ _mongoc_sspi_destroy_sspi_client_state (
 void
 _mongoc_sspi_set_gsserror (DWORD errCode, const SEC_CHAR *msg)
 {
-   SEC_CHAR *err;
-   DWORD status;
-   DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
-   status = FormatMessageA (flags, NULL, errCode, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err, 0, NULL);
-   if (status) {
-      MONGOC_ERROR ("SSPI: %s: %s", msg, err);
-      LocalFree (err);
-   } else {
-      MONGOC_ERROR ("SSPI: %s", msg);
-   }
+   char *err = mongoc_winerr_to_string (errCode);
+   MONGOC_ERROR ("SSPI: %s: %s", msg, err);
+   bson_free (err);
 }
 
 static SEC_CHAR *
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-file.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-file.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-file.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-file.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,7 +24,7 @@
 #include <mongoc/mongoc-stream-file.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-counters-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 /*
  * TODO: This does not respect timeouts or set O_NONBLOCK.
@@ -132,7 +132,7 @@ _mongoc_stream_file_readv (mongoc_stream
       ENTRY;
 
       for (size_t i = 0u; i < iovcnt; i++) {
-         BSON_ASSERT (mcommon_in_range_unsigned (unsigned_int, iov[i].iov_len));
+         BSON_ASSERT (mlib_in_range (unsigned int, iov[i].iov_len));
          const int nread = _read (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len);
          if (nread < 0) {
             ret = ret ? ret : -1;
@@ -142,7 +142,7 @@ _mongoc_stream_file_readv (mongoc_stream
             GOTO (done);
          } else {
             ret += nread;
-            if (nread != iov[i].iov_len) {
+            if ((size_t) nread != iov[i].iov_len) {
                ret = ret ? ret : -1;
                GOTO (done);
             }
@@ -154,7 +154,7 @@ _mongoc_stream_file_readv (mongoc_stream
 #else
    {
       ENTRY;
-      BSON_ASSERT (mcommon_in_range_unsigned (int, iovcnt));
+      BSON_ASSERT (mlib_in_range (int, iovcnt));
       ret = readv (file->fd, iov, (int) iovcnt);
       GOTO (done);
    }
@@ -181,9 +181,9 @@ _mongoc_stream_file_writev (mongoc_strea
 #ifdef _WIN32
    {
       for (size_t i = 0; i < iovcnt; i++) {
-         BSON_ASSERT (mcommon_in_range_unsigned (unsigned_int, iov[i].iov_len));
+         BSON_ASSERT (mlib_in_range (unsigned int, iov[i].iov_len));
          const int nwrite = _write (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len);
-         if (mcommon_cmp_not_equal_su (nwrite, iov[i].iov_len)) {
+         if (mlib_cmp (nwrite, !=, iov[i].iov_len)) {
             ret = ret ? ret : -1;
             goto done;
          }
@@ -193,7 +193,7 @@ _mongoc_stream_file_writev (mongoc_strea
    }
 #else
    {
-      BSON_ASSERT (mcommon_in_range_unsigned (int, iovcnt));
+      BSON_ASSERT (mlib_in_range (int, iovcnt));
       ret = writev (file->fd, iov, (int) iovcnt);
       goto done;
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl-private.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,44 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_STREAM_TLS_LIBRESSL_PRIVATE_H
-#define MONGOC_STREAM_TLS_LIBRESSL_PRIVATE_H
-
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-#include <bson/bson.h>
-
-#include <tls.h>
-
-BSON_BEGIN_DECLS
-
-
-/**
- * mongoc_stream_tls_libressl_t:
- *
- * Private storage for LibreSSL Streams
- */
-typedef struct {
-   struct tls *ctx;
-   struct tls_config *config;
-} mongoc_stream_tls_libressl_t;
-
-
-BSON_END_DECLS
-
-#endif /* MONGOC_ENABLE_SSL_LIBRESSL */
-#endif /* MONGOC_STREAM_TLS_LIBRESSL_PRIVATE_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,514 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-config.h>
-
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-trace-private.h>
-#include <mongoc/mongoc-log.h>
-#include <mongoc/mongoc-stream-tls.h>
-#include <mongoc/mongoc-stream-tls-private.h>
-#include <mongoc/mongoc-stream-private.h>
-#include <mongoc/mongoc-stream-tls-libressl-private.h>
-#include <mongoc/mongoc-libressl-private.h>
-#include <mongoc/mongoc-ssl.h>
-#include <mongoc/mongoc-ssl-private.h>
-#include <mongoc/mongoc-error.h>
-#include <mongoc/mongoc-counters-private.h>
-#include <mongoc/mongoc-stream-socket.h>
-#include <mongoc/mongoc-socket-private.h>
-
-#include <tls.h>
-
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "stream-tls-libressl"
-
-static void
-_mongoc_stream_tls_libressl_destroy (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-
-   tls_close (libressl->ctx);
-   tls_free (libressl->ctx);
-   tls_config_free (libressl->config);
-
-   mongoc_stream_destroy (tls->base_stream);
-
-   bson_free (libressl);
-   bson_free (stream);
-
-   mongoc_counter_streams_active_dec ();
-   mongoc_counter_streams_disposed_inc ();
-   EXIT;
-}
-
-static void
-_mongoc_stream_tls_libressl_failed (mongoc_stream_t *stream)
-{
-   ENTRY;
-   _mongoc_stream_tls_libressl_destroy (stream);
-   EXIT;
-}
-
-static int
-_mongoc_stream_tls_libressl_close (mongoc_stream_t *stream)
-{
-   int ret = 0;
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-
-   ret = mongoc_stream_close (tls->base_stream);
-   RETURN (ret);
-}
-
-static int
-_mongoc_stream_tls_libressl_flush (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-   RETURN (0);
-}
-
-static ssize_t
-_mongoc_stream_tls_libressl_write (mongoc_stream_t *stream, char *buf, size_t buf_len)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-   mongoc_stream_poll_t poller;
-   ssize_t total_write = 0;
-   ssize_t ret;
-   int64_t now;
-   int64_t expire = 0;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-
-   if (tls->timeout_msec >= 0) {
-      expire = bson_get_monotonic_time () + (tls->timeout_msec * 1000UL);
-   }
-
-   do {
-      poller.stream = stream;
-      poller.revents = 0;
-      poller.events = POLLOUT;
-      ret = tls_write (libressl->ctx, buf, buf_len);
-
-      if (ret == TLS_WANT_POLLIN) {
-         poller.events = POLLIN;
-         mongoc_stream_poll (&poller, 1, tls->timeout_msec);
-      } else if (ret == TLS_WANT_POLLOUT) {
-         poller.events = POLLOUT;
-         mongoc_stream_poll (&poller, 1, tls->timeout_msec);
-      } else if (ret < 0) {
-         RETURN (total_write);
-      } else {
-         buf += ret;
-         buf_len -= ret;
-         total_write += ret;
-      }
-      if (expire) {
-         now = bson_get_monotonic_time ();
-
-         if ((expire - now) < 0) {
-            if (ret == 0) {
-               mongoc_counter_streams_timeout_inc ();
-               break;
-            }
-
-            tls->timeout_msec = 0;
-         } else {
-            tls->timeout_msec = (expire - now) / 1000L;
-         }
-      }
-   } while (buf_len > 0);
-
-
-   RETURN (total_write);
-}
-
-/* This is copypasta from _mongoc_stream_tls_openssl_writev */
-#define MONGOC_STREAM_TLS_BUFFER_SIZE 4096
-static ssize_t
-_mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-   char buf[MONGOC_STREAM_TLS_BUFFER_SIZE];
-   ssize_t ret = 0;
-   ssize_t child_ret;
-   size_t i;
-   size_t iov_pos = 0;
-
-   /* There's a bit of a dance to coalesce vectorized writes into
-    * MONGOC_STREAM_TLS_BUFFER_SIZE'd writes to avoid lots of small tls
-    * packets.
-    *
-    * The basic idea is that we want to combine writes in the buffer if they're
-    * smaller than the buffer, flushing as it gets full.  For larger writes, or
-    * the last write in the iovec array, we want to ignore the buffer and just
-    * write immediately.  We take care of doing buffer writes by re-invoking
-    * ourself with a single iovec_t, pointing at our stack buffer.
-    */
-   char *buf_head = buf;
-   char *buf_tail = buf;
-   char *buf_end = buf + MONGOC_STREAM_TLS_BUFFER_SIZE;
-   size_t bytes;
-
-   char *to_write = NULL;
-   size_t to_write_len;
-
-   BSON_ASSERT (iov);
-   BSON_ASSERT (iovcnt);
-   BSON_ASSERT (libressl);
-   ENTRY;
-
-   tls->timeout_msec = timeout_msec;
-
-   for (i = 0; i < iovcnt; i++) {
-      iov_pos = 0;
-
-      while (iov_pos < iov[i].iov_len) {
-         if (buf_head != buf_tail || ((i + 1 < iovcnt) && ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) {
-            /* If we have either of:
-             *   - buffered bytes already
-             *   - another iovec to send after this one and we don't have more
-             *     bytes to send than the size of the buffer.
-             *
-             * copy into the buffer */
-
-            bytes = BSON_MIN (iov[i].iov_len - iov_pos, buf_end - buf_tail);
-
-            memcpy (buf_tail, (char *) iov[i].iov_base + iov_pos, bytes);
-            buf_tail += bytes;
-            iov_pos += bytes;
-
-            if (buf_tail == buf_end) {
-               /* If we're full, request send */
-
-               to_write = buf_head;
-               to_write_len = buf_tail - buf_head;
-
-               buf_tail = buf_head = buf;
-            }
-         } else {
-            /* Didn't buffer, so just write it through */
-
-            to_write = (char *) iov[i].iov_base + iov_pos;
-            to_write_len = iov[i].iov_len - iov_pos;
-
-            iov_pos += to_write_len;
-         }
-
-         if (to_write) {
-            /* We get here if we buffered some bytes and filled the buffer, or
-             * if we didn't buffer and have to send out of the iovec */
-
-            child_ret = _mongoc_stream_tls_libressl_write (stream, to_write, to_write_len);
-
-            if (child_ret < 0) {
-               RETURN (ret);
-            }
-
-            ret += child_ret;
-
-            if (child_ret < to_write_len) {
-               /* we timed out, so send back what we could send */
-
-               RETURN (ret);
-            }
-
-            to_write = NULL;
-         }
-      }
-   }
-
-   if (buf_head != buf_tail) {
-      /* If we have any bytes buffered, send */
-
-      child_ret = _mongoc_stream_tls_libressl_write (stream, buf_head, buf_tail - buf_head);
-
-      if (child_ret < 0) {
-         RETURN (child_ret);
-      }
-
-      ret += child_ret;
-   }
-
-   if (ret >= 0) {
-      mongoc_counter_streams_egress_add (ret);
-   }
-
-   TRACE ("Returning %d", (int) ret);
-   RETURN (ret);
-}
-
-/* This function is copypasta of _mongoc_stream_tls_openssl_readv */
-static ssize_t
-_mongoc_stream_tls_libressl_readv (
-   mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-   ssize_t ret = 0;
-   ssize_t read_ret;
-   size_t i;
-   size_t iov_pos = 0;
-   int64_t now;
-   int64_t expire = 0;
-   mongoc_stream_poll_t poller;
-
-   BSON_ASSERT (iov);
-   BSON_ASSERT (iovcnt);
-   BSON_ASSERT (libressl);
-   ENTRY;
-
-   tls->timeout_msec = timeout_msec;
-
-   if (timeout_msec >= 0) {
-      expire = bson_get_monotonic_time () + (timeout_msec * 1000UL);
-   }
-
-   for (i = 0; i < iovcnt; i++) {
-      iov_pos = 0;
-
-      while (iov_pos < iov[i].iov_len) {
-         poller.stream = stream;
-         poller.revents = 0;
-         poller.events = POLLIN;
-         read_ret = tls_read (libressl->ctx, (char *) iov[i].iov_base + iov_pos, (int) (iov[i].iov_len - iov_pos));
-
-         if (read_ret == TLS_WANT_POLLIN) {
-            poller.events = POLLIN;
-            mongoc_stream_poll (&poller, 1, tls->timeout_msec);
-         } else if (read_ret == TLS_WANT_POLLOUT) {
-            poller.events = POLLOUT;
-            mongoc_stream_poll (&poller, 1, tls->timeout_msec);
-         } else if (read_ret < 0) {
-            RETURN (ret);
-         } else {
-            iov_pos += read_ret;
-            ret += read_ret;
-         }
-         if (expire) {
-            now = bson_get_monotonic_time ();
-
-            if ((expire - now) < 0) {
-               if (read_ret == 0) {
-                  mongoc_counter_streams_timeout_inc ();
-                  errno = ETIMEDOUT;
-                  RETURN (-1);
-               }
-
-               tls->timeout_msec = 0;
-            } else {
-               tls->timeout_msec = (expire - now) / 1000L;
-            }
-         }
-
-
-         if (ret > 0 && (size_t) ret >= min_bytes) {
-            mongoc_counter_streams_ingress_add (ret);
-            RETURN (ret);
-         }
-      }
-   }
-
-   if (ret >= 0) {
-      mongoc_counter_streams_ingress_add (ret);
-   }
-
-   RETURN (ret);
-}
-
-static int
-_mongoc_stream_tls_libressl_setsockopt (
-   mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-   RETURN (mongoc_stream_setsockopt (tls->base_stream, level, optname, optval, optlen));
-}
-
-static mongoc_stream_t *
-_mongoc_stream_tls_libressl_get_base_stream (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-   RETURN (tls->base_stream);
-}
-
-
-static bool
-_mongoc_stream_tls_libressl_check_closed (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-   RETURN (mongoc_stream_check_closed (tls->base_stream));
-}
-
-bool
-mongoc_stream_tls_libressl_handshake (mongoc_stream_t *stream, const char *host, int *events, bson_error_t *error)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-   mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx;
-   int ret;
-
-   ENTRY;
-   BSON_ASSERT (libressl);
-
-   ret = tls_handshake (libressl->ctx);
-
-   if (ret == TLS_WANT_POLLIN) {
-      *events = POLLIN;
-   } else if (ret == TLS_WANT_POLLOUT) {
-      *events = POLLOUT;
-   } else if (ret < 0) {
-      *events = 0;
-      bson_set_error (
-         error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: %s", tls_error (libressl->ctx));
-      RETURN (false);
-   } else {
-      RETURN (true);
-   }
-   RETURN (false);
-}
-
-static bool
-_mongoc_stream_tls_libressl_timed_out (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-
-   ENTRY;
-
-   RETURN (mongoc_stream_timed_out (tls->base_stream));
-}
-
-static bool
-_mongoc_stream_tls_libressl_should_retry (mongoc_stream_t *stream)
-{
-   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream;
-
-   ENTRY;
-
-   RETURN (mongoc_stream_should_retry (tls->base_stream));
-}
-
-mongoc_stream_t *
-mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client)
-{
-   mongoc_stream_tls_t *tls;
-   mongoc_stream_tls_libressl_t *libressl;
-
-   ENTRY;
-   BSON_ASSERT (base_stream);
-   BSON_ASSERT (opt);
-
-
-   if (opt->crl_file) {
-      MONGOC_ERROR ("Setting mongoc_ssl_opt_t.crl_file has no effect when built "
-                    "against libtls");
-      RETURN (false);
-   }
-   libressl = (mongoc_stream_tls_libressl_t *) bson_malloc0 (sizeof *libressl);
-
-   tls = (mongoc_stream_tls_t *) bson_malloc0 (sizeof *tls);
-   tls->parent.type = MONGOC_STREAM_TLS;
-   tls->parent.destroy = _mongoc_stream_tls_libressl_destroy;
-   tls->parent.failed = _mongoc_stream_tls_libressl_failed;
-   tls->parent.close = _mongoc_stream_tls_libressl_close;
-   tls->parent.flush = _mongoc_stream_tls_libressl_flush;
-   tls->parent.writev = _mongoc_stream_tls_libressl_writev;
-   tls->parent.readv = _mongoc_stream_tls_libressl_readv;
-   tls->parent.setsockopt = _mongoc_stream_tls_libressl_setsockopt;
-   tls->parent.get_base_stream = _mongoc_stream_tls_libressl_get_base_stream;
-   tls->parent.check_closed = _mongoc_stream_tls_libressl_check_closed;
-   tls->parent.timed_out = _mongoc_stream_tls_libressl_timed_out;
-   tls->parent.should_retry = _mongoc_stream_tls_libressl_should_retry;
-   memcpy (&tls->ssl_opts, opt, sizeof tls->ssl_opts);
-   tls->handshake = mongoc_stream_tls_libressl_handshake;
-   tls->ctx = (void *) libressl;
-   tls->timeout_msec = -1;
-   tls->base_stream = base_stream;
-
-   libressl->ctx = client ? tls_client () : tls_server ();
-   libressl->config = tls_config_new ();
-
-   if (opt->weak_cert_validation) {
-      tls_config_insecure_noverifycert (libressl->config);
-      tls_config_insecure_noverifytime (libressl->config);
-   }
-   if (opt->allow_invalid_hostname) {
-      tls_config_insecure_noverifyname (libressl->config);
-   }
-   tls_config_set_ciphers (libressl->config, "compat");
-
-   mongoc_libressl_setup_certificate (libressl, opt);
-   mongoc_libressl_setup_ca (libressl, opt);
-   {
-      mongoc_stream_t *stream = base_stream;
-
-      do {
-         if (stream->type == MONGOC_STREAM_SOCKET) {
-            int socket = mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream)->sd;
-            if (tls_configure (libressl->ctx, libressl->config) == -1) {
-               MONGOC_ERROR ("%s", tls_config_error (libressl->config));
-               RETURN (false);
-            }
-            if (tls_connect_socket (libressl->ctx, socket, host) == -1) {
-               MONGOC_ERROR ("%s", tls_error (libressl->ctx));
-               RETURN (false);
-            }
-            break;
-         }
-      } while ((stream = mongoc_stream_get_base_stream (stream)));
-   }
-
-   mongoc_counter_streams_active_inc ();
-
-   if (_mongoc_ssl_opts_disable_certificate_revocation_check (opt)) {
-      MONGOC_ERROR ("Setting tlsDisableCertificateRevocationCheck has no "
-                    "effect when built against libtls");
-   }
-
-   if (_mongoc_ssl_opts_disable_ocsp_endpoint_check (opt)) {
-      MONGOC_ERROR ("Setting tlsDisableOCSPEndpointCheck has no effect when "
-                    "built against libtls");
-   }
-   RETURN ((mongoc_stream_t *) tls);
-}
-#endif /* MONGOC_ENABLE_SSL_LIBRESSL */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,37 +0,0 @@
-/*
- * Copyright 2009-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <mongoc/mongoc-prelude.h>
-
-#ifndef MONGOC_STREAM_TLS_LIBRESSL_H
-#define MONGOC_STREAM_TLS_LIBRESSL_H
-
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-
-#include <bson/bson.h>
-
-#include <mongoc/mongoc-macros.h>
-
-BSON_BEGIN_DECLS
-
-MONGOC_EXPORT (mongoc_stream_t *)
-mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client)
-   BSON_GNUC_DEPRECATED BSON_GNUC_WARN_UNUSED_RESULT;
-
-BSON_END_DECLS
-
-#endif /* MONGOC_ENABLE_SSL_LIBRESSL */
-#endif /* MONGOC_STREAM_TLS_LIBRESSL_H */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c	2025-06-19 15:42:22.000000000 +0000
@@ -33,7 +33,7 @@
 #include <mongoc/mongoc-openssl-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-log.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 #undef MONGOC_LOG_DOMAIN
@@ -215,7 +215,7 @@ mongoc_stream_tls_openssl_bio_read (BIO
       RETURN (-1);
    }
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, tls->timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, tls->timeout_msec))) {
       // CDRIVER-4589
       MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec);
       return -1;
@@ -235,7 +235,7 @@ mongoc_stream_tls_openssl_bio_read (BIO
       BIO_set_retry_read (openssl->bio);
    }
 
-   BSON_ASSERT (mcommon_in_range_signed (int, ret));
+   BSON_ASSERT (mlib_in_range (int, ret));
 
    RETURN ((int) ret);
 }
@@ -283,7 +283,7 @@ mongoc_stream_tls_openssl_bio_write (BIO
    iov.iov_base = (void *) buf;
    iov.iov_len = (size_t) len;
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, tls->timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, tls->timeout_msec))) {
       // CDRIVER-4589
       MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec);
       RETURN (-1);
@@ -308,7 +308,7 @@ mongoc_stream_tls_openssl_bio_write (BIO
       BIO_set_retry_write (openssl->bio);
    }
 
-   BSON_ASSERT (mcommon_in_range_signed (int, ret));
+   BSON_ASSERT (mlib_in_range (int, ret));
 
    RETURN ((int) ret);
 }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c	2025-06-19 15:42:22.000000000 +0000
@@ -39,10 +39,10 @@
 #include <mongoc/mongoc-openssl-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-log.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 
 #include <common-macros-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include <inttypes.h>
 
@@ -212,7 +212,7 @@ _mongoc_stream_tls_openssl_write (mongoc
       expire = bson_get_monotonic_time () + (tls->timeout_msec * 1000);
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (int, buf_len));
+   BSON_ASSERT (mlib_in_range (int, buf_len));
    ret = BIO_write (openssl->bio, buf, (int) buf_len);
 
    if (ret <= 0) {
@@ -223,7 +223,7 @@ _mongoc_stream_tls_openssl_write (mongoc
       now = bson_get_monotonic_time ();
 
       if ((expire - now) < 0) {
-         if (mcommon_cmp_less_su (ret, buf_len)) {
+         if (mlib_cmp (ret, <, buf_len)) {
             mongoc_counter_streams_timeout_inc ();
          }
 
@@ -334,7 +334,7 @@ _mongoc_stream_tls_openssl_writev (mongo
              * if we didn't buffer and have to send out of the iovec */
 
             child_ret = _mongoc_stream_tls_openssl_write (tls, to_write, to_write_len);
-            if (mcommon_cmp_not_equal_su (child_ret, to_write_len)) {
+            if (mlib_cmp (child_ret, !=, to_write_len)) {
                TRACE ("Got child_ret: %zd while to_write_len is: %zu", child_ret, to_write_len);
             }
 
@@ -349,7 +349,7 @@ _mongoc_stream_tls_openssl_writev (mongo
 
             ret += child_ret;
 
-            if (mcommon_cmp_less_su (child_ret, to_write_len)) {
+            if (mlib_cmp (child_ret, <, to_write_len)) {
                /* we timed out, so send back what we could send */
 
                RETURN (ret);
@@ -540,12 +540,12 @@ _mongoc_stream_tls_openssl_set_verify_ce
       return false;
    }
 
-   bson_set_error (error,
-                   MONGOC_ERROR_STREAM,
-                   MONGOC_ERROR_STREAM_SOCKET,
-                   "TLS handshake failed: certificate verify failed (%ld): %s",
-                   verify_result,
-                   X509_verify_cert_error_string (verify_result));
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_STREAM,
+                      MONGOC_ERROR_STREAM_SOCKET,
+                      "TLS handshake failed: certificate verify failed (%ld): %s",
+                      verify_result,
+                      X509_verify_cert_error_string (verify_result));
 
    return true;
 }
@@ -572,7 +572,7 @@ _mongoc_stream_tls_openssl_handshake (mo
 #ifdef MONGOC_ENABLE_OCSP_OPENSSL
       /* Validate OCSP */
       if (openssl->ocsp_opts && 1 != _mongoc_ocsp_tlsext_status (ssl, openssl->ocsp_opts)) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: Failed OCSP verification");
          RETURN (false);
       }
@@ -588,10 +588,10 @@ _mongoc_stream_tls_openssl_handshake (mo
       }
 
       /* Otherwise, use simple error message. */
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "TLS handshake failed: Failed certificate verification");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "TLS handshake failed: Failed certificate verification");
 
       RETURN (false);
    }
@@ -618,34 +618,19 @@ _mongoc_stream_tls_openssl_handshake (mo
 
    /* Otherwise, try to relay error info from OpenSSL. */
    if (ERR_peek_error () != 0) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "TLS handshake failed: %s",
-                      ERR_error_string (ERR_get_error (), NULL));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "TLS handshake failed: %s",
+                         ERR_error_string (ERR_get_error (), NULL));
       RETURN (false);
    }
 
    /* Otherwise, use simple error info. */
    {
-#ifdef _WIN32
-      LPTSTR msg = NULL;
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
-                     NULL,
-                     errno, /* WSAETIMEDOUT */
-                     LANG_NEUTRAL,
-                     (LPTSTR) &msg,
-                     0,
-                     NULL);
-#else
-      const char *msg = strerror (errno); /* ETIMEDOUT */
-#endif
-
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: %s", msg);
-
-#ifdef _WIN32
-      LocalFree (msg);
-#endif
+      char errmsg_buf[BSON_ERROR_BUFFER_SIZE];
+      char *msg = bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf);
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: %s", msg);
    }
 
    RETURN (false);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -44,6 +44,7 @@ typedef enum {
 typedef struct {
    CredHandle cred_handle;
    TimeStamp time_stamp;
+   PCCERT_CONTEXT cert; /* Owning. Optional client cert. */
 } mongoc_secure_channel_cred;
 
 typedef struct {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c	2025-06-19 15:42:22.000000000 +0000
@@ -64,7 +64,7 @@
 #include <mongoc/mongoc-secure-channel-private.h>
 #include <mongoc/mongoc-ssl.h>
 #include <mongoc/mongoc-ssl-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-counters-private.h>
 #include <mongoc/mongoc-errno-private.h>
 
@@ -162,6 +162,7 @@ _mongoc_stream_tls_secure_channel_destro
       /* if the handle was not cached and the refcount is zero */
       TRACE ("%s", "clear credential handle");
       FreeCredentialsHandle (&secure_channel->cred->cred_handle);
+      CertFreeCertificateContext (secure_channel->cred->cert);
       bson_free (secure_channel->cred);
    }
 
@@ -811,7 +812,7 @@ mongoc_stream_tls_secure_channel_handsha
    *events = 0;
 
    if (error && !error->code) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed");
    }
 
    RETURN (false);
@@ -912,15 +913,15 @@ mongoc_stream_tls_secure_channel_new (mo
    }
 
    if (opt->ca_file) {
-      mongoc_secure_channel_setup_ca (secure_channel, opt);
+      mongoc_secure_channel_setup_ca (opt);
    }
 
    if (opt->crl_file) {
-      mongoc_secure_channel_setup_crl (secure_channel, opt);
+      mongoc_secure_channel_setup_crl (opt);
    }
 
    if (opt->pem_file) {
-      cert = mongoc_secure_channel_setup_certificate (secure_channel, opt);
+      cert = mongoc_secure_channel_setup_certificate (opt);
 
       if (cert) {
          schannel_cred.cCreds = 1;
@@ -932,6 +933,10 @@ mongoc_stream_tls_secure_channel_new (mo
    schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT;
 
    secure_channel->cred = (mongoc_secure_channel_cred *) bson_malloc0 (sizeof (mongoc_secure_channel_cred));
+   if (cert) {
+      // Store client cert to free later.
+      secure_channel->cred->cert = cert;
+   }
 
    /* Example:
     *   https://msdn.microsoft.com/en-us/library/windows/desktop/aa375454%28v=vs.85%29.aspx
@@ -949,19 +954,10 @@ mongoc_stream_tls_secure_channel_new (mo
                                            &secure_channel->cred->time_stamp); /* certificate expiration time */
 
    if (sspi_status != SEC_E_OK) {
-      LPTSTR msg = NULL;
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
-                     NULL,
-                     GetLastError (),
-                     LANG_NEUTRAL,
-                     (LPTSTR) &msg,
-                     0,
-                     NULL);
-      MONGOC_ERROR ("Failed to initialize security context, error code: 0x%04X%04X: '%s'",
-                    (unsigned int) (sspi_status >> 16) & 0xffff,
-                    (unsigned int) sspi_status & 0xffff,
-                    msg);
-      LocalFree (msg);
+      // Cast signed SECURITY_STATUS to unsigned DWORD. FormatMessage expects DWORD.
+      char *msg = mongoc_winerr_to_string ((DWORD) sspi_status);
+      MONGOC_ERROR ("Failed to initialize security context: %s", msg);
+      bson_free (msg);
       RETURN (NULL);
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -24,8 +24,12 @@
 
 #include <Security/Security.h>
 
+#include <common-macros-private.h>
+
 BSON_BEGIN_DECLS
 
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+BEGIN_IGNORE_DEPRECATIONS
 
 /**
  * mongoc_stream_tls_secure_transport_t:
@@ -38,6 +42,8 @@ typedef struct {
    CFMutableArrayRef my_cert;
 } mongoc_stream_tls_secure_transport_t;
 
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+END_IGNORE_DEPRECATIONS
 
 BSON_END_DECLS
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c	2025-06-19 15:42:22.000000000 +0000
@@ -30,17 +30,21 @@
 #include <mongoc/mongoc-secure-transport-private.h>
 #include <mongoc/mongoc-ssl.h>
 #include <mongoc/mongoc-ssl-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-counters-private.h>
 #include <mongoc/mongoc-stream-tls.h>
 #include <mongoc/mongoc-stream-tls-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-stream-tls-secure-transport-private.h>
+#include <common-macros-private.h>
 #include <common-string-private.h>
 
 #undef MONGOC_LOG_DOMAIN
 #define MONGOC_LOG_DOMAIN "stream-tls-secure_transport"
 
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+BEGIN_IGNORE_DEPRECATIONS
+
 static void
 _mongoc_stream_tls_secure_transport_destroy (mongoc_stream_t *stream)
 {
@@ -139,7 +143,7 @@ _mongoc_stream_tls_secure_transport_writ
       now = bson_get_monotonic_time ();
 
       if ((expire - now) < 0) {
-         if (write_ret < buf_len) {
+         if (write_ret < (ssize_t) buf_len) {
             mongoc_counter_streams_timeout_inc ();
          }
 
@@ -197,7 +201,8 @@ _mongoc_stream_tls_secure_transport_writ
       iov_pos = 0;
 
       while (iov_pos < iov[i].iov_len) {
-         if (buf_head != buf_tail || ((i + 1 < iovcnt) && ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) {
+         if (buf_head != buf_tail ||
+             ((i + 1 < iovcnt) && ((size_t) (buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) {
             /* If we have either of:
              *   - buffered bytes already
              *   - another iovec to send after this one and we don't have more
@@ -205,7 +210,7 @@ _mongoc_stream_tls_secure_transport_writ
              *
              * copy into the buffer */
 
-            bytes = BSON_MIN (iov[i].iov_len - iov_pos, buf_end - buf_tail);
+            bytes = BSON_MIN (iov[i].iov_len - iov_pos, (size_t) (buf_end - buf_tail));
 
             memcpy (buf_tail, (char *) iov[i].iov_base + iov_pos, bytes);
             buf_tail += bytes;
@@ -240,7 +245,7 @@ _mongoc_stream_tls_secure_transport_writ
 
             ret += child_ret;
 
-            if (child_ret < to_write_len) {
+            if ((size_t) child_ret < to_write_len) {
                /* we timed out, so send back what we could send */
 
                RETURN (ret);
@@ -400,7 +405,7 @@ _set_error_from_osstatus (OSStatus statu
 
    err = SecCopyErrorMessageString (status, NULL);
    err_str = _mongoc_cfstringref_to_cstring (err);
-   bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "%s: %s (%d)", prefix, err_str, status);
+   _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "%s: %s (%d)", prefix, err_str, status);
 
    bson_free (err_str);
    CFRelease (err);
@@ -538,7 +543,7 @@ _verify_peer (mongoc_stream_t *stream, b
 
    if (trust_result != kSecTrustResultProceed && trust_result != kSecTrustResultUnspecified) {
       char *reason = explain_trust_result (trust, trust_result);
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed (%s)", reason);
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed (%s)", reason);
       bson_free (reason);
       goto fail;
    }
@@ -700,4 +705,8 @@ mongoc_stream_tls_secure_transport_new (
    }
    RETURN ((mongoc_stream_t *) tls);
 }
+
+// CDRIVER-2722: Secure Transport is deprecated on MacOS.
+END_IGNORE_DEPRECATIONS
+
 #endif /* MONGOC_ENABLE_SSL_SECURE_TRANSPORT */
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,16 +24,13 @@
 
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-trace-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 
 #include <mongoc/mongoc-stream-tls-private.h>
 #include <mongoc/mongoc-stream-private.h>
 #if defined(MONGOC_ENABLE_SSL_OPENSSL)
 #include <mongoc/mongoc-stream-tls-openssl.h>
 #include <mongoc/mongoc-openssl-private.h>
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-#include <mongoc/mongoc-libressl-private.h>
-#include <mongoc/mongoc-stream-tls-libressl.h>
 #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
 #include <mongoc/mongoc-secure-transport-private.h>
 #include <mongoc/mongoc-stream-tls-secure-transport.h>
@@ -43,7 +40,7 @@
 #endif
 #include <mongoc/mongoc-stream-tls.h>
 #include <common-macros-private.h> // BEGIN_IGNORE_DEPRECATIONS
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #undef MONGOC_LOG_DOMAIN
 #define MONGOC_LOG_DOMAIN "stream-tls"
@@ -106,11 +103,11 @@ mongoc_stream_tls_handshake_block (mongo
             const int64_t now = bson_get_monotonic_time ();
             const int64_t remaining = expire - now;
             if (remaining < 0) {
-               bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake timed out.");
+               _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake timed out.");
                return false;
             } else {
                const int64_t msec = remaining / 1000;
-               BSON_ASSERT (mcommon_in_range_signed (int32_t, msec));
+               BSON_ASSERT (mlib_in_range (int32_t, msec));
                timeout_msec = (int32_t) msec;
             }
          }
@@ -119,46 +116,10 @@ mongoc_stream_tls_handshake_block (mongo
    } while (events && ret > 0);
 
    if (error && !error->code) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed.");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed.");
    }
    return false;
 }
-/**
- * Deprecated. Was never supposed to be part of the public API.
- * See mongoc_stream_tls_handshake.
- */
-bool
-mongoc_stream_tls_do_handshake (mongoc_stream_t *stream, int32_t timeout_msec)
-{
-   mongoc_stream_tls_t *stream_tls = (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream);
-
-   BSON_UNUSED (timeout_msec);
-
-   BSON_ASSERT (stream_tls);
-
-   MONGOC_ERROR ("This function doesn't do anything. Please call "
-                 "mongoc_stream_tls_handshake()");
-   return false;
-}
-
-
-/**
- * Deprecated. Was never supposed to be part of the public API.
- * See mongoc_stream_tls_handshake.
- */
-bool
-mongoc_stream_tls_check_cert (mongoc_stream_t *stream, const char *host)
-{
-   mongoc_stream_tls_t *stream_tls = (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream);
-
-   BSON_UNUSED (host);
-
-   BSON_ASSERT (stream_tls);
-
-   MONGOC_ERROR ("This function doesn't do anything. Please call "
-                 "mongoc_stream_tls_handshake()");
-   return false;
-}
 
 
 /*
@@ -207,10 +168,6 @@ mongoc_stream_tls_new_with_hostname (mon
 
 #if defined(MONGOC_ENABLE_SSL_OPENSSL)
    return mongoc_stream_tls_openssl_new (base_stream, host, opt, client);
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-   BEGIN_IGNORE_DEPRECATIONS
-   return mongoc_stream_tls_libressl_new (base_stream, host, opt, client);
-   END_IGNORE_DEPRECATIONS
 #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
    return mongoc_stream_tls_secure_transport_new (base_stream, host, opt, client);
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
@@ -270,10 +227,4 @@ mongoc_stream_tls_new_with_hostname_and_
 }
 #endif
 
-mongoc_stream_t *
-mongoc_stream_tls_new (mongoc_stream_t *base_stream, mongoc_ssl_opt_t *opt, int client)
-{
-   return mongoc_stream_tls_new_with_hostname (base_stream, NULL, opt, client);
-}
-
 #endif
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream-tls.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream-tls.h	2025-06-19 15:42:22.000000000 +0000
@@ -33,23 +33,16 @@ typedef struct _mongoc_stream_tls_t mong
 MONGOC_EXPORT (bool)
 mongoc_stream_tls_handshake (
    mongoc_stream_t *stream, const char *host, int32_t timeout_msec, int *events, bson_error_t *error);
+
 MONGOC_EXPORT (bool)
 mongoc_stream_tls_handshake_block (mongoc_stream_t *stream,
                                    const char *host,
                                    int32_t timeout_msec,
                                    bson_error_t *error);
-MONGOC_EXPORT (bool)
-mongoc_stream_tls_do_handshake (mongoc_stream_t *stream, int32_t timeout_msec)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_stream_tls_handshake);
-MONGOC_EXPORT (bool)
-mongoc_stream_tls_check_cert (mongoc_stream_t *stream, const char *host)
-   BSON_GNUC_DEPRECATED_FOR (mongoc_stream_tls_handshake);
+
 MONGOC_EXPORT (mongoc_stream_t *)
 mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client)
    BSON_GNUC_WARN_UNUSED_RESULT;
-MONGOC_EXPORT (mongoc_stream_t *)
-mongoc_stream_tls_new (mongoc_stream_t *base_stream, mongoc_ssl_opt_t *opt, int client) BSON_GNUC_WARN_UNUSED_RESULT
-   BSON_GNUC_DEPRECATED_FOR (mongoc_stream_tls_new_with_hostname);
 
 
 BSON_END_DECLS
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,7 @@
 
 #include <mongoc/mongoc-array-private.h>
 #include <mongoc/mongoc-buffer-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-errno-private.h>
 #include <mongoc/mongoc-flags.h>
 #include <mongoc/mongoc-log.h>
@@ -29,7 +29,7 @@
 #include <mongoc/mongoc-stream-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-util-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 #undef MONGOC_LOG_DOMAIN
@@ -414,13 +414,13 @@ _mongoc_stream_writev_full (
       total_bytes += iov[i].iov_len;
    }
 
-   if (BSON_UNLIKELY (!mcommon_in_range_signed (int32_t, timeout_msec))) {
+   if (BSON_UNLIKELY (!mlib_in_range (int32_t, timeout_msec))) {
       // CDRIVER-4589
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
-                      timeout_msec);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "timeout_msec value %" PRId64 " exceeds supported 32-bit range",
+                         timeout_msec);
       RETURN (false);
    }
 
@@ -434,26 +434,26 @@ _mongoc_stream_writev_full (
 
          errstr = bson_strerror_r (errno, buf, sizeof (buf));
 
-         bson_set_error (error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_SOCKET,
-                         "Failure during socket delivery: %s (%d)",
-                         errstr,
-                         errno);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_SOCKET,
+                            "Failure during socket delivery: %s (%d)",
+                            errstr,
+                            errno);
       }
 
       RETURN (false);
    }
 
-   if (mcommon_cmp_not_equal_su (r, total_bytes)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_SOCKET,
-                      "Failure to send all requested bytes (only sent: %" PRIu64 "/%zu in %" PRId64
-                      "ms) during socket delivery",
-                      (uint64_t) r,
-                      total_bytes,
-                      timeout_msec);
+   if (mlib_cmp (r, !=, total_bytes)) {
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_SOCKET,
+                         "Failure to send all requested bytes (only sent: %" PRIu64 "/%zu in %" PRId64
+                         "ms) during socket delivery",
+                         (uint64_t) r,
+                         total_bytes,
+                         timeout_msec);
 
       RETURN (false);
    }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-stream.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-stream.h	2025-06-19 15:42:22.000000000 +0000
@@ -37,19 +37,19 @@ typedef struct _mongoc_stream_poll_t {
 
 struct _mongoc_stream_t {
    int type;
-   void (*destroy) (mongoc_stream_t *stream);
-   int (*close) (mongoc_stream_t *stream);
-   int (*flush) (mongoc_stream_t *stream);
-   ssize_t (*writev) (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec);
-   ssize_t (*readv) (
+   void (BSON_CALL *destroy) (mongoc_stream_t *stream);
+   int (BSON_CALL *close) (mongoc_stream_t *stream);
+   int (BSON_CALL *flush) (mongoc_stream_t *stream);
+   ssize_t (BSON_CALL *writev) (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec);
+   ssize_t (BSON_CALL *readv) (
       mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec);
-   int (*setsockopt) (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen);
-   mongoc_stream_t *(*get_base_stream) (mongoc_stream_t *stream);
-   bool (*check_closed) (mongoc_stream_t *stream);
-   ssize_t (*poll) (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout);
-   void (*failed) (mongoc_stream_t *stream);
-   bool (*timed_out) (mongoc_stream_t *stream);
-   bool (*should_retry) (mongoc_stream_t *stream);
+   int (BSON_CALL *setsockopt) (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen);
+   mongoc_stream_t *(BSON_CALL *get_base_stream) (mongoc_stream_t *stream);
+   bool (BSON_CALL *check_closed) (mongoc_stream_t *stream);
+   ssize_t (BSON_CALL *poll) (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout);
+   void (BSON_CALL *failed) (mongoc_stream_t *stream);
+   bool (BSON_CALL *timed_out) (mongoc_stream_t *stream);
+   bool (BSON_CALL *should_retry) (mongoc_stream_t *stream);
    void *padding[3];
 };
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-structured-log.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-structured-log.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-structured-log.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-structured-log.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <mlib/intencode.h>
 #include <common-atomic-private.h>
 #include <common-oid-private.h>
 #include <common-string-private.h>
@@ -25,6 +26,7 @@
 #include <mongoc/mongoc-topology-private.h>
 #include <mongoc/mongoc-structured-log.h>
 #include <mongoc/mongoc-util-private.h>
+#include <mlib/loop.h>
 
 #define STRUCTURED_LOG_COMPONENT_TABLE_SIZE (1 + (size_t) MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION)
 
@@ -159,7 +161,7 @@ mongoc_structured_log_opts_set_max_level
                                                              mongoc_structured_log_level_t level)
 {
    BSON_ASSERT_PARAM (opts);
-   for (int component = 0; component < STRUCTURED_LOG_COMPONENT_TABLE_SIZE; component++) {
+   mlib_foreach_urange (component, STRUCTURED_LOG_COMPONENT_TABLE_SIZE) {
       if (!mongoc_structured_log_opts_set_max_level_for_component (
              opts, (mongoc_structured_log_component_t) component, level)) {
          // Fine to stop on the first error, always means 'level' is wrong and none of these will succeed.
@@ -310,8 +312,7 @@ mongoc_structured_log_opts_set_max_docum
    } else {
       char *endptr;
       long int_value = strtol (max_length_str, &endptr, 10);
-      if (int_value >= 0 && endptr != max_length_str && *endptr == '\0' &&
-          mcommon_in_range_signed (size_t, int_value) &&
+      if (int_value >= 0 && endptr != max_length_str && *endptr == '\0' && mlib_in_range (size_t, int_value) &&
           mongoc_structured_log_opts_set_max_document_length (opts, (size_t) int_value)) {
          result = true;
       }
@@ -349,7 +350,7 @@ mongoc_structured_log_opts_set_max_level
       all_ok = false;
    }
 
-   for (int component = 0; component < STRUCTURED_LOG_COMPONENT_TABLE_SIZE; component++) {
+   mlib_foreach_urange (component, STRUCTURED_LOG_COMPONENT_TABLE_SIZE) {
       if (_mongoc_structured_log_get_log_level_from_env (
              gStructuredLogComponentEnvVars[component], &level, &err_flag_per_component_atomic[component])) {
          BSON_ASSERT (mongoc_structured_log_opts_set_max_level_for_component (
@@ -604,11 +605,9 @@ _mongoc_structured_log_command_with_payl
       BSON_ASSERT (doc_begin != doc_end);
 
       const uint8_t *doc_ptr = doc_begin;
-      int32_t doc_len;
 
-      while (doc_ptr + sizeof doc_len <= doc_end) {
-         memcpy (&doc_len, doc_ptr, sizeof doc_len);
-         doc_len = BSON_UINT32_FROM_LE (doc_len);
+      while (doc_ptr + sizeof (int32_t) <= doc_end) {
+         const int32_t doc_len = mlib_read_i32le (doc_ptr);
 
          bson_t doc;
          if (doc_len < 5 || (size_t) doc_len > (size_t) (doc_end - doc_ptr) ||
@@ -897,6 +896,7 @@ _mongoc_structured_log_append_error (bso
                                      const mongoc_structured_log_builder_stage_t *stage,
                                      const mongoc_structured_log_opts_t *opts)
 {
+   BSON_UNUSED (opts);
    const char *key_or_null = stage->arg1.utf8;
    const bson_error_t *error_or_null = stage->arg2.error;
    if (key_or_null) {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-structured-log.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-structured-log.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-structured-log.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-structured-log.h	2025-06-19 15:42:22.000000000 +0000
@@ -48,7 +48,7 @@ typedef struct mongoc_structured_log_ent
 
 typedef struct mongoc_structured_log_opts_t mongoc_structured_log_opts_t;
 
-typedef void (*mongoc_structured_log_func_t) (const mongoc_structured_log_entry_t *entry, void *user_data);
+typedef void (BSON_CALL *mongoc_structured_log_func_t) (const mongoc_structured_log_entry_t *entry, void *user_data);
 
 MONGOC_EXPORT (mongoc_structured_log_opts_t *)
 mongoc_structured_log_opts_new (void);
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-description.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-description.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-description.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-description.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,7 +16,7 @@
 
 #include <common-oid-private.h>
 #include <mongoc/mongoc-array-private.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-server-description-private.h>
 #include <mongoc/mongoc-topology-description-apm-private.h>
 #include <mongoc/mongoc-trace-private.h>
@@ -682,24 +682,24 @@ _mongoc_topology_description_validate_ma
    }
 
    if (max_staleness_seconds * 1000 < td->heartbeat_msec + MONGOC_IDLE_WRITE_PERIOD_MS) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "maxStalenessSeconds is set to %" PRId64 ", it must be at least heartbeatFrequencyMS (%" PRId64
-                      ") + server's idle write period (%d seconds)",
-                      max_staleness_seconds,
-                      td->heartbeat_msec,
-                      MONGOC_IDLE_WRITE_PERIOD_MS / 1000);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "maxStalenessSeconds is set to %" PRId64 ", it must be at least heartbeatFrequencyMS (%" PRId64
+                         ") + server's idle write period (%d seconds)",
+                         max_staleness_seconds,
+                         td->heartbeat_msec,
+                         MONGOC_IDLE_WRITE_PERIOD_MS / 1000);
       return false;
    }
 
    if (max_staleness_seconds < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "maxStalenessSeconds is set to %" PRId64 ", it must be at least %d seconds",
-                      max_staleness_seconds,
-                      MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "maxStalenessSeconds is set to %" PRId64 ", it must be at least %d seconds",
+                         max_staleness_seconds,
+                         MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
       return false;
    }
 
@@ -1093,7 +1093,7 @@ mongoc_topology_description_server_by_id
 
    sd = mongoc_set_get_const (mc_tpld_servers_const (td), id);
    if (!sd) {
-      bson_set_error (
+      _mongoc_set_error (
          error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NOT_ESTABLISHED, "Could not find description for node %u", id);
    }
 
@@ -1646,7 +1646,7 @@ _mongoc_topology_description_update_rs_f
          _mongoc_topology_description_set_max_set_version (topology, server);
 
       } else {
-         bson_set_error (
+         _mongoc_set_error (
             &error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "member's setVersion or electionId is stale");
          mongoc_topology_description_invalidate_server (topology, log_and_monitor, server->id, &error);
          _update_rs_type (topology);
@@ -1662,7 +1662,7 @@ _mongoc_topology_description_update_rs_f
           */
          if (_mongoc_topology_description_later_election (topology, server)) {
             // stale primary code return:
-            bson_set_error (
+            _mongoc_set_error (
                &error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "member's setVersion or electionId is stale");
             mongoc_topology_description_invalidate_server (topology, log_and_monitor, server->id, &error);
             _update_rs_type (topology);
@@ -2095,24 +2095,24 @@ _mongoc_topology_description_check_compa
       }
 
       if (sd->min_wire_version > WIRE_VERSION_MAX) {
-         bson_set_error (&td->compatibility_error,
-                         MONGOC_ERROR_PROTOCOL,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "Server at %s requires wire version %d,"
-                         " but this version of libmongoc only supports up to %d",
-                         sd->host.host_and_port,
-                         sd->min_wire_version,
-                         WIRE_VERSION_MAX);
+         _mongoc_set_error (&td->compatibility_error,
+                            MONGOC_ERROR_PROTOCOL,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "Server at %s requires wire version %d,"
+                            " but this version of libmongoc only supports up to %d",
+                            sd->host.host_and_port,
+                            sd->min_wire_version,
+                            WIRE_VERSION_MAX);
       } else if (sd->max_wire_version < WIRE_VERSION_MIN) {
-         bson_set_error (&td->compatibility_error,
-                         MONGOC_ERROR_PROTOCOL,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "Server at %s reports wire version %d, but this"
-                         " version of libmongoc requires at least %d (MongoDB %s)",
-                         sd->host.host_and_port,
-                         sd->max_wire_version,
-                         WIRE_VERSION_MIN,
-                         _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN));
+         _mongoc_set_error (&td->compatibility_error,
+                            MONGOC_ERROR_PROTOCOL,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "Server at %s reports wire version %d, but this"
+                            " version of libmongoc requires at least %d (MongoDB %s)",
+                            sd->host.host_and_port,
+                            sd->max_wire_version,
+                            WIRE_VERSION_MIN,
+                            _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN));
       }
    }
 }
@@ -2197,19 +2197,19 @@ mongoc_topology_description_handle_hello
 
       if (!sd->set_name) {
          wrong_set_name = true;
-         bson_set_error (&set_name_err,
-                         MONGOC_ERROR_SERVER_SELECTION,
-                         MONGOC_ERROR_SERVER_SELECTION_FAILURE,
-                         "no reported set name, but expected '%s'",
-                         topology->set_name);
+         _mongoc_set_error (&set_name_err,
+                            MONGOC_ERROR_SERVER_SELECTION,
+                            MONGOC_ERROR_SERVER_SELECTION_FAILURE,
+                            "no reported set name, but expected '%s'",
+                            topology->set_name);
       } else if (0 != strcmp (sd->set_name, topology->set_name)) {
          wrong_set_name = true;
-         bson_set_error (&set_name_err,
-                         MONGOC_ERROR_SERVER_SELECTION,
-                         MONGOC_ERROR_SERVER_SELECTION_FAILURE,
-                         "reported set name '%s' does not match '%s'",
-                         sd->set_name,
-                         topology->set_name);
+         _mongoc_set_error (&set_name_err,
+                            MONGOC_ERROR_SERVER_SELECTION,
+                            MONGOC_ERROR_SERVER_SELECTION_FAILURE,
+                            "reported set name '%s' does not match '%s'",
+                            sd->set_name,
+                            topology->set_name);
       }
 
       if (wrong_set_name) {
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-description.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-description.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-description.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-description.h	2025-06-19 15:42:22.000000000 +0000
@@ -46,8 +46,8 @@ MONGOC_EXPORT (const char *)
 mongoc_topology_description_type (const mongoc_topology_description_t *td);
 
 MONGOC_EXPORT (mongoc_server_description_t **)
-mongoc_topology_description_get_servers (const mongoc_topology_description_t *td,
-                                         size_t *n) BSON_GNUC_WARN_UNUSED_RESULT;
+mongoc_topology_description_get_servers (const mongoc_topology_description_t *td, size_t *n)
+   BSON_GNUC_WARN_UNUSED_RESULT;
 
 BSON_END_DECLS
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -20,6 +20,7 @@
 #define MONGOC_TOPOLOGY_PRIVATE_H
 
 #include <mongoc/mongoc-config.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-topology-scanner-private.h>
 #include <mongoc/mongoc-server-description-private.h>
 #include <mongoc/mongoc-topology-description-private.h>
@@ -625,7 +626,7 @@ _mongoc_topology_invalidate_server (mong
 {
    bson_error_t error;
    mc_tpld_modification tdmod = mc_tpld_modify_begin (topology);
-   bson_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "invalidated");
+   _mongoc_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "invalidated");
    mongoc_topology_description_invalidate_server (tdmod.new_td, &topology->log_and_monitor, server_id, &error);
    mc_tpld_modify_commit (tdmod);
 }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-scanner.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-scanner.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology-scanner.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology-scanner.c	2025-06-19 15:42:22.000000000 +0000
@@ -17,7 +17,7 @@
 #include <bson/bson.h>
 
 #include <mongoc/mongoc-config.h>
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-topology-scanner-private.h>
 #include <mongoc/mongoc-stream-private.h>
@@ -45,7 +45,7 @@
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-structured-log-private.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-atomic-private.h>
 
 #include <inttypes.h>
@@ -726,12 +726,12 @@ _async_error_or_timeout (mongoc_async_cm
          node->successful_dns_result = NULL;
       }
 
-      bson_set_error (&node->last_error,
-                      MONGOC_ERROR_CLIENT,
-                      MONGOC_ERROR_STREAM_CONNECT,
-                      "%s calling hello on \'%s\'",
-                      message,
-                      node->host.host_and_port);
+      _mongoc_set_error (&node->last_error,
+                         MONGOC_ERROR_CLIENT,
+                         MONGOC_ERROR_STREAM_CONNECT,
+                         "%s calling hello on \'%s\'",
+                         message,
+                         node->host.host_and_port);
 
       _mongoc_topology_scanner_monitor_heartbeat_failed (ts, &node->host, &node->last_error, duration_usec);
 
@@ -870,7 +870,7 @@ mongoc_topology_scanner_node_setup_tcp (
    if (!node->dns_results) {
       // Expect no truncation.
       int req = bson_snprintf (portstr, sizeof portstr, "%hu", host->port);
-      BSON_ASSERT (mcommon_cmp_less_su (req, sizeof portstr));
+      BSON_ASSERT (mlib_cmp (req, <, sizeof portstr));
 
       memset (&hints, 0, sizeof hints);
       hints.ai_family = host->family;
@@ -882,7 +882,7 @@ mongoc_topology_scanner_node_setup_tcp (
 
       if (s != 0) {
          mongoc_counter_dns_failure_inc ();
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve '%s'", host->host);
          RETURN (false);
       }
@@ -915,7 +915,7 @@ mongoc_topology_scanner_node_connect_uni
 {
 #ifdef _WIN32
    ENTRY;
-   bson_set_error (
+   _mongoc_set_error (
       error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "UNIX domain sockets not supported on win32.");
    RETURN (false);
 #else
@@ -933,15 +933,16 @@ mongoc_topology_scanner_node_connect_uni
    // Expect no truncation.
    int req = bson_snprintf (saddr.sun_path, sizeof saddr.sun_path - 1, "%s", host->host);
 
-   if (mcommon_cmp_greater_equal_su (req, sizeof saddr.sun_path - 1)) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to define socket address path.");
+   if (mlib_cmp (req, >=, sizeof saddr.sun_path - 1)) {
+      _mongoc_set_error (
+         error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to define socket address path.");
       RETURN (false);
    }
 
    sock = mongoc_socket_new (AF_UNIX, SOCK_STREAM, 0);
 
    if (sock == NULL) {
-      bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket.");
+      _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket.");
       RETURN (false);
    }
 
@@ -951,11 +952,11 @@ mongoc_topology_scanner_node_connect_uni
 
       errstr = bson_strerror_r (mongoc_socket_errno (sock), buf, sizeof (buf));
 
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_CONNECT,
-                      "Failed to connect to UNIX domain socket: %s",
-                      errstr);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_CONNECT,
+                         "Failed to connect to UNIX domain socket: %s",
+                         errstr);
       mongoc_socket_destroy (sock);
       RETURN (false);
    }
@@ -966,7 +967,7 @@ mongoc_topology_scanner_node_connect_uni
          node, stream, false /* is_setup_done */, NULL /* dns result */, 0 /* delay */, true /* use_handshake */);
       RETURN (true);
    }
-   bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to create TLS stream");
+   _mongoc_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to create TLS stream");
    RETURN (false);
 #endif
 }
@@ -1188,6 +1189,7 @@ _mongoc_topology_scanner_finish (mongoc_
          /* last error domain and code win */
          error->domain = node->last_error.domain;
          error->code = node->last_error.code;
+         error->reserved = node->last_error.reserved;
       }
    }
 
@@ -1232,7 +1234,7 @@ mongoc_topology_scanner_get_error (mongo
    BSON_ASSERT (ts);
    BSON_ASSERT (error);
 
-   memcpy (error, &ts->error, sizeof (bson_error_t));
+   *error = ts->error;
 }
 
 /*
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-topology.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-topology.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,6 @@
 #include <mongoc/mongoc-handshake.h>
 #include <mongoc/mongoc-handshake-private.h>
 
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-topology-private.h>
@@ -38,7 +37,7 @@
 
 #include <stdint.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-oid-private.h>
 
 static void
@@ -624,7 +623,7 @@ mongoc_topology_new (const mongoc_uri_t
 
    size_t hl_array_size = 0u;
 
-   BSON_ASSERT (mcommon_in_range_signed (size_t, td->max_hosts));
+   BSON_ASSERT (mlib_in_range (size_t, td->max_hosts));
    const mongoc_host_list_t *const *hl_array = _mongoc_apply_srv_max_hosts (hl, (size_t) td->max_hosts, &hl_array_size);
 
    for (size_t idx = 0u; idx < hl_array_size; ++idx) {
@@ -753,10 +752,10 @@ mongoc_topology_apply_scanned_srv_hosts
       mongoc_topology_description_reconcile (td, log_and_monitor, valid_hosts);
       had_valid_hosts = true;
    } else {
-      bson_set_error (error,
-                      MONGOC_ERROR_STREAM,
-                      MONGOC_ERROR_STREAM_NAME_RESOLUTION,
-                      "SRV response did not contain any valid hosts");
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_STREAM,
+                         MONGOC_ERROR_STREAM_NAME_RESOLUTION,
+                         "SRV response did not contain any valid hosts");
    }
 
    _mongoc_host_list_destroy_all (valid_hosts);
@@ -964,7 +963,7 @@ mongoc_topology_compatible (const mongoc
    if (max_staleness_seconds != MONGOC_NO_MAX_STALENESS) {
       /* shouldn't happen if we've properly enforced wire version */
       if (!mongoc_topology_description_all_sds_have_write_date (td)) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, "Not all servers have lastWriteDate");
          return false;
       }
@@ -982,14 +981,14 @@ static void
 _mongoc_server_selection_error (const char *msg, const bson_error_t *scanner_error, bson_error_t *error)
 {
    if (scanner_error && scanner_error->code) {
-      bson_set_error (error,
-                      MONGOC_ERROR_SERVER_SELECTION,
-                      MONGOC_ERROR_SERVER_SELECTION_FAILURE,
-                      "%s: %s",
-                      msg,
-                      scanner_error->message);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_SERVER_SELECTION,
+                         MONGOC_ERROR_SERVER_SELECTION_FAILURE,
+                         "%s: %s",
+                         msg,
+                         scanner_error->message);
    } else {
-      bson_set_error (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "%s", msg);
+      _mongoc_set_error (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "%s", msg);
    }
 }
 
@@ -1081,18 +1080,18 @@ _mongoc_topology_select_server_id_loadba
       /* Use the same error domain / code that is returned in mongoc-cluster.c
        * when fetching a stream fails. */
       if (scanner_error.code) {
-         bson_set_error (error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
-                         "Could not establish stream for node %s: %s",
-                         node->host.host_and_port,
-                         scanner_error.message);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
+                            "Could not establish stream for node %s: %s",
+                            node->host.host_and_port,
+                            scanner_error.message);
       } else {
-         bson_set_error (error,
-                         MONGOC_ERROR_STREAM,
-                         MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
-                         "Could not establish stream for node %s",
-                         node->host.host_and_port);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_STREAM,
+                            MONGOC_ERROR_STREAM_NOT_ESTABLISHED,
+                            "Could not establish stream for node %s",
+                            node->host.host_and_port);
       }
       selected_server_id = 0;
       goto done;
@@ -1158,6 +1157,7 @@ mongoc_topology_select_server_id (mongoc
          mongoc_topology_scanner_get_error (ts, error);
          error->domain = MONGOC_ERROR_SERVER_SELECTION;
          error->code = MONGOC_ERROR_SERVER_SELECTION_FAILURE;
+         _mongoc_set_error_category (error, MONGOC_ERROR_CATEGORY);
       }
       server_id = 0;
       goto done;
@@ -1345,12 +1345,12 @@ mongoc_topology_select_server_id (mongoc
          server_id = 0;
          goto done;
       } else if (r) {
-         bson_set_error (error,
-                         MONGOC_ERROR_SERVER_SELECTION,
-                         MONGOC_ERROR_SERVER_SELECTION_FAILURE,
-                         "Unknown error '%d' received while waiting on "
-                         "thread condition",
-                         r);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_SERVER_SELECTION,
+                            MONGOC_ERROR_SERVER_SELECTION_FAILURE,
+                            "Unknown error '%d' received while waiting on "
+                            "thread condition",
+                            r);
          server_id = 0;
          goto done;
       }
@@ -1613,7 +1613,7 @@ _mongoc_topology_pop_server_session (mon
       }
 
       if (timeout == MONGOC_NO_SESSIONS) {
-         bson_set_error (
+         _mongoc_set_error (
             error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_SESSION_FAILURE, "Server does not support sessions");
          ss = NULL;
          goto done;
@@ -1953,6 +1953,7 @@ _topology_collect_errors (const mongoc_t
          /* The last error's code and domain wins. */
          error_out->code = error->code;
          error_out->domain = error->domain;
+         error_out->reserved = error->reserved;
       }
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-uri.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-uri.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-uri.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-uri.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,6 +25,7 @@
 #include <mongoc/mongoc-util-private.h>
 
 #include <mongoc/mongoc-config.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-host-list.h>
 #include <mongoc/mongoc-host-list-private.h>
 #include <mongoc/mongoc-log.h>
@@ -46,12 +47,12 @@ struct _mongoc_uri_t {
    bool is_srv;
    char srv[BSON_HOST_NAME_MAX + 1];
    mongoc_host_list_t *hosts;
-   char *username;
-   char *password;
+   char *username; // MongoCredential.username
+   char *password; // MongoCredential.password
    char *database;
-   bson_t raw;     /* Unparsed options, see mongoc_uri_parse_options */
-   bson_t options; /* Type-coerced and canonicalized options */
-   bson_t credentials;
+   bson_t raw;         // Unparsed options, see mongoc_uri_parse_options
+   bson_t options;     // Type-coerced and canonicalized options
+   bson_t credentials; // MongoCredential.source, MongoCredential.mechanism, and MongoCredential.mechanism_properties.
    bson_t compressors;
    mongoc_read_prefs_t *read_prefs;
    mongoc_read_concern_t *read_concern;
@@ -59,7 +60,7 @@ struct _mongoc_uri_t {
 };
 
 #define MONGOC_URI_ERROR(error, format, ...) \
-   bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, format, __VA_ARGS__)
+   _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, format, __VA_ARGS__)
 
 
 static const char *escape_instructions = "Percent-encode username and password"
@@ -86,16 +87,16 @@ mongoc_uri_do_unescape (char **str)
 }
 
 
-#define VALIDATE_SRV_ERR()                                                \
-   do {                                                                   \
-      bson_set_error (error,                                              \
-                      MONGOC_ERROR_STREAM,                                \
-                      MONGOC_ERROR_STREAM_NAME_RESOLUTION,                \
-                      "Invalid host \"%s\" returned for service \"%s\": " \
-                      "host must be subdomain of service name",           \
-                      host,                                               \
-                      srv_hostname);                                      \
-      return false;                                                       \
+#define VALIDATE_SRV_ERR()                                                   \
+   do {                                                                      \
+      _mongoc_set_error (error,                                              \
+                         MONGOC_ERROR_STREAM,                                \
+                         MONGOC_ERROR_STREAM_NAME_RESOLUTION,                \
+                         "Invalid host \"%s\" returned for service \"%s\": " \
+                         "host must be subdomain of service name",           \
+                         host,                                               \
+                         srv_hostname);                                      \
+      return false;                                                          \
    } while (0)
 
 
@@ -245,7 +246,7 @@ scan_to_unichar (const char *str, bson_u
       } else {
          const char *term_iter;
          for (term_iter = terminators; *term_iter; term_iter++) {
-            if (c == *term_iter) {
+            if (mlib_cmp (c, ==, *term_iter)) {
                return NULL;
             }
          }
@@ -515,25 +516,46 @@ mongoc_uri_parse_database (mongoc_uri_t
 static bool
 mongoc_uri_parse_auth_mechanism_properties (mongoc_uri_t *uri, const char *str)
 {
-   char *field;
-   char *value;
    const char *end_scan;
-   bson_t properties;
 
-   bson_init (&properties);
+   bson_t properties = BSON_INITIALIZER;
 
-   /* build up the properties document */
-   while ((field = scan_to_unichar (str, ':', "&", &end_scan))) {
+   // Key-value pairs are delimited by ','.
+   for (char *kvp; (kvp = scan_to_unichar (str, ',', "", &end_scan)); bson_free (kvp)) {
       str = end_scan + 1;
-      if (!(value = scan_to_unichar (str, ',', ":&", &end_scan))) {
-         value = bson_strdup (str);
-         str = "";
-      } else {
-         str = end_scan + 1;
+
+      char *const key = scan_to_unichar (kvp, ':', "", &end_scan);
+
+      // Found delimiter: split into key and value.
+      if (key) {
+         char *const value = bson_strdup (end_scan + 1);
+         BSON_APPEND_UTF8 (&properties, key, value);
+         bson_free (key);
+         bson_free (value);
+      }
+
+      // No delimiter: entire string is the key. Use empty string as value.
+      else {
+         BSON_APPEND_UTF8 (&properties, kvp, "");
+      }
+   }
+
+   // Last (or only) pair.
+   if (*str != '\0') {
+      char *const key = scan_to_unichar (str, ':', "", &end_scan);
+
+      // Found delimiter: split into key and value.
+      if (key) {
+         char *const value = bson_strdup (end_scan + 1);
+         BSON_APPEND_UTF8 (&properties, key, value);
+         bson_free (key);
+         bson_free (value);
+      }
+
+      // No delimiter: entire string is the key. Use empty string as value.
+      else {
+         BSON_APPEND_UTF8 (&properties, str, "");
       }
-      bson_append_utf8 (&properties, field, -1, value, -1);
-      bson_free (field);
-      bson_free (value);
    }
 
    /* append our auth properties to our credentials */
@@ -719,13 +741,8 @@ mongoc_uri_option_is_int32 (const char *
           !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTIMEOUTMS) ||
           !strcasecmp (key, MONGOC_URI_SOCKETCHECKINTERVALMS) || !strcasecmp (key, MONGOC_URI_SOCKETTIMEOUTMS) ||
           !strcasecmp (key, MONGOC_URI_LOCALTHRESHOLDMS) || !strcasecmp (key, MONGOC_URI_MAXPOOLSIZE) ||
-          !strcasecmp (key, MONGOC_URI_MAXSTALENESSSECONDS) || !strcasecmp (key, MONGOC_URI_MINPOOLSIZE) ||
-          !strcasecmp (key, MONGOC_URI_WAITQUEUETIMEOUTMS) || !strcasecmp (key, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) ||
-          !strcasecmp (key, MONGOC_URI_SRVMAXHOSTS);
-   /* Not including deprecated unimplemented options:
-    * - MONGOC_URI_MAXIDLETIMEMS
-    * - MONGOC_URI_WAITQUEUEMULTIPLE
-    */
+          !strcasecmp (key, MONGOC_URI_MAXSTALENESSSECONDS) || !strcasecmp (key, MONGOC_URI_WAITQUEUETIMEOUTMS) ||
+          !strcasecmp (key, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) || !strcasecmp (key, MONGOC_URI_SRVMAXHOSTS);
 }
 
 bool
@@ -737,11 +754,18 @@ mongoc_uri_option_is_int64 (const char *
 bool
 mongoc_uri_option_is_bool (const char *key)
 {
-   return !strcasecmp (key, MONGOC_URI_CANONICALIZEHOSTNAME) || !strcasecmp (key, MONGOC_URI_DIRECTCONNECTION) ||
-          !strcasecmp (key, MONGOC_URI_JOURNAL) || !strcasecmp (key, MONGOC_URI_RETRYREADS) ||
-          !strcasecmp (key, MONGOC_URI_RETRYWRITES) || !strcasecmp (key, MONGOC_URI_SAFE) ||
-          !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTRYONCE) || !strcasecmp (key, MONGOC_URI_TLS) ||
-          !strcasecmp (key, MONGOC_URI_TLSINSECURE) || !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) ||
+   // CDRIVER-5933
+   if (!strcasecmp (key, MONGOC_URI_CANONICALIZEHOSTNAME)) {
+      MONGOC_WARNING (MONGOC_URI_CANONICALIZEHOSTNAME " is deprecated, use " MONGOC_URI_AUTHMECHANISMPROPERTIES
+                                                      " with CANONICALIZE_HOST_NAME instead");
+      return true;
+   }
+
+   return !strcasecmp (key, MONGOC_URI_DIRECTCONNECTION) || !strcasecmp (key, MONGOC_URI_JOURNAL) ||
+          !strcasecmp (key, MONGOC_URI_RETRYREADS) || !strcasecmp (key, MONGOC_URI_RETRYWRITES) ||
+          !strcasecmp (key, MONGOC_URI_SAFE) || !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTRYONCE) ||
+          !strcasecmp (key, MONGOC_URI_TLS) || !strcasecmp (key, MONGOC_URI_TLSINSECURE) ||
+          !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) ||
           !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES) ||
           !strcasecmp (key, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) ||
           !strcasecmp (key, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || !strcasecmp (key, MONGOC_URI_LOADBALANCED) ||
@@ -1089,7 +1113,7 @@ mongoc_uri_apply_options (mongoc_uri_t *
             }
 
             if (!mongoc_uri_set_option_as_bool (uri, canon, bval)) {
-               bson_set_error (
+               _mongoc_set_error (
                   error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Failed to set %s to %d", canon, bval);
                return false;
             }
@@ -1121,9 +1145,15 @@ mongoc_uri_apply_options (mongoc_uri_t *
             MONGOC_WARNING ("authMechanismProperties SERVICE_NAME already set, "
                             "ignoring '%s'",
                             key);
-         } else if (!mongoc_uri_parse_auth_mechanism_properties (uri, tmp)) {
-            bson_free (tmp);
-            goto UNSUPPORTED_VALUE;
+         } else {
+            // CDRIVER-5933
+            MONGOC_WARNING (MONGOC_URI_GSSAPISERVICENAME " is deprecated, use " MONGOC_URI_AUTHMECHANISMPROPERTIES
+                                                         " with SERVICE_NAME instead");
+
+            if (!mongoc_uri_parse_auth_mechanism_properties (uri, tmp)) {
+               bson_free (tmp);
+               goto UNSUPPORTED_VALUE;
+            }
          }
          bson_free (tmp);
 
@@ -1285,71 +1315,453 @@ mongoc_uri_finalize_tls (mongoc_uri_t *u
 }
 
 
+typedef enum _mongoc_uri_finalize_validate {
+   _mongoc_uri_finalize_allowed,
+   _mongoc_uri_finalize_required,
+   _mongoc_uri_finalize_prohibited,
+} mongoc_uri_finalize_validate;
+
+
 static bool
-mongoc_uri_finalize_auth (mongoc_uri_t *uri, bson_error_t *error)
+_finalize_auth_username (const char *username,
+                         const char *mechanism,
+                         mongoc_uri_finalize_validate validate,
+                         bson_error_t *error)
+{
+   BSON_OPTIONAL_PARAM (username);
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_OPTIONAL_PARAM (error);
+
+   switch (validate) {
+   case _mongoc_uri_finalize_required:
+      if (!username || strlen (username) == 0u) {
+         MONGOC_URI_ERROR (error, "'%s' authentication mechanism requires a username", mechanism);
+         return false;
+      }
+      break;
+
+   case _mongoc_uri_finalize_prohibited:
+      if (username) {
+         MONGOC_URI_ERROR (error, "'%s' authentication mechanism does not accept a username", mechanism);
+         return false;
+      }
+      break;
+
+   case _mongoc_uri_finalize_allowed:
+   default:
+      if (username && strlen (username) == 0u) {
+         MONGOC_URI_ERROR (error, "'%s' authentication mechanism requires a non-empty username", mechanism);
+         return false;
+      }
+      break;
+   }
+
+   return true;
+}
+
+static bool
+_finalize_auth_source_external (const char *source, const char *mechanism, bson_error_t *error)
 {
-   bson_iter_t iter;
-   const char *source = NULL;
-   const bool require_auth = uri->username != NULL;
+   BSON_OPTIONAL_PARAM (source);
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_OPTIONAL_PARAM (error);
+
+   if (source && strcasecmp (source, "$external") != 0) {
+      MONGOC_URI_ERROR (error,
+                        "'%s' authentication mechanism requires \"$external\" authSource, but \"%s\" was specified",
+                        mechanism,
+                        source);
+      return false;
+   }
+
+   return true;
+}
+
+static bool
+_finalize_auth_password (const char *password,
+                         const char *mechanism,
+                         mongoc_uri_finalize_validate validate,
+                         bson_error_t *error)
+{
+   BSON_OPTIONAL_PARAM (password);
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_OPTIONAL_PARAM (error);
+
+   switch (validate) {
+   case _mongoc_uri_finalize_required:
+      // Passwords may be zero length.
+      if (!password) {
+         MONGOC_URI_ERROR (error, "'%s' authentication mechanism requires a password", mechanism);
+         return false;
+      }
+      break;
+
+   case _mongoc_uri_finalize_prohibited:
+      if (password) {
+         MONGOC_URI_ERROR (error, "'%s' authentication mechanism does not accept a password", mechanism);
+         return false;
+      }
+      break;
 
-   if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) {
-      source = bson_iter_utf8 (&iter, NULL);
+   case _mongoc_uri_finalize_allowed:
+   default:
+      break;
    }
 
-   if (mongoc_uri_get_auth_mechanism (uri)) {
-      /* authSource with GSSAPI or X509 should always be external */
-      if (!strcasecmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI") ||
-          !strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509")) {
-         if (source) {
-            if (strcasecmp (source, "$external")) {
-               MONGOC_URI_ERROR (error, "%s", "GSSAPI and X509 require \"$external\" authSource");
+   return true;
+}
+
+typedef struct __supported_mechanism_properties {
+   const char *name;
+   bson_type_t type;
+} supported_mechanism_properties;
+
+static bool
+_supported_mechanism_properties_check (const supported_mechanism_properties *supported_properties,
+                                       const bson_t *mechanism_properties,
+                                       const char *mechanism,
+                                       bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (supported_properties);
+   BSON_ASSERT_PARAM (mechanism_properties);
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_ASSERT_PARAM (error);
+
+   bson_iter_t iter;
+   BSON_ASSERT (bson_iter_init (&iter, mechanism_properties));
+
+   // For each element in `MongoCredential.mechanism_properties`...
+   while (bson_iter_next (&iter)) {
+      const char *const key = bson_iter_key (&iter);
+
+      // ... ensure it matches one of the supported mechanism property fields.
+      for (const supported_mechanism_properties *prop = supported_properties; prop->name; ++prop) {
+         // Authentication spec: naming of mechanism properties MUST be case-insensitive. For instance, SERVICE_NAME and
+         // service_name refer to the same property.
+         if (strcasecmp (key, prop->name) == 0) {
+            const bson_type_t type = bson_iter_type (&iter);
+
+            if (type == prop->type) {
+               goto found_match; // Matches both key and type.
+            } else {
+               // Authentication spec: Drivers SHOULD raise an error as early as possible when detecting invalid values
+               // in a credential. For instance, if a mechanism_property is specified for MONGODB-CR, the driver should
+               // raise an error indicating that the property does not apply.
+               //
+               // Note: this overrides the Connection String spec: Any invalid Values for a given key MUST be ignored
+               // and MUST log a WARN level message.
+               MONGOC_URI_ERROR (error,
+                                 "'%s' authentication mechanism property '%s' has incorrect type '%s', should be '%s'",
+                                 key,
+                                 mechanism,
+                                 _mongoc_bson_type_to_str (type),
+                                 _mongoc_bson_type_to_str (prop->type));
                return false;
             }
-         } else {
-            bson_append_utf8 (&uri->credentials, MONGOC_URI_AUTHSOURCE, -1, "$external", -1);
          }
       }
-      /* MONGODB-X509 and MONGODB-AWS are the only mechanisms that don't require
-       * username */
-      if (!(strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == 0 ||
-            strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-AWS") == 0)) {
-         if (!mongoc_uri_get_username (uri) || strcmp (mongoc_uri_get_username (uri), "") == 0) {
-            MONGOC_URI_ERROR (
-               error, "'%s' authentication mechanism requires username", mongoc_uri_get_auth_mechanism (uri));
-            return false;
+
+      // Authentication spec: Drivers SHOULD raise an error as early as possible when detecting invalid values in a
+      // credential. For instance, if a mechanism_property is specified for MONGODB-CR, the driver should raise an error
+      // indicating that the property does not apply.
+      //
+      // Note: this overrides the Connection String spec: Any invalid Values for a given key MUST be ignored and MUST
+      // log a WARN level message.
+      MONGOC_URI_ERROR (error, "Unsupported '%s' authentication mechanism property: '%s'", mechanism, key);
+      return false;
+
+   found_match:
+      continue;
+   }
+
+   return true;
+}
+
+static bool
+_finalize_auth_gssapi_mechanism_properties (const bson_t *mechanism_properties, bson_error_t *error)
+{
+   BSON_OPTIONAL_PARAM (mechanism_properties);
+   BSON_ASSERT_PARAM (error);
+
+   static const supported_mechanism_properties supported_properties[] = {
+      {"SERVICE_NAME", BSON_TYPE_UTF8},
+      {"CANONICALIZE_HOST_NAME", BSON_TYPE_UTF8}, // CDRIVER-4128: UTF-8 even when "false" or "true".
+      {"SERVICE_REALM", BSON_TYPE_UTF8},
+      {"SERVICE_HOST", BSON_TYPE_UTF8},
+      {0},
+   };
+
+   if (mechanism_properties) {
+      return _supported_mechanism_properties_check (supported_properties, mechanism_properties, "GSSAPI", error);
+   }
+
+   return true;
+}
+
+static bool
+_finalize_auth_aws_mechanism_properties (const bson_t *mechanism_properties, bson_error_t *error)
+{
+   BSON_OPTIONAL_PARAM (mechanism_properties);
+   BSON_ASSERT_PARAM (error);
+
+   static const supported_mechanism_properties supported_properties[] = {
+      {"AWS_SESSION_TOKEN", BSON_TYPE_UTF8},
+      {0},
+   };
+
+   if (mechanism_properties) {
+      return _supported_mechanism_properties_check (supported_properties, mechanism_properties, "MONGODB-AWS", error);
+   }
+
+   return true;
+}
+
+static bool
+mongoc_uri_finalize_auth (mongoc_uri_t *uri, bson_error_t *error)
+{
+   BSON_ASSERT_PARAM (uri);
+   BSON_OPTIONAL_PARAM (error);
+
+   // Most validation of MongoCredential fields below according to the Authentication spec must be deferred to the
+   // implementation of the Authentication Handshake algorithm (i.e. `_mongoc_cluster_auth_node`) due to support for
+   // partial and late setting of credential fields via `mongoc_uri_set_*` functions. Limit validation to requirements
+   // for individual field which are explicitly specified. Do not validate requirements on fields in relation to one
+   // another (e.g. "given field A, field B must..."). The username, password, and authSource credential fields are
+   // exceptions to this rule for both backward compatibility and spec test compliance.
+
+   bool ret = false;
+
+   bson_iter_t iter;
+
+   const char *const mechanism = mongoc_uri_get_auth_mechanism (uri);
+   const char *const username = mongoc_uri_get_username (uri);
+   const char *const password = mongoc_uri_get_password (uri);
+   const char *const source =
+      bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE) ? bson_iter_utf8 (&iter, NULL) : NULL;
+
+   // Satisfy Connection String spec test: "must raise an error when the authSource is empty".
+   // This applies even before determining whether or not authentication is required.
+   if (source && strlen (source) == 0) {
+      MONGOC_URI_ERROR (error, "%s", "authSource may not be specified as an empty string");
+      return false;
+   }
+
+   // Authentication spec: The presence of a credential delimiter (i.e. '@') in the URI connection string is
+   // evidence that the user has unambiguously specified user information and MUST be interpreted as a user
+   // configuring authentication credentials (even if the username and/or password are empty strings).
+   //
+   // Note: username is always set when the credential delimiter `@` is present in the URI as parsed by
+   // `mongoc_uri_parse_userpass`.
+   //
+   // If neither an authentication mechanism nor a username is provided, there is nothing to do.
+   if (!mechanism && !username) {
+      return true;
+   } else {
+      // All code below assumes authentication credentials are being configured.
+   }
+
+   bson_t *mechanism_properties = NULL;
+   bson_t mechanism_properties_owner;
+   {
+      bson_t tmp;
+      if (mongoc_uri_get_mechanism_properties (uri, &tmp)) {
+         bson_copy_to (&tmp, &mechanism_properties_owner); // Avoid invalidation by updates to `uri->credentials`.
+         mechanism_properties = &mechanism_properties_owner;
+      } else {
+         bson_init (&mechanism_properties_owner); // Ensure initialization.
+      }
+   }
+
+   // Default authentication method.
+   if (!mechanism) {
+      // The authentication mechanism will be derived by `_mongoc_cluster_auth_node` during handshake according to
+      // `saslSupportedMechs`.
+
+      // Authentication spec: username: MUST be specified and non-zero length.
+      // Default authentication method is used when no mechanism is specified but a username is present; see the
+      // `!mechanism && !username` check above.
+      if (!_finalize_auth_username (username, "default", _mongoc_uri_finalize_required, error)) {
+         goto fail;
+      }
+
+      // Defer remaining validation of `MongoCredential` fields to Authentication Handshake.
+   }
+
+   // SCRAM-SHA-1, SCRAM-SHA-256, and PLAIN (same validation requirements)
+   else if (strcasecmp (mechanism, "SCRAM-SHA-1") == 0 || strcasecmp (mechanism, "SCRAM-SHA-256") == 0 ||
+            strcasecmp (mechanism, "PLAIN") == 0) {
+      // Authentication spec: username: MUST be specified and non-zero length.
+      if (!_finalize_auth_username (username, mechanism, _mongoc_uri_finalize_required, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: password: MUST be specified.
+      if (!_finalize_auth_password (password, mechanism, _mongoc_uri_finalize_required, error)) {
+         goto fail;
+      }
+
+      // Defer remaining validation of `MongoCredential` fields to Authentication Handshake.
+   }
+
+   // MONGODB-X509
+   else if (strcasecmp (mechanism, "MONGODB-X509") == 0) {
+      // `MongoCredential.username` SHOULD NOT be provided for MongoDB 3.4 and newer.
+      // CDRIVER-1959: allow for backward compatibility until the spec states "MUST NOT" instead of "SHOULD NOT" and
+      // spec tests are updated accordingly to permit warnings or errors.
+      if (!_finalize_auth_username (username, mechanism, _mongoc_uri_finalize_allowed, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: password: MUST NOT be specified.
+      if (!_finalize_auth_password (password, mechanism, _mongoc_uri_finalize_prohibited, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: source: MUST be "$external" and defaults to "$external".
+      if (!source) {
+         bsonBuildAppend (uri->credentials, kv (MONGOC_URI_AUTHSOURCE, cstr ("$external")));
+         if (bsonBuildError) {
+            MONGOC_URI_ERROR (error,
+                              "unexpected URI credentials BSON error when attempting to default 'MONGODB-X509' "
+                              "authentication source to '$external': %s",
+                              bsonBuildError);
+            goto fail;
          }
+      } else if (!_finalize_auth_source_external (source, mechanism, error)) {
+         goto fail;
       }
-      /* MONGODB-X509 errors if a password is supplied. */
-      if (strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == 0) {
-         if (mongoc_uri_get_password (uri)) {
-            MONGOC_URI_ERROR (
-               error, "'%s' authentication mechanism does not accept a password", mongoc_uri_get_auth_mechanism (uri));
-            return false;
+
+      // Defer remaining validation of `MongoCredential` fields to Authentication Handshake.
+   }
+
+   // GSSAPI
+   else if (strcasecmp (mechanism, "GSSAPI") == 0) {
+      // Authentication spec: username: MUST be specified and non-zero length.
+      if (!_finalize_auth_username (username, mechanism, _mongoc_uri_finalize_required, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: source: MUST be "$external" and defaults to "$external".
+      if (!source) {
+         bsonBuildAppend (uri->credentials, kv (MONGOC_URI_AUTHSOURCE, cstr ("$external")));
+         if (bsonBuildError) {
+            MONGOC_URI_ERROR (error,
+                              "unexpected URI credentials BSON error when attempting to default 'GSSAPI' "
+                              "authentication mechanism source to '$external': %s",
+                              bsonBuildError);
+            goto fail;
          }
+      } else if (!_finalize_auth_source_external (source, mechanism, error)) {
+         goto fail;
       }
-      /* GSSAPI uses 'mongodb' as the default service name */
-      if (strcasecmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI") == 0 &&
-          !(bson_iter_init_find (&iter, &uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES) &&
-            BSON_ITER_HOLDS_DOCUMENT (&iter) && bson_iter_recurse (&iter, &iter) &&
-            bson_iter_find_case (&iter, "SERVICE_NAME"))) {
-         bson_t tmp;
-         bson_t *props = NULL;
 
-         props = mongoc_uri_get_mechanism_properties (uri, &tmp) ? bson_copy (&tmp) : bson_new ();
+      // Authentication spec: password: MAY be specified.
+      if (!_finalize_auth_password (password, mechanism, _mongoc_uri_finalize_allowed, error)) {
+         goto fail;
+      }
 
-         BSON_APPEND_UTF8 (props, "SERVICE_NAME", "mongodb");
-         mongoc_uri_set_mechanism_properties (uri, props);
+      // `MongoCredentials.mechanism_properties` are allowed for GSSAPI.
+      if (!_finalize_auth_gssapi_mechanism_properties (mechanism_properties, error)) {
+         goto fail;
+      }
 
-         bson_destroy (props);
+      // Authentication spec: valid values for CANONICALIZE_HOST_NAME are true, false, "none", "forward",
+      // "forwardAndReverse". If a value is provided that does not match one of these the driver MUST raise an error.
+      if (mechanism_properties) {
+         bsonParse (*mechanism_properties,
+                    find (iKeyWithType ("CANONICALIZE_HOST_NAME", utf8),
+                          case (when (iStrEqual ("true"), nop),
+                                when (iStrEqual ("false"), nop),
+                                // CDRIVER-4128: only legacy boolean values are currently supported.
+                                else (do ({
+                                   bsonParseError =
+                                      "'GSSAPI' authentication mechanism requires CANONICALIZE_HOST_NAME is either "
+                                      "\"true\" or \"false\"";
+                                })))));
+         if (bsonParseError) {
+            MONGOC_URI_ERROR (error, "%s", bsonParseError);
+            goto fail;
+         }
       }
 
-   } else if (require_auth) /* Default auth mechanism is used */ {
-      if (!mongoc_uri_get_username (uri) || strcmp (mongoc_uri_get_username (uri), "") == 0) {
-         MONGOC_URI_ERROR (error, "%s", "Default authentication mechanism requires username");
-         return false;
+      // Authentication spec: Drivers MUST allow the user to specify a different service name. The default is
+      // "mongodb".
+      if (!mechanism_properties || !bson_iter_init_find_case (&iter, mechanism_properties, "SERVICE_NAME")) {
+         bsonBuildDecl (props,
+                        if (mechanism_properties, then (insert (*mechanism_properties, always))),
+                        kv ("SERVICE_NAME", cstr ("mongodb")));
+         const bool success = !bsonBuildError && mongoc_uri_set_mechanism_properties (uri, &props);
+         bson_destroy (&props);
+         if (!success) {
+            MONGOC_URI_ERROR (error,
+                              "unexpected URI credentials BSON error when attempting to default 'GSSAPI' "
+                              "authentication mechanism property 'SERVICE_NAME' to 'mongodb': %s",
+                              bsonBuildError ? bsonBuildError : "mongoc_uri_set_mechanism_properties failed");
+            goto fail;
+         }
       }
+
+      // Defer remaining validation of `MongoCredential` fields to Authentication Handshake.
+   }
+
+   // MONGODB-AWS
+   else if (strcasecmp (mechanism, "MONGODB-AWS") == 0) {
+      // Authentication spec: username: MAY be specified (as the non-sensitive AWS access key).
+      if (!_finalize_auth_username (username, mechanism, _mongoc_uri_finalize_allowed, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: source: MUST be "$external" and defaults to "$external".
+      if (!source) {
+         bsonBuildAppend (uri->credentials, kv (MONGOC_URI_AUTHSOURCE, cstr ("$external")));
+         if (bsonBuildError) {
+            MONGOC_URI_ERROR (error,
+                              "unexpected URI credentials BSON error when attempting to default 'MONGODB-AWS' "
+                              "authentication mechanism source to '$external': %s",
+                              bsonBuildError);
+            goto fail;
+         }
+      } else if (!_finalize_auth_source_external (source, mechanism, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: password: MAY be specified (as the sensitive AWS secret key).
+      if (!_finalize_auth_password (password, mechanism, _mongoc_uri_finalize_allowed, error)) {
+         goto fail;
+      }
+
+      // mechanism_properties are allowed for MONGODB-AWS.
+      if (!_finalize_auth_aws_mechanism_properties (mechanism_properties, error)) {
+         goto fail;
+      }
+
+      // Authentication spec: if a username is provided without a password (or vice-versa), Drivers MUST raise an error.
+      if (!username != !password) {
+         MONGOC_URI_ERROR (error,
+                           "'%s' authentication mechanism does not accept a username or a password without the other",
+                           mechanism);
+         goto fail;
+      }
+
+      // Defer remaining validation of `MongoCredential` fields to Authentication Handshake.
    }
-   return true;
+
+   // Invalid or unsupported authentication mechanism.
+   else {
+      MONGOC_URI_ERROR (
+         error,
+         "Unsupported value for authMechanism '%s': must be one of "
+         "['MONGODB-OIDC', 'SCRAM-SHA-1', 'SCRAM-SHA-256', 'PLAIN', 'MONGODB-X509', 'GSSAPI', 'MONGODB-AWS']",
+         mechanism);
+      goto fail;
+   }
+
+   ret = true;
+
+fail:
+   bson_destroy (&mechanism_properties_owner);
+
+   return ret;
 }
 
 static bool
@@ -1426,100 +1838,126 @@ error:
 static bool
 mongoc_uri_parse (mongoc_uri_t *uri, const char *str, bson_error_t *error)
 {
+   BSON_ASSERT_PARAM (uri);
    BSON_ASSERT_PARAM (str);
 
-   char *before_slash = NULL;
-   const char *tmp;
+   const size_t str_len = strlen (str);
 
-   if (!bson_utf8_validate (str, strlen (str), false /* allow_null */)) {
+   if (!bson_utf8_validate (str, str_len, false /* allow_null */)) {
       MONGOC_URI_ERROR (error, "%s", "Invalid UTF-8 in URI");
-      goto error;
+      return false;
    }
 
+   // Save for later.
+   const char *const str_end = str + str_len;
+
+   // Parse and remove scheme and its delimiter.
+   // e.g. "mongodb://user:pass@host1:27017,host2:27018/database?key1=value1&key2=value2"
+   //       ~~~~~~~~~~
    if (!mongoc_uri_parse_scheme (uri, str, &str)) {
       MONGOC_URI_ERROR (error, "%s", "Invalid URI Schema, expecting 'mongodb://' or 'mongodb+srv://'");
-      goto error;
+      return false;
    }
+   // str -> "user:pass@host1:27017,host2:27018/database?key1=value1&key2=value2"
 
-   before_slash = scan_to_unichar (str, '/', "", &tmp);
-   if (!before_slash) {
-      // Handle cases of optional delimiting slash
-      char *userpass = NULL;
-      char *hosts = NULL;
-
-      // Skip any "?"s that exist in the userpass
-      userpass = scan_to_unichar (str, '@', "", &tmp);
-      if (!userpass) {
-         // If none found, safely check for "?" indicating beginning of options
-         before_slash = scan_to_unichar (str, '?', "", &tmp);
-      } else {
-         const size_t userpass_len = (size_t) (tmp - str);
-         // Otherwise, see if options exist after userpass and concatenate result
-         hosts = scan_to_unichar (tmp, '?', "", &tmp);
+   // From this point forward, use this cursor to find the split between "userhosts" and "dbopts".
+   const char *cursor = str;
 
-         if (hosts) {
-            const size_t hosts_len = (size_t) (tmp - str) - userpass_len;
+   // Remove userinfo and its delimiter.
+   // e.g. "user:pass@host1:27017,host2:27018/database?key1=value1&key2=value2"
+   //       ~~~~~~~~~~
+   {
+      const char *tmp;
 
-            before_slash = bson_strndup (str, userpass_len + hosts_len);
-         }
-      }
+      // Only ':' is permitted among RFC-3986 gen-delims (":/?#[]@") in userinfo.
+      // However, continue supporting these characters for backward compatibility, as permitted by the Connection String
+      // spec: for backwards-compatibility reasons, drivers MAY allow reserved characters other than "@" and ":" to be
+      // present in user information without percent-encoding.
+      char *userinfo = scan_to_unichar (cursor, '@', "", &tmp);
+
+      if (userinfo) {
+         cursor = tmp + 1; // Consume userinfo delimiter.
+         bson_free (userinfo);
+      }
+   }
+   // cursor -> "host1:27017,host2:27018/database?key1=value1&key2=value2"
+
+   // Find either the optional auth database delimiter or the query delimiter.
+   // e.g. "host1:27017,host2:27018/database?key1=value1&key2=value2"
+   //                              ^
+   // e.g. "host1:27017,host2:27018?key1=value1&key2=value2"
+   //                              ^
+   {
+      const char *tmp;
 
-      bson_free (userpass);
-      bson_free (hosts);
-   }
+      // Only ':', '[', and ']' are permitted among RFC-3986 gen-delims (":/?#[]@") in hostinfo.
+      const char *const terminators = "/?#@";
 
-   if (!before_slash) {
-      before_slash = bson_strdup (str);
-      str += strlen (before_slash);
-   } else {
-      str = tmp;
-   }
+      char *hostinfo;
 
-   if (!mongoc_uri_parse_before_slash (uri, before_slash, error)) {
-      goto error;
-   }
+      // Optional auth delimiter is present.
+      if ((hostinfo = scan_to_unichar (cursor, '/', terminators, &tmp))) {
+         cursor = tmp; // Include the delimiter.
+         bson_free (hostinfo);
+      }
 
-   BSON_ASSERT (str);
+      // Query delimiter is present.
+      else if ((hostinfo = scan_to_unichar (cursor, '?', terminators, &tmp))) {
+         cursor = tmp; // Include the delimiter.
+         bson_free (hostinfo);
+      }
 
-   if (*str) {
-      // Check for valid end of hostname delimeter (skip slash if necessary)
-      if (*str != '/' && *str != '?') {
-         MONGOC_URI_ERROR (error, "%s", "Expected end of hostname delimiter");
-         goto error;
+      // Neither delimiter is present. Entire rest of string is part of hostinfo.
+      else {
+         cursor = str_end; // Jump to end of string.
+         BSON_ASSERT (*cursor == '\0');
+      }
+   }
+   // cursor -> "/database?key1=value1&key2=value2"
+
+   // Parse "userhosts". e.g. "user:pass@host1:27017,host2:27018"
+   {
+      char *const userhosts = bson_strndup (str, (size_t) (cursor - str));
+      const bool ret = mongoc_uri_parse_before_slash (uri, userhosts, error);
+      bson_free (userhosts);
+      if (!ret) {
+         return false;
       }
+   }
 
-      if (*str == '/') {
-         // Try to parse database.
-         str++;
-         if (*str) {
-            if (!mongoc_uri_parse_database (uri, str, &str)) {
+   // Parse "dbopts". e.g. "/database?key1=value1&key2=value2"
+   if (*cursor != '\0') {
+      BSON_ASSERT (*cursor == '/' || *cursor == '?');
+
+      // Parse the auth database.
+      if (*cursor == '/') {
+         ++cursor; // Consume the delimiter.
+
+         // No auth database may be present even if the delimiter is present.
+         // e.g. "mongodb://localhost:27017/"
+         if (*cursor != '\0') {
+            if (!mongoc_uri_parse_database (uri, cursor, &cursor)) {
                MONGOC_URI_ERROR (error, "%s", "Invalid database name in URI");
-               goto error;
+               return false;
             }
          }
       }
 
-      if (*str == '?') {
-         // Try to parse options.
-         str++;
-         if (*str) {
-            if (!mongoc_uri_parse_options (uri, str, false /* from DNS */, error)) {
-               goto error;
+      // Parse the query options.
+      if (*cursor == '?') {
+         ++cursor; // Consume the delimiter.
+
+         // No options may be present even if the delimiter is present.
+         // e.g. "mongodb://localhost:27017?"
+         if (*cursor != '\0') {
+            if (!mongoc_uri_parse_options (uri, cursor, false /* from DNS */, error)) {
+               return false;
             }
          }
       }
    }
 
-   if (!mongoc_uri_finalize (uri, error)) {
-      goto error;
-   }
-
-   bson_free (before_slash);
-   return true;
-
-error:
-   bson_free (before_slash);
-   return false;
+   return mongoc_uri_finalize (uri, error);
 }
 
 
@@ -1625,7 +2063,7 @@ mongoc_uri_set_mechanism_properties (mon
                     // Append the new properties
                     kv (MONGOC_URI_AUTHMECHANISMPROPERTIES, bson (*properties)));
    bson_reinit (&uri->credentials);
-   bsonBuildAppend (uri->credentials, insert (tmp, true));
+   bsonBuildAppend (uri->credentials, insert (tmp, always));
    bson_destroy (&tmp);
    return bsonBuildError == NULL;
 }
@@ -1715,8 +2153,7 @@ _mongoc_uri_build_write_concern (mongoc_
                     storeStrRef (w_str),
                     case (
                        // Special W options:
-                       when (anyOf (eq (int32, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED),
-                                    eq (int32, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)),
+                       when (eq (int32, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED),
                              // These conflict with journalling:
                              if (eval (mongoc_write_concern_get_journal (write_concern)),
                                  then (error ("Journal conflicts with w value"))),
@@ -1949,33 +2386,53 @@ mongoc_uri_set_database (mongoc_uri_t *u
 const char *
 mongoc_uri_get_auth_source (const mongoc_uri_t *uri)
 {
-   bson_iter_t iter;
-   const char *mechanism;
+   BSON_ASSERT_PARAM (uri);
 
-   BSON_ASSERT (uri);
+   // Explicitly set.
+   {
+      bson_iter_t iter;
+      if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) {
+         return bson_iter_utf8 (&iter, NULL);
+      }
+   }
 
-   if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) {
-      return bson_iter_utf8 (&iter, NULL);
+   // The database name if supplied.
+   const char *const db = uri->database;
+
+   // Depending on the authentication mechanism, `MongoCredential.source` has different defaults.
+   const char *const mechanism = mongoc_uri_get_auth_mechanism (uri);
+
+   // Default authentication mechanism uses either SCRAM-SHA-1 or SCRAM-SHA-256.
+   if (!mechanism) {
+      return db ? db : "admin";
    }
 
-   /* Auth spec:
-    * "For GSSAPI and MONGODB-X509 authMechanisms the authSource defaults to
-    * $external. For PLAIN the authSource defaults to the database name if
-    * supplied on the connection string or $external. For
-    * SCRAM-SHA-1 and SCRAM-SHA-256 authMechanisms, the authSource defaults to
-    * the database name if supplied on the connection string or admin."
-    */
-   mechanism = mongoc_uri_get_auth_mechanism (uri);
-   if (mechanism) {
-      if (!strcasecmp (mechanism, "GSSAPI") || !strcasecmp (mechanism, "MONGODB-X509")) {
-         return "$external";
-      }
-      if (!strcasecmp (mechanism, "PLAIN")) {
-         return uri->database ? uri->database : "$external";
+   // Defaults to the database name if supplied on the connection string or "admin" for:
+   {
+      static const char *const matches[] = {
+         "SCRAM-SHA-1",
+         "SCRAM-SHA-256",
+         NULL,
+      };
+
+      for (const char *const *match = matches; *match; ++match) {
+         if (strcasecmp (mechanism, *match) == 0) {
+            return db ? db : "admin";
+         }
       }
    }
 
-   return uri->database ? uri->database : "admin";
+   // Defaults to the database name if supplied on the connection string or "$external" for:
+   //  - PLAIN
+   if (strcasecmp (mechanism, "PLAIN") == 0) {
+      return db ? db : "$external";
+   }
+
+   // Fallback to "$external" for all remaining authentication mechanisms:
+   //  - MONGODB-X509
+   //  - GSSAPI
+   //  - MONGODB-AWS
+   return "$external";
 }
 
 
@@ -2098,13 +2555,6 @@ mongoc_uri_get_srv_hostname (const mongo
 }
 
 
-const char *
-mongoc_uri_get_service (const mongoc_uri_t *uri)
-{
-   return mongoc_uri_get_srv_hostname (uri);
-}
-
-
 /* Initial DNS Seedlist Discovery Spec: `srvServiceName` requires a string value
  * and defaults to "mongodb". */
 static const char *const mongoc_default_srv_service_name = "mongodb";
@@ -2207,13 +2657,6 @@ mongoc_uri_get_string (const mongoc_uri_
 }
 
 
-const bson_t *
-mongoc_uri_get_read_prefs (const mongoc_uri_t *uri)
-{
-   BSON_ASSERT (uri);
-   return mongoc_read_prefs_get_tags (uri->read_prefs);
-}
-
 char *
 mongoc_uri_unescape (const char *escaped_string)
 {
@@ -2367,11 +2810,6 @@ mongoc_uri_get_tls (const mongoc_uri_t *
    return false;
 }
 
-bool
-mongoc_uri_get_ssl (const mongoc_uri_t *uri) /* IN */
-{
-   return mongoc_uri_get_tls (uri);
-}
 
 const char *
 mongoc_uri_get_server_monitoring_mode (const mongoc_uri_t *uri)
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-uri.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-uri.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-uri.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-uri.h	2025-06-19 15:42:22.000000000 +0000
@@ -46,10 +46,8 @@
 #define MONGOC_URI_JOURNAL "journal"
 #define MONGOC_URI_LOADBALANCED "loadbalanced"
 #define MONGOC_URI_LOCALTHRESHOLDMS "localthresholdms"
-#define MONGOC_URI_MAXIDLETIMEMS "maxidletimems"
 #define MONGOC_URI_MAXPOOLSIZE "maxpoolsize"
 #define MONGOC_URI_MAXSTALENESSSECONDS "maxstalenessseconds"
-#define MONGOC_URI_MINPOOLSIZE "minpoolsize"
 #define MONGOC_URI_READCONCERNLEVEL "readconcernlevel"
 #define MONGOC_URI_READPREFERENCE "readpreference"
 #define MONGOC_URI_READPREFERENCETAGS "readpreferencetags"
@@ -60,7 +58,6 @@
 #define MONGOC_URI_SERVERMONITORINGMODE "servermonitoringmode"
 #define MONGOC_URI_SERVERSELECTIONTIMEOUTMS "serverselectiontimeoutms"
 #define MONGOC_URI_SERVERSELECTIONTRYONCE "serverselectiontryonce"
-#define MONGOC_URI_SLAVEOK "slaveok"
 #define MONGOC_URI_SOCKETCHECKINTERVALMS "socketcheckintervalms"
 #define MONGOC_URI_SOCKETTIMEOUTMS "sockettimeoutms"
 #define MONGOC_URI_SRVSERVICENAME "srvservicename"
@@ -75,7 +72,6 @@
 #define MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK "tlsdisablecertificaterevocationcheck"
 #define MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK "tlsdisableocspendpointcheck"
 #define MONGOC_URI_W "w"
-#define MONGOC_URI_WAITQUEUEMULTIPLE "waitqueuemultiple"
 #define MONGOC_URI_WAITQUEUETIMEOUTMS "waitqueuetimeoutms"
 #define MONGOC_URI_WTIMEOUTMS "wtimeoutms"
 #define MONGOC_URI_ZLIBCOMPRESSIONLEVEL "zlibcompressionlevel"
@@ -96,110 +92,154 @@ typedef struct _mongoc_uri_t mongoc_uri_
 
 MONGOC_EXPORT (mongoc_uri_t *)
 mongoc_uri_copy (const mongoc_uri_t *uri) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_uri_destroy (mongoc_uri_t *uri);
+
 MONGOC_EXPORT (mongoc_uri_t *)
 mongoc_uri_new (const char *uri_string) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_uri_t *)
 mongoc_uri_new_with_error (const char *uri_string, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_uri_t *)
 mongoc_uri_new_for_host_port (const char *hostname, uint16_t port) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (const mongoc_host_list_t *)
 mongoc_uri_get_hosts (const mongoc_uri_t *uri);
-MONGOC_EXPORT (const char *)
-mongoc_uri_get_service (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_srv_hostname);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_srv_hostname (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_srv_service_name (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_database (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_database (mongoc_uri_t *uri, const char *database);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_uri_get_compressors (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_uri_get_options (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_password (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_password (mongoc_uri_t *uri, const char *password);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_has_option (const mongoc_uri_t *uri, const char *key);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_option_is_int32 (const char *key);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_option_is_int64 (const char *key);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_option_is_bool (const char *key);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_option_is_utf8 (const char *key);
+
 MONGOC_EXPORT (int32_t)
 mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, const char *option, int32_t fallback);
+
 MONGOC_EXPORT (int64_t)
 mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, const char *option, int64_t fallback);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, const char *option, bool fallback);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, const char *option, const char *fallback);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, const char *option, int32_t value);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, const char *option, int64_t value);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, const char *option, bool value);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, const char *option, const char *value);
-MONGOC_EXPORT (const bson_t *)
-mongoc_uri_get_read_prefs (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_read_prefs_t);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_replica_set (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_string (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_username (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_username (mongoc_uri_t *uri, const char *username);
+
 MONGOC_EXPORT (const bson_t *)
 mongoc_uri_get_credentials (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_auth_source (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_auth_source (mongoc_uri_t *uri, const char *value);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_appname (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_appname (mongoc_uri_t *uri, const char *value);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_compressors (mongoc_uri_t *uri, const char *value);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_auth_mechanism (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_auth_mechanism (mongoc_uri_t *uri, const char *value);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, bson_t *properties);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri, const bson_t *properties);
-MONGOC_EXPORT (bool)
-mongoc_uri_get_ssl (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_tls);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_get_tls (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (char *)
 mongoc_uri_unescape (const char *escaped_string) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (const mongoc_read_prefs_t *)
 mongoc_uri_get_read_prefs_t (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (void)
 mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri, const mongoc_read_prefs_t *prefs);
+
 MONGOC_EXPORT (const mongoc_write_concern_t *)
 mongoc_uri_get_write_concern (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (void)
 mongoc_uri_set_write_concern (mongoc_uri_t *uri, const mongoc_write_concern_t *wc);
+
 MONGOC_EXPORT (const mongoc_read_concern_t *)
 mongoc_uri_get_read_concern (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (void)
 mongoc_uri_set_read_concern (mongoc_uri_t *uri, const mongoc_read_concern_t *rc);
+
 MONGOC_EXPORT (const char *)
 mongoc_uri_get_server_monitoring_mode (const mongoc_uri_t *uri);
+
 MONGOC_EXPORT (bool)
 mongoc_uri_set_server_monitoring_mode (mongoc_uri_t *uri, const char *value);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-util-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-util-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-util-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-util-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -86,13 +86,6 @@ const char *
 _mongoc_wire_version_to_server_version (int32_t version);
 
 bool
-_mongoc_get_server_id_from_opts (const bson_t *opts,
-                                 mongoc_error_domain_t domain,
-                                 mongoc_error_code_t code,
-                                 uint32_t *server_id,
-                                 bson_error_t *error);
-
-bool
 _mongoc_validate_new_document (const bson_t *insert, bson_validate_flags_t vflags, bson_error_t *error);
 
 bool
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-util.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-util.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-util.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-util.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,6 +24,7 @@
 
 #include <common-md5-private.h>
 #include <common-thread-private.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-rand-private.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-client.h>
@@ -31,16 +32,22 @@
 #include <mongoc/mongoc-client-session-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-sleep.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/loop.h>
 
-const bson_validate_flags_t _mongoc_default_insert_vflags =
-   BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS;
-
-const bson_validate_flags_t _mongoc_default_replace_vflags =
-   BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS;
-
-const bson_validate_flags_t _mongoc_default_update_vflags =
-   BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS;
+/**
+ * ! NOTE
+ *
+ * In earlier releases, these flags had `BSON_VALIDATE_UTF8` and `BSON_VALIDATE_UTF8_ALLOW_NULL`.
+ * Due to a bug, the CRUD APIs did not actually do UTF-8 validation. This issue has been fixed, but
+ * we want to maintain backward compatibility, so the UTF-8 validation was removed from these flag
+ * values.
+ *
+ * A future API may add the UTF-8 validation back, but it would be a breaking change.
+ */
+const bson_validate_flags_t _mongoc_default_insert_vflags = BSON_VALIDATE_EMPTY_KEYS;
+const bson_validate_flags_t _mongoc_default_replace_vflags = BSON_VALIDATE_EMPTY_KEYS;
+const bson_validate_flags_t _mongoc_default_update_vflags = BSON_VALIDATE_EMPTY_KEYS;
 
 int
 _mongoc_rand_simple (unsigned int *seed)
@@ -68,13 +75,12 @@ _mongoc_hex_md5 (const char *input)
    uint8_t digest[16];
    bson_md5_t md5;
    char digest_str[33];
-   int i;
 
    mcommon_md5_init (&md5);
    mcommon_md5_append (&md5, (const uint8_t *) input, (uint32_t) strlen (input));
    mcommon_md5_finish (&md5, digest);
 
-   for (i = 0; i < sizeof digest; i++) {
+   mlib_foreach_urange (i, sizeof digest) {
       // Expect no truncation.
       int req = bson_snprintf (&digest_str[i * 2], 3, "%02x", digest[i]);
       BSON_ASSERT (req < 3);
@@ -316,41 +322,6 @@ _mongoc_wire_version_to_server_version (
 }
 
 
-/* Get "serverId" from opts. Sets *server_id to the serverId from "opts" or 0
- * if absent. On error, fills out *error with domain and code and return false.
- */
-bool
-_mongoc_get_server_id_from_opts (
-   const bson_t *opts, mongoc_error_domain_t domain, mongoc_error_code_t code, uint32_t *server_id, bson_error_t *error)
-{
-   bson_iter_t iter;
-
-   ENTRY;
-
-   BSON_ASSERT (server_id);
-
-   *server_id = 0;
-
-   if (!opts || !bson_iter_init_find (&iter, opts, "serverId")) {
-      RETURN (true);
-   }
-
-   if (!BSON_ITER_HOLDS_INT (&iter)) {
-      bson_set_error (error, domain, code, "The serverId option must be an integer");
-      RETURN (false);
-   }
-
-   if (bson_iter_as_int64 (&iter) <= 0) {
-      bson_set_error (error, domain, code, "The serverId option must be >= 1");
-      RETURN (false);
-   }
-
-   *server_id = (uint32_t) bson_iter_as_int64 (&iter);
-
-   RETURN (true);
-}
-
-
 bool
 _mongoc_validate_new_document (const bson_t *doc, bson_validate_flags_t vflags, bson_error_t *error)
 {
@@ -361,11 +332,11 @@ _mongoc_validate_new_document (const bso
    }
 
    if (!bson_validate_with_error (doc, vflags, &validate_err)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "invalid document for insert: %s",
-                      validate_err.message);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "invalid document for insert: %s",
+                         validate_err.message);
       return false;
    }
 
@@ -385,27 +356,27 @@ _mongoc_validate_replace (const bson_t *
    }
 
    if (!bson_validate_with_error (doc, vflags, &validate_err)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "invalid argument for replace: %s",
-                      validate_err.message);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "invalid argument for replace: %s",
+                         validate_err.message);
       return false;
    }
 
    if (!bson_iter_init (&iter, doc)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "replace document is corrupt");
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "replace document is corrupt");
       return false;
    }
 
    while (bson_iter_next (&iter)) {
       key = bson_iter_key (&iter);
       if (key[0] == '$') {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid key '%s': replace prohibits $ operators",
-                         key);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid key '%s': replace prohibits $ operators",
+                            key);
 
          return false;
       }
@@ -427,11 +398,11 @@ _mongoc_validate_update (const bson_t *u
    }
 
    if (!bson_validate_with_error (update, vflags, &validate_err)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "invalid argument for update: %s",
-                      validate_err.message);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "invalid argument for update: %s",
+                         validate_err.message);
       return false;
    }
 
@@ -440,19 +411,19 @@ _mongoc_validate_update (const bson_t *u
    }
 
    if (!bson_iter_init (&iter, update)) {
-      bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "update document is corrupt");
+      _mongoc_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "update document is corrupt");
       return false;
    }
 
    while (bson_iter_next (&iter)) {
       key = bson_iter_key (&iter);
       if (key[0] != '$') {
-         bson_set_error (error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Invalid key '%s': update only works with $ operators"
-                         " and pipelines",
-                         key);
+         _mongoc_set_error (error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Invalid key '%s': update only works with $ operators"
+                            " and pipelines",
+                            key);
 
          return false;
       }
@@ -957,21 +928,21 @@ _mongoc_iter_document_as_bson (const bso
    const uint8_t *data;
 
    if (!BSON_ITER_HOLDS_DOCUMENT (iter)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "expected BSON document for field: %s",
-                      bson_iter_key (iter));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "expected BSON document for field: %s",
+                         bson_iter_key (iter));
       return false;
    }
 
    bson_iter_document (iter, &len, &data);
    if (!bson_init_static (bson, data, len)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "unable to initialize BSON document from field: %s",
-                      bson_iter_key (iter));
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "unable to initialize BSON document from field: %s",
+                         bson_iter_key (iter));
       return false;
    }
 
@@ -988,7 +959,7 @@ hex_to_bin (const char *hex, uint32_t *l
       return NULL;
    }
 
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, hex_len / 2u));
+   BSON_ASSERT (mlib_in_range (uint32_t, hex_len / 2u));
 
    *len = (uint32_t) (hex_len / 2u);
    out = bson_malloc0 (*len);
@@ -1001,7 +972,7 @@ hex_to_bin (const char *hex, uint32_t *l
          return NULL;
       }
 
-      BSON_ASSERT (mcommon_in_range_unsigned (uint8_t, hex_char));
+      BSON_ASSERT (mlib_in_range (uint8_t, hex_char));
       out[i / 2u] = (uint8_t) hex_char;
    }
    return out;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-command.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-command.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-command.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-command.c	2025-06-19 15:42:22.000000000 +0000
@@ -19,7 +19,6 @@
 #include <mongoc/mongoc-client-private.h>
 #include <mongoc/mongoc-client-session-private.h>
 #include <mongoc/mongoc-client-side-encryption-private.h>
-#include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-trace-private.h>
 #include <mongoc/mongoc-write-command-private.h>
@@ -27,7 +26,8 @@
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-opts-private.h>
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/intencode.h>
+#include <mlib/cmp.h>
 
 #include <inttypes.h>
 
@@ -164,14 +164,11 @@ _mongoc_write_command_init_insert (mongo
 {
    ENTRY;
 
-   BSON_ASSERT (command);
+   BSON_ASSERT_PARAM (command);
+   BSON_ASSERT_PARAM (document);
 
    _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts);
-
-   /* must handle NULL document from mongoc_collection_insert_bulk */
-   if (document) {
-      _mongoc_write_command_insert_append (command, document);
-   }
+   _mongoc_write_command_insert_append (command, document);
 
    EXIT;
 }
@@ -198,7 +195,6 @@ _mongoc_write_command_init_insert_one_id
    _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts);
 
    /* near identical to _mongoc_write_command_insert_append but additionally records the inserted id */
-   /* no need to handle NULL document from mongoc_collection_insert_bulk since only called by insert_one */
    BSON_ASSERT (command->type == MONGOC_WRITE_COMMAND_INSERT);
    BSON_ASSERT (document->len >= 5);
 
@@ -243,7 +239,7 @@ _mongoc_write_command_init_insert_idl (m
 
    _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts);
 
-   /* must handle NULL document from mongoc_collection_insert_bulk */
+   /* must handle NULL document from mongoc_collection_insert_many */
    if (document) {
       _mongoc_write_command_insert_append (command, document);
    }
@@ -390,14 +386,14 @@ _mongoc_write_command_init (bson_t *doc,
 static void
 _mongoc_write_command_too_large_error (bson_error_t *error, int32_t idx, int32_t len, int32_t max_bson_size)
 {
-   bson_set_error (error,
-                   MONGOC_ERROR_BSON,
-                   MONGOC_ERROR_BSON_INVALID,
-                   "Document %" PRId32 " is too large for the cluster. "
-                   "Document is %" PRId32 " bytes, max is %" PRId32 ".",
-                   idx,
-                   len,
-                   max_bson_size);
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_BSON,
+                      MONGOC_ERROR_BSON_INVALID,
+                      "Document %" PRId32 " is too large for the cluster. "
+                      "Document is %" PRId32 " bytes, max is %" PRId32 ".",
+                      idx,
+                      len,
+                      max_bson_size);
 }
 
 
@@ -408,11 +404,11 @@ _empty_error (mongoc_write_command_t *co
                                     MONGOC_ERROR_COLLECTION_INSERT_FAILED,
                                     MONGOC_ERROR_COLLECTION_UPDATE_FAILED};
 
-   bson_set_error (error,
-                   MONGOC_ERROR_COLLECTION,
-                   codes[command->type],
-                   "Cannot do an empty %s",
-                   _mongoc_write_command_get_name (command));
+   _mongoc_set_error (error,
+                      MONGOC_ERROR_COLLECTION,
+                      codes[command->type],
+                      "Cannot do an empty %s",
+                      _mongoc_write_command_get_name (command));
 }
 
 
@@ -698,24 +694,20 @@ _mongoc_write_opmsg (mongoc_write_comman
    }
 
    do {
-      uint32_t ulen;
-      memcpy (&ulen, command->payload.data + payload_batch_size + payload_total_offset, 4);
-      ulen = BSON_UINT32_FROM_LE (ulen);
+      const int32_t len = mlib_read_i32le (command->payload.data + payload_batch_size + payload_total_offset);
 
       // Although messageLength is an int32, it should never be negative.
-      BSON_ASSERT (mcommon_in_range_unsigned (int32_t, ulen));
-      const int32_t slen = (int32_t) ulen;
+      BSON_ASSERT (len >= 0);
 
-      if (slen > max_bson_obj_size + BSON_OBJECT_ALLOWANCE) {
+      if (len > max_bson_obj_size + BSON_OBJECT_ALLOWANCE) {
          /* Quit if the document is too large */
-         _mongoc_write_command_too_large_error (error, index_offset, slen, max_bson_obj_size);
+         _mongoc_write_command_too_large_error (error, index_offset, len, max_bson_obj_size);
          result->failed = true;
          break;
 
-      } else if (mcommon_cmp_less_equal_us (payload_batch_size + opmsg_overhead + ulen, max_msg_size) ||
-                 document_count == 0) {
+      } else if (mlib_cmp (payload_batch_size + opmsg_overhead + len, <=, max_msg_size) || document_count == 0) {
          /* The current batch is still under max batch size in bytes */
-         payload_batch_size += ulen;
+         payload_batch_size += len;
 
          /* If this document filled the maximum document count */
          if (++document_count == max_document_count) {
@@ -820,7 +812,7 @@ _mongoc_write_command_execute (mongoc_wr
    }
 
    if (!mongoc_write_concern_is_valid (write_concern)) {
-      bson_set_error (
+      _mongoc_set_error (
          &result->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The write concern is invalid.");
       result->failed = true;
       EXIT;
@@ -855,10 +847,10 @@ _mongoc_write_command_execute_idl (mongo
    if (command->flags.has_collation) {
       if (!mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
          result->failed = true;
-         bson_set_error (&result->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot set collation for unacknowledged writes");
+         _mongoc_set_error (&result->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot set collation for unacknowledged writes");
          EXIT;
       }
    }
@@ -866,10 +858,10 @@ _mongoc_write_command_execute_idl (mongo
    if (command->flags.has_array_filters) {
       if (!mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
          result->failed = true;
-         bson_set_error (&result->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot use array filters with unacknowledged writes");
+         _mongoc_set_error (&result->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot use array filters with unacknowledged writes");
          EXIT;
       }
    }
@@ -877,10 +869,10 @@ _mongoc_write_command_execute_idl (mongo
    if (command->flags.has_update_hint) {
       if (server_stream->sd->max_wire_version < WIRE_VERSION_UPDATE_HINT &&
           !mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
-         bson_set_error (&result->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "The selected server does not support hint for update");
+         _mongoc_set_error (&result->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "The selected server does not support hint for update");
          result->failed = true;
          EXIT;
       }
@@ -889,10 +881,10 @@ _mongoc_write_command_execute_idl (mongo
    if (command->flags.has_delete_hint) {
       if (server_stream->sd->max_wire_version < WIRE_VERSION_DELETE_HINT &&
           !mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
-         bson_set_error (&result->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
-                         "The selected server does not support hint for delete");
+         _mongoc_set_error (&result->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION,
+                            "The selected server does not support hint for delete");
          result->failed = true;
          EXIT;
       }
@@ -901,20 +893,20 @@ _mongoc_write_command_execute_idl (mongo
    if (command->flags.bypass_document_validation) {
       if (!mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
          result->failed = true;
-         bson_set_error (&result->error,
-                         MONGOC_ERROR_COMMAND,
-                         MONGOC_ERROR_COMMAND_INVALID_ARG,
-                         "Cannot set bypassDocumentValidation for unacknowledged writes");
+         _mongoc_set_error (&result->error,
+                            MONGOC_ERROR_COMMAND,
+                            MONGOC_ERROR_COMMAND_INVALID_ARG,
+                            "Cannot set bypassDocumentValidation for unacknowledged writes");
          EXIT;
       }
    }
 
    if (crud->client_session && !mongoc_write_concern_is_acknowledged (crud->writeConcern)) {
       result->failed = true;
-      bson_set_error (&result->error,
-                      MONGOC_ERROR_COMMAND,
-                      MONGOC_ERROR_COMMAND_INVALID_ARG,
-                      "Cannot use client session with unacknowledged writes");
+      _mongoc_set_error (&result->error,
+                         MONGOC_ERROR_COMMAND,
+                         MONGOC_ERROR_COMMAND_INVALID_ARG,
+                         "Cannot use client session with unacknowledged writes");
       EXIT;
    }
 
@@ -1045,7 +1037,12 @@ _set_error_from_response (bson_t *bson_a
       }
 
       if (code && !mcommon_string_from_append_is_empty (&compound_err)) {
-         bson_set_error (error, domain, (uint32_t) code, "%s", mcommon_str_from_append (&compound_err));
+         _mongoc_set_error_with_category (error,
+                                          MONGOC_ERROR_CATEGORY_SERVER,
+                                          domain,
+                                          (uint32_t) code,
+                                          "%s",
+                                          mcommon_str_from_append (&compound_err));
       }
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern-private.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern-private.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern-private.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern-private.h	2025-06-19 15:42:22.000000000 +0000
@@ -25,12 +25,10 @@
 BSON_BEGIN_DECLS
 
 
-#define MONGOC_WRITE_CONCERN_FSYNC_DEFAULT -1
 #define MONGOC_WRITE_CONCERN_JOURNAL_DEFAULT -1
 
 
 struct _mongoc_write_concern_t {
-   int8_t fsync_; /* deprecated */
    int8_t journal;
    int32_t w;
    int64_t wtimeout;
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern.c 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern.c
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern.c	2025-06-19 15:42:22.000000000 +0000
@@ -15,7 +15,7 @@
  */
 
 
-#include <mongoc/mongoc-error.h>
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-log.h>
 #include <mongoc/mongoc-util-private.h>
 #include <mongoc/mongoc-write-concern.h>
@@ -42,7 +42,6 @@ mongoc_write_concern_new (void)
 
    write_concern = BSON_ALIGNED_ALLOC0 (mongoc_write_concern_t);
    write_concern->w = MONGOC_WRITE_CONCERN_W_DEFAULT;
-   write_concern->fsync_ = MONGOC_WRITE_CONCERN_FSYNC_DEFAULT;
    write_concern->journal = MONGOC_WRITE_CONCERN_JOURNAL_DEFAULT;
    write_concern->is_default = true;
 
@@ -59,7 +58,6 @@ mongoc_write_concern_copy (const mongoc_
 
    if (write_concern) {
       ret = mongoc_write_concern_new ();
-      ret->fsync_ = write_concern->fsync_;
       ret->journal = write_concern->journal;
       ret->w = write_concern->w;
       ret->wtimeout = write_concern->wtimeout;
@@ -90,33 +88,6 @@ mongoc_write_concern_destroy (mongoc_wri
 
 
 bool
-mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern)
-{
-   BSON_ASSERT (write_concern);
-   return (write_concern->fsync_ == true);
-}
-
-
-/**
- * mongoc_write_concern_set_fsync:
- * @write_concern: A mongoc_write_concern_t.
- * @fsync_: If the write concern requires fsync() by the server.
- *
- * Set if fsync() should be called on the server before acknowledging a
- * write request.
- */
-void
-mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, bool fsync_)
-{
-   BSON_ASSERT (write_concern);
-
-   write_concern->fsync_ = !!fsync_;
-   write_concern->is_default = false;
-   write_concern->frozen = false;
-}
-
-
-bool
 mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern)
 {
    BSON_ASSERT (write_concern);
@@ -347,10 +318,6 @@ _mongoc_write_concern_freeze (mongoc_wri
       BSON_APPEND_INT32 (compiled, "w", write_concern->w);
    }
 
-   if (write_concern->fsync_ != MONGOC_WRITE_CONCERN_FSYNC_DEFAULT) {
-      bson_append_bool (compiled, "fsync", 5, !!write_concern->fsync_);
-   }
-
    if (write_concern->journal != MONGOC_WRITE_CONCERN_JOURNAL_DEFAULT) {
       bson_append_bool (compiled, "j", 1, !!write_concern->journal);
    }
@@ -374,9 +341,8 @@ bool
 mongoc_write_concern_is_acknowledged (const mongoc_write_concern_t *write_concern)
 {
    if (write_concern) {
-      return (((write_concern->w != MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED) &&
-               (write_concern->w != MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) ||
-              write_concern->fsync_ == true || mongoc_write_concern_get_journal (write_concern));
+      return (((write_concern->w != MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)) ||
+              mongoc_write_concern_get_journal (write_concern));
    }
    return true;
 }
@@ -398,10 +364,9 @@ mongoc_write_concern_is_valid (const mon
       return false;
    }
 
-   /* Journal or fsync should require acknowledgement.  */
-   if ((write_concern->fsync_ == true || mongoc_write_concern_get_journal (write_concern)) &&
-       (write_concern->w == MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED ||
-        write_concern->w == MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) {
+   /* Journal should require acknowledgement.  */
+   if ((mongoc_write_concern_get_journal (write_concern)) &&
+       (write_concern->w == MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)) {
       return false;
    }
 
@@ -417,7 +382,7 @@ static bool
 _mongoc_write_concern_validate (const mongoc_write_concern_t *write_concern, bson_error_t *error)
 {
    if (write_concern && !mongoc_write_concern_is_valid (write_concern)) {
-      bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern");
+      _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern");
       return false;
    }
    return true;
@@ -450,7 +415,7 @@ _mongoc_parse_wc_err (const bson_t *doc,
             errmsg = bson_iter_utf8 (&inner, NULL);
          }
       }
-      bson_set_error (error, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg);
+      _mongoc_set_error (error, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg);
       return true;
    }
    return false;
@@ -511,7 +476,7 @@ _mongoc_write_concern_new_from_iter (con
       if (BSON_ITER_IS_KEY (&inner, "w")) {
          if (BSON_ITER_HOLDS_INT32 (&inner)) {
             w = bson_iter_int32 (&inner);
-            if (w < MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED) {
+            if (w < MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED) {
                goto fail;
             }
 
@@ -529,12 +494,8 @@ _mongoc_write_concern_new_from_iter (con
             goto fail;
          }
       } else if (BSON_ITER_IS_KEY (&inner, "fsync")) {
-         if (!BSON_ITER_HOLDS_BOOL (&inner)) {
-            goto fail;
-         }
-         BEGIN_IGNORE_DEPRECATIONS
-         mongoc_write_concern_set_fsync (write_concern, bson_iter_bool (&inner));
-         END_IGNORE_DEPRECATIONS
+         // fsync removed in C driver 2.0.
+         goto fail;
       } else if (BSON_ITER_IS_KEY (&inner, "j")) {
          if (!BSON_ITER_HOLDS_BOOL (&inner)) {
             goto fail;
@@ -556,7 +517,7 @@ _mongoc_write_concern_new_from_iter (con
    return write_concern;
 
 fail:
-   bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern");
+   _mongoc_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern");
    mongoc_write_concern_destroy (write_concern);
    return NULL;
 }
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc-write-concern.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc-write-concern.h	2025-06-19 15:42:22.000000000 +0000
@@ -27,7 +27,6 @@ BSON_BEGIN_DECLS
 
 
 #define MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED 0
-#define MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED -1 /* deprecated */
 #define MONGOC_WRITE_CONCERN_W_DEFAULT -2
 #define MONGOC_WRITE_CONCERN_W_MAJORITY -3
 #define MONGOC_WRITE_CONCERN_W_TAG -4
@@ -38,46 +37,61 @@ typedef struct _mongoc_write_concern_t m
 
 MONGOC_EXPORT (mongoc_write_concern_t *)
 mongoc_write_concern_new (void) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (mongoc_write_concern_t *)
 mongoc_write_concern_copy (const mongoc_write_concern_t *write_concern) BSON_GNUC_WARN_UNUSED_RESULT;
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_destroy (mongoc_write_concern_t *write_concern);
-MONGOC_EXPORT (bool)
-mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern) BSON_GNUC_DEPRECATED;
-MONGOC_EXPORT (void)
-mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, bool fsync_) BSON_GNUC_DEPRECATED;
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_journal_is_set (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern, bool journal);
+
 MONGOC_EXPORT (int32_t)
 mongoc_write_concern_get_w (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_w (mongoc_write_concern_t *write_concern, int32_t w);
+
 MONGOC_EXPORT (const char *)
 mongoc_write_concern_get_wtag (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern, const char *tag);
+
 MONGOC_EXPORT (int32_t)
 mongoc_write_concern_get_wtimeout (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (int64_t)
 mongoc_write_concern_get_wtimeout_int64 (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern, int64_t wtimeout_msec);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_get_wmajority (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (void)
 mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_is_acknowledged (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_is_valid (const mongoc_write_concern_t *write_concern);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_append (mongoc_write_concern_t *write_concern, bson_t *doc);
+
 MONGOC_EXPORT (bool)
 mongoc_write_concern_is_default (const mongoc_write_concern_t *write_concern);
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/mongoc.h 2.0.2-1/src/libmongoc/src/mongoc/mongoc.h
--- 1.30.4-1/src/libmongoc/src/mongoc/mongoc.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/mongoc.h	2025-06-19 15:42:22.000000000 +0000
@@ -34,7 +34,6 @@
 #include <mongoc/mongoc-config.h>
 #include <mongoc/mongoc-cursor.h>
 #include <mongoc/mongoc-database.h>
-#include <mongoc/mongoc-index.h>
 #include <mongoc/mongoc-error.h>
 #include <mongoc/mongoc-flags.h>
 #include <mongoc/mongoc-gridfs.h>
@@ -44,7 +43,6 @@
 #include <mongoc/mongoc-gridfs-file-page.h>
 #include <mongoc/mongoc-host-list.h>
 #include <mongoc/mongoc-init.h>
-#include <mongoc/mongoc-matcher.h>
 #include <mongoc/mongoc-handshake.h>
 #include <mongoc/mongoc-opcode.h>
 #include <mongoc/mongoc-log.h>
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc/service-gcp.c 2.0.2-1/src/libmongoc/src/mongoc/service-gcp.c
--- 1.30.4-1/src/libmongoc/src/mongoc/service-gcp.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc/service-gcp.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,6 +16,7 @@
 
 #include <mongoc/service-gcp.h>
 
+#include <mongoc/mongoc-error-private.h>
 #include <mongoc/mongoc-util-private.h>
 
 #define HOST "metadata.google.internal"
@@ -97,13 +98,13 @@ gcp_access_token_try_parse_from_json (gc
    const char *const token_type = !found ? NULL : bson_iter_utf8 (&iter, NULL);
 
    if (!(access_token && token_type)) {
-      bson_set_error (error,
-                      MONGOC_ERROR_GCP,
-                      MONGOC_ERROR_KMS_SERVER_BAD_JSON,
-                      "One or more required JSON properties are "
-                      "missing/invalid: data: %.*s",
-                      len,
-                      json);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_GCP,
+                         MONGOC_ERROR_KMS_SERVER_BAD_JSON,
+                         "One or more required JSON properties are "
+                         "missing/invalid: data: %.*s",
+                         len,
+                         json);
       goto done;
    }
 
@@ -148,13 +149,13 @@ gcp_access_token_from_gcp_server (gcp_se
 
    // Only accept an HTTP 200 as success
    if (resp.status != 200) {
-      bson_set_error (error,
-                      MONGOC_ERROR_GCP,
-                      MONGOC_ERROR_KMS_SERVER_HTTP,
-                      "Error from the GCP metadata server while looking for "
-                      "access token: %.*s",
-                      resp.body_len,
-                      resp.body);
+      _mongoc_set_error (error,
+                         MONGOC_ERROR_GCP,
+                         MONGOC_ERROR_KMS_SERVER_HTTP,
+                         "Error from the GCP metadata server while looking for "
+                         "access token: %.*s",
+                         resp.body_len,
+                         resp.body);
       goto fail;
    }
 
diff -pruN 1.30.4-1/src/libmongoc/src/mongoc-config.cmake 2.0.2-1/src/libmongoc/src/mongoc-config.cmake
--- 1.30.4-1/src/libmongoc/src/mongoc-config.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/src/mongoc-config.cmake	1970-01-01 00:00:00.000000000 +0000
@@ -1,45 +0,0 @@
-include(CMakeFindDependencyMacro)
-find_dependency(bson-1.0 @libmongoc_VERSION@)
-
-# If we need to import a TLS package for our imported targets, do that now:
-set(MONGOC_TLS_BACKEND [[@TLS_BACKEND@]])
-set(_tls_package [[@TLS_IMPORT_PACKAGE@]])
-if(_tls_package)
-  # We bring our own FindLibreSSL, since most systems do not have one yet. The system's version
-  # will be preferred, if possible.
-  set(_prev_path "${CMAKE_MODULE_PATH}")
-  list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/3rdParty")
-  find_dependency("${_tls_package}")
-  set(CMAKE_MODULE_PATH "${_prev_path}")
-endif()
-
-include("${CMAKE_CURRENT_LIST_DIR}/mongoc-targets.cmake")
-
-unset(_required)
-unset(_quiet)
-if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED)
-  set(_required REQUIRED)
-endif()
-if(${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY)
-  set(_quiet QUIET)
-endif()
-
-set(_mongoc_built_with_bundled_utf8proc "@USE_BUNDLED_UTF8PROC@")
-if(NOT _mongoc_built_with_bundled_utf8proc AND NOT TARGET PkgConfig::PC_UTF8PROC)
-  # libmongoc was compiled against an external utf8proc and links against a
-  # FindPkgConfig-generated IMPORTED target. Find that package and generate that
-  # imported target here:
-  find_dependency(PkgConfig)
-  pkg_check_modules(PC_UTF8PROC ${_required} ${_quiet} libutf8proc IMPORTED_TARGET GLOBAL)
-endif()
-
-# Find dependencies for SASL
-set(_sasl_backend [[@SASL_BACKEND@]])
-if(_sasl_backend STREQUAL "Cyrus")
-  # We need libsasl2. The find-module should be installed within this package.
-  # temporarily place it on the module search path:
-  set(_prev_path "${CMAKE_MODULE_PATH}")
-  list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/3rdParty")
-  find_dependency(SASL2 2.0)
-  set(CMAKE_MODULE_PATH "${_prev_path}")
-endif()
diff -pruN 1.30.4-1/src/libmongoc/tests/TestSuite.c 2.0.2-1/src/libmongoc/tests/TestSuite.c
--- 1.30.4-1/src/libmongoc/tests/TestSuite.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/TestSuite.c	2025-06-19 15:42:22.000000000 +0000
@@ -387,20 +387,11 @@ _TestSuite_TestFnCtxDtor (void *ctx)
 static void
 _print_getlasterror_win (const char *msg)
 {
-   LPTSTR err_msg;
-
-   FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-                  NULL,
-                  GetLastError (),
-                  MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
-                  /* FormatMessage is weird about this param. */
-                  (LPTSTR) &err_msg,
-                  0,
-                  NULL);
+   char *err_msg = mongoc_winerr_to_string (GetLastError ());
 
    test_error ("%s: %s", msg, err_msg);
 
-   LocalFree (err_msg);
+   bson_free (err_msg);
 }
 
 
diff -pruN 1.30.4-1/src/libmongoc/tests/TestSuite.h 2.0.2-1/src/libmongoc/tests/TestSuite.h
--- 1.30.4-1/src/libmongoc/tests/TestSuite.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/TestSuite.h	2025-06-19 15:42:22.000000000 +0000
@@ -120,6 +120,20 @@ bson_open (const char *filename, int fla
    } else                                    \
       ((void) 0)
 
+#define MONGOC_STDERR_HEXDUMP(pointer, length)                    \
+   if (1) {                                                       \
+      const uint8_t *_pointer = (const uint8_t *) (pointer);      \
+      const size_t _length = (length);                            \
+      fflush (stdout);                                            \
+      putc ('<', stderr);                                         \
+      for (size_t _i = 0; _i < _length; _i++) {                   \
+         fprintf (stderr, "%s%02x", _i ? " " : "", _pointer[_i]); \
+      }                                                           \
+      putc ('>', stderr);                                         \
+      fflush (stderr);                                            \
+   } else                                                         \
+      ((void) 0)
+
 #define ASSERT(Cond)                                                                                                 \
    do {                                                                                                              \
       if (!(Cond)) {                                                                                                 \
@@ -169,8 +183,8 @@ _test_error (const char *format, ...) BS
             int fd2 = bson_open ("failure.expected.bson", O_RDWR | O_CREAT, 0640);                              \
             ASSERT (fd1 != -1);                                                                                 \
             ASSERT (fd2 != -1);                                                                                 \
-            ASSERT ((bson)->len == bson_write (fd1, bson_data, (bson)->len));                                   \
-            ASSERT ((expected)->len == bson_write (fd2, expected_data, (expected)->len));                       \
+            ASSERT ((int) (bson)->len == (int) bson_write (fd1, bson_data, (bson)->len));                       \
+            ASSERT ((int) (expected)->len == (int) bson_write (fd2, expected_data, (expected)->len));           \
             bson_close (fd1);                                                                                   \
             bson_close (fd2);                                                                                   \
          }                                                                                                      \
@@ -260,15 +274,23 @@ _test_error (const char *format, ...) BS
 #define ASSERT_CMPDOUBLE(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "f", double)
 #define ASSERT_CMPVOID(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "p", void *)
 
-#define ASSERT_MEMCMP(a, b, n)                                                                                      \
-   do {                                                                                                             \
-      if (0 != memcmp (a, b, n)) {                                                                                  \
-         MONGOC_STDERR_PRINTF ("Failed comparing %d bytes: \"%.*s\" != \"%.*s\"", n, n, (char *) a, n, (char *) b); \
-         abort ();                                                                                                  \
-      }                                                                                                             \
+#define ASSERT_MEMCMP(a, b, n)                                                                             \
+   do {                                                                                                    \
+      const void *_a = (a);                                                                                \
+      const void *_b = (b);                                                                                \
+      const size_t _n = (n);                                                                               \
+      if (0 != memcmp (_a, _b, _n)) {                                                                      \
+         MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: Expected an exact match of %" PRIu64 " bytes:\n ", \
+                               (uint64_t) _n);                                                             \
+         MONGOC_STDERR_HEXDUMP (_a, _n);                                                                   \
+         fprintf (stderr, " !=\n ");                                                                       \
+         MONGOC_STDERR_HEXDUMP (_b, _n);                                                                   \
+         MONGOC_STDERR_PRINTF ("\n %s:%d %s()\n", __FILE__, (int) (__LINE__), BSON_FUNC);                  \
+         fflush (stderr);                                                                                  \
+         abort ();                                                                                         \
+      }                                                                                                    \
    } while (0)
 
-
 #ifdef ASSERT_ALMOST_EQUAL
 #undef ASSERT_ALMOST_EQUAL
 #endif
diff -pruN 1.30.4-1/src/libmongoc/tests/benchmark-tls-pooled.c 2.0.2-1/src/libmongoc/tests/benchmark-tls-pooled.c
--- 1.30.4-1/src/libmongoc/tests/benchmark-tls-pooled.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/benchmark-tls-pooled.c	2025-06-19 15:42:22.000000000 +0000
@@ -8,9 +8,12 @@
  */
 
 #include <mongoc/mongoc.h>
+#include <mlib/loop.h>
+
 #include <pthread.h>
 #include <stdio.h>
 
+
 static void *
 worker (void *data)
 {
@@ -50,7 +53,6 @@ main (int argc, char *argv[])
    mongoc_uri_t *uri;
    mongoc_client_pool_t *pool;
    pthread_t threads[num_clients];
-   unsigned i;
    void *ret;
 
    mongoc_init ();
@@ -74,11 +76,11 @@ main (int argc, char *argv[])
    pool = mongoc_client_pool_new (uri);
    mongoc_client_pool_set_error_api (pool, MONGOC_ERROR_API_VERSION_2);
 
-   for (i = 0; i < num_clients; i++) {
+   mlib_foreach_irange (i, num_clients) {
       pthread_create (&threads[i], NULL, worker, pool);
    }
 
-   for (i = 0; i < num_clients; i++) {
+   mlib_foreach_irange (i, num_clients) {
       pthread_join (threads[i], &ret);
    }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/bsonutil/bson-match.c 2.0.2-1/src/libmongoc/tests/bsonutil/bson-match.c
--- 1.30.4-1/src/libmongoc/tests/bsonutil/bson-match.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/bsonutil/bson-match.c	2025-06-19 15:42:22.000000000 +0000
@@ -20,6 +20,7 @@
 #include "TestSuite.h"
 #include "unified/util.h"
 #include <mongoc/utlist.h>
+#include <mlib/loop.h>
 
 typedef struct _special_functor_t {
    special_fn fn;
@@ -686,10 +687,8 @@ test_match (void)
        true},
       {"numeric type mismatch is ok", "{'a': 1}", "{'a': 1.0}", true},
       {"comparing number to string is an error", "{'a': 1}", "{'a': 'foo'}", false}};
-   int i;
 
-   for (i = 0; i < sizeof (tests) / sizeof (testcase_t); i++) {
-      testcase_t *test = tests + i;
+   mlib_foreach_arr (testcase_t, test, tests) {
       bson_error_t error;
       bson_val_t *expected = bson_val_from_json (test->expected);
       bson_val_t *actual = bson_val_from_json (test->actual);
diff -pruN 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/key-doc.json 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/key-doc.json
--- 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/key-doc.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/key-doc.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,30 @@
+{
+    "_id": {
+        "$binary": {
+            "base64": "EjRWeBI0mHYSNBI0VniQEg==",
+            "subType": "04"
+        }
+    },
+    "keyMaterial": {
+        "$binary": {
+            "base64": "sHe0kz57YW7v8g9VP9sf/+K1ex4JqKc5rf/URX3n3p8XdZ6+15uXPaSayC6adWbNxkFskuMCOifDoTT+rkqMtFkDclOy884RuGGtUysq3X7zkAWYTKi8QAfKkajvVbZl2y23UqgVasdQu3OVBQCrH/xY00nNAs/52e958nVjBuzQkSb1T8pKJAyjZsHJ60+FtnfafDZSTAIBJYn7UWBCwQ==",
+            "subType": "00"
+        }
+    },
+    "creationDate": {
+        "$date": {
+            "$numberLong": "1648914851981"
+        }
+    },
+    "updateDate": {
+        "$date": {
+            "$numberLong": "1648914851981"
+        }
+    },
+    "status": {
+        "$numberInt": "0"
+    },
+    "masterKey": {
+        "provider": "local"
+    }
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle.json 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle.json
--- 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,19 @@
+{
+    "properties": {
+        "csfle": {
+            "encrypt": {
+                "keyId": [
+                    {
+                        "$binary": {
+                            "base64": "EjRWeBI0mHYSNBI0VniQEg==",
+                            "subType": "04"
+                        }
+                    }
+                ],
+                "bsonType": "string",
+                "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
+            }
+        }
+    },
+    "bsonType": "object"
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle2.json 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle2.json
--- 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle2.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-csfle2.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,19 @@
+{
+    "properties": {
+        "csfle2": {
+            "encrypt": {
+                "keyId": [
+                    {
+                        "$binary": {
+                            "base64": "EjRWeBI0mHYSNBI0VniQEg==",
+                            "subType": "04"
+                        }
+                    }
+                ],
+                "bsonType": "string",
+                "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
+            }
+        }
+    },
+    "bsonType": "object"
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe.json 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe.json
--- 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,20 @@
+{
+    "escCollection": "enxcol_.qe.esc",
+    "ecocCollection": "enxcol_.qe.ecoc",
+    "fields": [
+        {
+            "keyId": {
+                "$binary": {
+                    "base64": "EjRWeBI0mHYSNBI0VniQEg==",
+                    "subType": "04"
+                }
+            },
+            "path": "qe",
+            "bsonType": "string",
+            "queries": {
+                "queryType": "equality",
+                "contention": 0
+            }
+        }
+    ]
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe2.json 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe2.json
--- 1.30.4-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe2.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/client_side_encryption_prose/lookup/schema-qe2.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,20 @@
+{
+    "escCollection": "enxcol_.qe2.esc",
+    "ecocCollection": "enxcol_.qe2.ecoc",
+    "fields": [
+        {
+            "keyId": {
+                "$binary": {
+                    "base64": "EjRWeBI0mHYSNBI0VniQEg==",
+                    "subType": "04"
+                }
+            },
+            "path": "qe2",
+            "bsonType": "string",
+            "queries": {
+                "queryType": "equality",
+                "contention": 0
+            }
+        }
+    ]
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/debug-stream.c 2.0.2-1/src/libmongoc/tests/debug-stream.c
--- 1.30.4-1/src/libmongoc/tests/debug-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/debug-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,10 +14,6 @@
  * limitations under the License.
  */
 
-
-#ifndef DEBUG_STREAM_H
-#define DEBUG_STREAM_H
-
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-client-private.h>
 
@@ -181,5 +177,3 @@ test_framework_set_debug_stream (mongoc_
    stats->client = client;
    mongoc_client_set_stream_initiator (client, debug_stream_initiator, stats);
 }
-
-#endif /* DEBUG_STREAM_H */
diff -pruN 1.30.4-1/src/libmongoc/tests/import-tests.cmake 2.0.2-1/src/libmongoc/tests/import-tests.cmake
--- 1.30.4-1/src/libmongoc/tests/import-tests.cmake	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/import-tests.cmake	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,7 @@
 include(TestProject)
 
+math(EXPR next_major_version "${PROJECT_VERSION_MAJOR}+1")
+
 # A bare find_package will succeed
 add_test_cmake_project(
    mongoc/CMake/bare-bson-import src/libmongoc/tests/cmake-import
@@ -21,31 +23,31 @@ add_test_cmake_project(
 )
 
 add_test_cmake_project(
-   mongoc/CMake/bson-import-1.0 src/libmongoc/tests/cmake-import
+   mongoc/CMake/bson-import-${PROJECT_VERSION_MAJOR}.0 src/libmongoc/tests/cmake-import
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=1.25;REQUIRED"
+      "FIND_BSON_ARGS=${PROJECT_VERSION_MAJOR}.0;REQUIRED"
       "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
 )
 
-# Try to import a too-new version of 1.x that will never exist
+# Try to import a too-new minor version that will never exist
 add_test_cmake_project(
    mongoc/CMake/bson-import-too-new-fails src/libmongoc/tests/cmake-import
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=1.9999.0"
+      "FIND_BSON_ARGS=${PROJECT_VERSION_MAJOR}.9999.0"
       EXPECT_FIND_BSON_FAILS=TRUE
 )
 
-# Try to import a 2.0 version, which is not installed in this test case
+# Try to import the next major version, which is not installed in this test case
 add_test_cmake_project(
-   mongoc/CMake/bson-import-2.0-fails src/libmongoc/tests/cmake-import
+   mongoc/CMake/bson-import-${next_major_version}.0-fails src/libmongoc/tests/cmake-import
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=2.0"
+      "FIND_BSON_ARGS=${next_major_version}.0"
       EXPECT_FIND_BSON_FAILS=TRUE
 )
 
@@ -64,7 +66,7 @@ add_test_cmake_project(
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=${PROJECT_VERSION}...1.9999.0;REQUIRED"
+      "FIND_BSON_ARGS=${PROJECT_VERSION}...${PROJECT_VERSION_MAJOR}.9999.0;REQUIRED"
       "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
 )
 
@@ -82,7 +84,7 @@ add_test_cmake_project(
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=1.0...2.0;REQUIRED"
+      "FIND_BSON_ARGS=${PROJECT_VERSION_MAJOR}.0...${next_major_version}.0;REQUIRED"
       "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
 )
 
@@ -91,7 +93,7 @@ add_test_cmake_project(
    INSTALL_PARENT
    SETTINGS
       FIND_BSON=1
-      "FIND_BSON_ARGS=2.0...<3"
+      "FIND_BSON_ARGS=${next_major_version}.0...<${next_major_version}.9999"
       EXPECT_FIND_BSON_FAILS=TRUE
 )
 
@@ -112,3 +114,38 @@ add_test_cmake_project(
       "FIND_BSON_ARGS=REQUIRED;OPTIONAL_COMPONENTS;foo"
       "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
 )
+
+add_test_cmake_project(
+   mongoc/pkg-config/bson-import-shared src/libmongoc/tests/pkg-config-import
+   INSTALL_PARENT
+   SETTINGS
+      PKG_CONFIG_SEARCH=bson${PROJECT_VERSION_MAJOR}
+      "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
+)
+
+add_test_cmake_project(
+   mongoc/pkg-config/bson-import-static src/libmongoc/tests/pkg-config-import
+   INSTALL_PARENT
+   SETTINGS
+      PKG_CONFIG_SEARCH=bson${PROJECT_VERSION_MAJOR}-static
+      "EXPECT_BSON_VERSION=${mongo-c-driver_VERSION_FULL}"
+      EXPECT_BSON_STATIC=1
+)
+
+add_test_cmake_project(
+   mongoc/pkg-config/mongoc-import-shared src/libmongoc/tests/pkg-config-import
+   INSTALL_PARENT
+   SETTINGS
+      PKG_CONFIG_SEARCH=mongoc${PROJECT_VERSION_MAJOR}
+      "EXPECT_MONGOC_VERSION=${mongo-c-driver_VERSION_FULL}"
+)
+
+add_test_cmake_project(
+   mongoc/pkg-config/mongoc-import-static src/libmongoc/tests/pkg-config-import
+   INSTALL_PARENT
+   SETTINGS
+      PKG_CONFIG_SEARCH=mongoc${PROJECT_VERSION_MAJOR}-static
+      "EXPECT_MONGOC_VERSION=${mongo-c-driver_VERSION_FULL}"
+      EXPECT_BSON_STATIC=1
+      EXPECT_MONGOC_STATIC=1
+)
diff -pruN 1.30.4-1/src/libmongoc/tests/json/connection_uri/additional-nonspec-tests.json 2.0.2-1/src/libmongoc/tests/json/connection_uri/additional-nonspec-tests.json
--- 1.30.4-1/src/libmongoc/tests/json/connection_uri/additional-nonspec-tests.json	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/json/connection_uri/additional-nonspec-tests.json	2025-06-19 15:42:22.000000000 +0000
@@ -174,16 +174,15 @@
       }
     },
     {
-      "description": "Valid connection pool options are parsed correctly, libmongoc version without maxIdleTimeMS",
-      "uri": "mongodb://example.com/?waitQueueTimeoutMS=50000&maxPoolSize=5&minPoolSize=3",
+      "description": "Valid connection pool options are parsed correctly, libmongoc version without maxIdleTimeMS or minPoolSize",
+      "uri": "mongodb://example.com/?waitQueueTimeoutMS=50000&maxPoolSize=5",
       "valid": true,
       "warning": false,
       "hosts": null,
       "auth": null,
       "options": {
         "waitQueueTimeoutMS": 50000,
-        "maxPoolSize": 5,
-        "minPoolSize": 3
+        "maxPoolSize": 5
       }
     }
   ]
diff -pruN 1.30.4-1/src/libmongoc/tests/json/server_discovery_and_monitoring/rs/secondary_ipv6_literal.json 2.0.2-1/src/libmongoc/tests/json/server_discovery_and_monitoring/rs/secondary_ipv6_literal.json
--- 1.30.4-1/src/libmongoc/tests/json/server_discovery_and_monitoring/rs/secondary_ipv6_literal.json	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/json/server_discovery_and_monitoring/rs/secondary_ipv6_literal.json	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,38 @@
+{
+    "description": "Secondary with IPv6 literal",
+    "uri": "mongodb://[::1]/?replicaSet=rs",
+    "phases": [
+        {
+            "responses": [
+                [
+                    "[::1]:27017",
+                    {
+                        "ok": 1,
+                        "helloOk": true,
+                        "isWritablePrimary": false,
+                        "secondary": true,
+                        "setName": "rs",
+                        "me": "[::1]:27017",
+                        "hosts": [
+                            "[::1]:27017"
+                        ],
+                        "minWireVersion": 0,
+                        "maxWireVersion": 26
+                    }
+                ]
+            ],
+            "outcome": {
+                "servers": {
+                    "[::1]:27017": {
+                        "type": "RSSecondary",
+                        "setName": "rs"
+                    }
+                },
+                "topologyType": "ReplicaSetNoPrimary",
+                "setName": "rs",
+                "logicalSessionTimeoutMinutes": null,
+                "compatible": true
+            }
+        }
+    ]
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/json-test-operations.c 2.0.2-1/src/libmongoc/tests/json-test-operations.c
--- 1.30.4-1/src/libmongoc/tests/json-test-operations.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/json-test-operations.c	2025-06-19 15:42:22.000000000 +0000
@@ -1229,10 +1229,20 @@ count (mongoc_collection_t *collection,
    } else if (!strcmp (name, "estimatedDocumentCount")) {
       r = mongoc_collection_estimated_document_count (collection, &opts, read_prefs, reply, &error);
    } else if (!strcmp (name, "count")) {
-      /* deprecated old count function */
-      r = mongoc_collection_count_with_opts (collection, MONGOC_QUERY_NONE, &filter, 0, 0, &opts, read_prefs, &error);
-      /* fake a reply for the test framework's sake */
-      bson_init (reply);
+      // "count" previously referred to the deprecated helper: `mongoc_collection_count_with_opts`.
+      // Run the "count" command directly to support tests. See: CRUD spec "Count API Details".
+      bson_t *cmd = BCON_NEW ("count", mongoc_collection_get_name (collection));
+      BSON_ASSERT (BSON_APPEND_DOCUMENT (cmd, "query", &filter));
+      bool ok = mongoc_collection_read_command_with_opts (collection, cmd, read_prefs, &opts, reply, &error);
+      if (!ok) {
+         // Set resulting count to -1 to indicate failure.
+         r = -1;
+      } else {
+         bson_iter_t iter;
+         BSON_ASSERT (bson_iter_init_find (&iter, reply, "n"));
+         r = bson_iter_as_int64 (&iter);
+      }
+      bson_destroy (cmd);
    } else {
       test_error ("count() called with unrecognized operation name %s", name);
       return false;
diff -pruN 1.30.4-1/src/libmongoc/tests/json-test.c 2.0.2-1/src/libmongoc/tests/json-test.c
--- 1.30.4-1/src/libmongoc/tests/json-test.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/json-test.c	2025-06-19 15:42:22.000000000 +0000
@@ -22,6 +22,7 @@
 #include <mongoc/mongoc-uri-private.h>
 #include <mongoc/mongoc-client-side-encryption.h>
 #include <common-oid-private.h>
+#include <mlib/loop.h>
 
 #include "json-test.h"
 #include "json-test-operations.h"
@@ -655,43 +656,35 @@ collect_tests_from_dir (char (*paths)[MA
 bson_t *
 get_bson_from_json_file (char *filename)
 {
-   FILE *file;
-   long length;
-   bson_t *data;
-   bson_error_t error;
-   const char *buffer;
-
-   file = fopen (filename, "rb");
+   FILE *const file = fopen (filename, "rb");
    if (!file) {
-      return NULL;
+      test_error ("Failed to open JSON file: %s", filename);
    }
 
    /* get file length */
    fseek (file, 0, SEEK_END);
-   length = ftell (file);
+   const long length = ftell (file);
    fseek (file, 0, SEEK_SET);
    if (length < 1) {
-      return NULL;
+      test_error ("Failed to read length of JSON file: %s", filename);
    }
 
    /* read entire file into buffer */
-   buffer = (const char *) bson_malloc0 (length);
-   if (fread ((void *) buffer, 1, length, file) != length) {
-      test_error ("Failed to read JSON file into buffer");
-   }
-
+   char *const buffer = (char *) bson_malloc0 (length);
+   const size_t nread = fread (buffer, 1, length, file);
    fclose (file);
-   if (!buffer) {
-      return NULL;
+   if (mlib_cmp (nread, !=, length)) {
+      test_error ("Failed to read JSON file [%s] into buffer", filename);
    }
 
    /* convert to bson */
-   data = bson_new_from_json ((const uint8_t *) buffer, length, &error);
+   bson_error_t error;
+   bson_t *const data = bson_new_from_json ((const uint8_t *) buffer, length, &error);
    if (!data) {
       test_error ("Cannot parse %s: %s", filename, error.message);
    }
 
-   bson_free ((void *) buffer);
+   bson_free (buffer);
 
    return data;
 }
@@ -1381,12 +1374,12 @@ set_auto_encryption_opts (mongoc_client_
    auto_encryption_opts = mongoc_auto_encryption_opts_new ();
 
    if (bson_iter_init_find (&iter, &opts, "kmsProviders")) {
-      bson_t kms_providers;
+      bson_t kms_providers = BSON_INITIALIZER;
       bson_t tls_opts = BSON_INITIALIZER;
       bson_t tmp;
 
       bson_iter_bson (&iter, &tmp);
-      bson_copy_to_excluding (
+      bson_copy_to_excluding_noinit (
          &tmp, &kms_providers, "aws", "awsTemporary", "awsTemporaryNoSessionToken", "azure", "gcp", "kmip", NULL);
 
       /* AWS credentials are set from environment variables. */
@@ -1819,7 +1812,6 @@ json_test_config_cleanup (json_test_conf
 static bson_t *
 _skip_if_unsupported (const char *test_name, bson_t *original)
 {
-   int i;
    bool skip = false;
    const char *unsupported_tests[] = {"/retryable_reads/legacy/gridfs-downloadByName",
                                       "/retryable_reads/legacy/gridfs-downloadByName-serverErrors",
@@ -1831,8 +1823,8 @@ _skip_if_unsupported (const char *test_n
                                       "/retryable_reads/legacy/listIndexNames-serverErrors",
                                       "/retryable_reads/legacy/mapReduce"};
 
-   for (i = 0; i < sizeof (unsupported_tests) / sizeof (unsupported_tests[0]); i++) {
-      if (0 == strcmp (test_name, unsupported_tests[i])) {
+   mlib_foreach_arr (const char *, test, unsupported_tests) {
+      if (0 == strcmp (test_name, *test)) {
          skip = true;
          break;
       }
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future-functions.c 2.0.2-1/src/libmongoc/tests/mock_server/future-functions.c
--- 1.30.4-1/src/libmongoc/tests/mock_server/future-functions.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future-functions.c	2025-06-19 15:42:22.000000000 +0000
@@ -258,23 +258,6 @@ BSON_THREAD_FUN (background_mongoc_clien
 }
 
 static
-BSON_THREAD_FUN (background_mongoc_client_kill_cursor, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_void_type;
-
-   mongoc_client_kill_cursor (
-      future_value_get_mongoc_client_ptr (future_get_param (future, 0)),
-      future_value_get_int64_t (future_get_param (future, 1)));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
 BSON_THREAD_FUN (background_mongoc_client_watch, data)
 {
    future_t *future = (future_t *) data;
@@ -319,58 +302,7 @@ BSON_THREAD_FUN (background_mongoc_colle
 }
 
 static
-BSON_THREAD_FUN (background_mongoc_collection_count, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_int64_t_type;
-
-   future_value_set_int64_t (
-      &return_value,
-      mongoc_collection_count (
-         future_value_get_mongoc_collection_ptr (future_get_param (future, 0)),
-         future_value_get_mongoc_query_flags_t (future_get_param (future, 1)),
-         future_value_get_const_bson_ptr (future_get_param (future, 2)),
-         future_value_get_int64_t (future_get_param (future, 3)),
-         future_value_get_int64_t (future_get_param (future, 4)),
-         future_value_get_const_mongoc_read_prefs_ptr (future_get_param (future, 5)),
-         future_value_get_bson_error_ptr (future_get_param (future, 6))
-      ));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
-BSON_THREAD_FUN (background_mongoc_collection_count_with_opts, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_int64_t_type;
-
-   future_value_set_int64_t (
-      &return_value,
-      mongoc_collection_count_with_opts (
-         future_value_get_mongoc_collection_ptr (future_get_param (future, 0)),
-         future_value_get_mongoc_query_flags_t (future_get_param (future, 1)),
-         future_value_get_const_bson_ptr (future_get_param (future, 2)),
-         future_value_get_int64_t (future_get_param (future, 3)),
-         future_value_get_int64_t (future_get_param (future, 4)),
-         future_value_get_const_bson_ptr (future_get_param (future, 5)),
-         future_value_get_const_mongoc_read_prefs_ptr (future_get_param (future, 6)),
-         future_value_get_bson_error_ptr (future_get_param (future, 7))
-      ));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
-BSON_THREAD_FUN (background_mongoc_collection_create_index_with_opts, data)
+BSON_THREAD_FUN (background_mongoc_collection_create_indexes_with_opts, data)
 {
    future_t *future = (future_t *) data;
    future_value_t return_value;
@@ -379,10 +311,10 @@ BSON_THREAD_FUN (background_mongoc_colle
 
    future_value_set_bool (
       &return_value,
-      mongoc_collection_create_index_with_opts (
+      mongoc_collection_create_indexes_with_opts (
          future_value_get_mongoc_collection_ptr (future_get_param (future, 0)),
-         future_value_get_const_bson_ptr (future_get_param (future, 1)),
-         future_value_get_const_mongoc_index_opt_t (future_get_param (future, 2)),
+         future_value_get_mongoc_index_model_t_ptr_const_ptr (future_get_param (future, 1)),
+         future_value_get_size_t (future_get_param (future, 2)),
          future_value_get_const_bson_ptr (future_get_param (future, 3)),
          future_value_get_bson_ptr (future_get_param (future, 4)),
          future_value_get_bson_error_ptr (future_get_param (future, 5))
@@ -508,28 +440,6 @@ BSON_THREAD_FUN (background_mongoc_colle
 }
 
 static
-BSON_THREAD_FUN (background_mongoc_collection_stats, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_bool_type;
-
-   future_value_set_bool (
-      &return_value,
-      mongoc_collection_stats (
-         future_value_get_mongoc_collection_ptr (future_get_param (future, 0)),
-         future_value_get_const_bson_ptr (future_get_param (future, 1)),
-         future_value_get_bson_ptr (future_get_param (future, 2)),
-         future_value_get_bson_error_ptr (future_get_param (future, 3))
-      ));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
 BSON_THREAD_FUN (background_mongoc_collection_insert_many, data)
 {
    future_t *future = (future_t *) data;
@@ -648,30 +558,6 @@ BSON_THREAD_FUN (background_mongoc_colle
 }
 
 static
-BSON_THREAD_FUN (background_mongoc_collection_insert_bulk, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_bool_type;
-
-   future_value_set_bool (
-      &return_value,
-      mongoc_collection_insert_bulk (
-         future_value_get_mongoc_collection_ptr (future_get_param (future, 0)),
-         future_value_get_mongoc_insert_flags_t (future_get_param (future, 1)),
-         future_value_get_const_bson_ptr_ptr (future_get_param (future, 2)),
-         future_value_get_uint32_t (future_get_param (future, 3)),
-         future_value_get_const_mongoc_write_concern_ptr (future_get_param (future, 4)),
-         future_value_get_bson_error_ptr (future_get_param (future, 5))
-      ));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
 BSON_THREAD_FUN (background_mongoc_cluster_run_command_parts, data)
 {
    future_t *future = (future_t *) data;
@@ -915,27 +801,6 @@ BSON_THREAD_FUN (background_mongoc_gridf
 }
 
 static
-BSON_THREAD_FUN (background_mongoc_gridfs_find_one, data)
-{
-   future_t *future = (future_t *) data;
-   future_value_t return_value;
-
-   return_value.type = future_value_mongoc_gridfs_file_ptr_type;
-
-   future_value_set_mongoc_gridfs_file_ptr (
-      &return_value,
-      mongoc_gridfs_find_one (
-         future_value_get_mongoc_gridfs_ptr (future_get_param (future, 0)),
-         future_value_get_const_bson_ptr (future_get_param (future, 1)),
-         future_value_get_bson_error_ptr (future_get_param (future, 2))
-      ));
-
-   future_resolve (future, return_value);
-
-   BSON_THREAD_RETURN;
-}
-
-static
 BSON_THREAD_FUN (background_mongoc_gridfs_file_remove, data)
 {
    future_t *future = (future_t *) data;
@@ -1630,24 +1495,6 @@ future_client_read_write_command_with_op
 }
 
 future_t *
-future_client_kill_cursor (
-   mongoc_client_ptr client,
-   int64_t cursor_id)
-{
-   future_t *future = future_new (future_value_void_type,
-                                  2);
-   
-   future_value_set_mongoc_client_ptr (
-      future_get_param (future, 0), client);
-   
-   future_value_set_int64_t (
-      future_get_param (future, 1), cursor_id);
-   
-   future_start (future, background_mongoc_client_kill_cursor);
-   return future;
-}
-
-future_t *
 future_client_watch (
    mongoc_client_ptr client,
    const_bson_ptr pipeline,
@@ -1700,90 +1547,10 @@ future_collection_aggregate (
 }
 
 future_t *
-future_collection_count (
+future_collection_create_indexes_with_opts (
    mongoc_collection_ptr collection,
-   mongoc_query_flags_t flags,
-   const_bson_ptr query,
-   int64_t skip,
-   int64_t limit,
-   const_mongoc_read_prefs_ptr read_prefs,
-   bson_error_ptr error)
-{
-   future_t *future = future_new (future_value_int64_t_type,
-                                  7);
-   
-   future_value_set_mongoc_collection_ptr (
-      future_get_param (future, 0), collection);
-   
-   future_value_set_mongoc_query_flags_t (
-      future_get_param (future, 1), flags);
-   
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 2), query);
-   
-   future_value_set_int64_t (
-      future_get_param (future, 3), skip);
-   
-   future_value_set_int64_t (
-      future_get_param (future, 4), limit);
-   
-   future_value_set_const_mongoc_read_prefs_ptr (
-      future_get_param (future, 5), read_prefs);
-   
-   future_value_set_bson_error_ptr (
-      future_get_param (future, 6), error);
-   
-   future_start (future, background_mongoc_collection_count);
-   return future;
-}
-
-future_t *
-future_collection_count_with_opts (
-   mongoc_collection_ptr collection,
-   mongoc_query_flags_t flags,
-   const_bson_ptr query,
-   int64_t skip,
-   int64_t limit,
-   const_bson_ptr opts,
-   const_mongoc_read_prefs_ptr read_prefs,
-   bson_error_ptr error)
-{
-   future_t *future = future_new (future_value_int64_t_type,
-                                  8);
-   
-   future_value_set_mongoc_collection_ptr (
-      future_get_param (future, 0), collection);
-   
-   future_value_set_mongoc_query_flags_t (
-      future_get_param (future, 1), flags);
-   
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 2), query);
-   
-   future_value_set_int64_t (
-      future_get_param (future, 3), skip);
-   
-   future_value_set_int64_t (
-      future_get_param (future, 4), limit);
-   
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 5), opts);
-   
-   future_value_set_const_mongoc_read_prefs_ptr (
-      future_get_param (future, 6), read_prefs);
-   
-   future_value_set_bson_error_ptr (
-      future_get_param (future, 7), error);
-   
-   future_start (future, background_mongoc_collection_count_with_opts);
-   return future;
-}
-
-future_t *
-future_collection_create_index_with_opts (
-   mongoc_collection_ptr collection,
-   const_bson_ptr keys,
-   const_mongoc_index_opt_t opt,
+   mongoc_index_model_t_ptr_const_ptr models,
+   size_t num_models,
    const_bson_ptr opts,
    bson_ptr reply,
    bson_error_ptr error)
@@ -1794,11 +1561,11 @@ future_collection_create_index_with_opts
    future_value_set_mongoc_collection_ptr (
       future_get_param (future, 0), collection);
    
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 1), keys);
+   future_value_set_mongoc_index_model_t_ptr_const_ptr (
+      future_get_param (future, 1), models);
    
-   future_value_set_const_mongoc_index_opt_t (
-      future_get_param (future, 2), opt);
+   future_value_set_size_t (
+      future_get_param (future, 2), num_models);
    
    future_value_set_const_bson_ptr (
       future_get_param (future, 3), opts);
@@ -1809,7 +1576,7 @@ future_collection_create_index_with_opts
    future_value_set_bson_error_ptr (
       future_get_param (future, 5), error);
    
-   future_start (future, background_mongoc_collection_create_index_with_opts);
+   future_start (future, background_mongoc_collection_create_indexes_with_opts);
    return future;
 }
 
@@ -1960,32 +1727,6 @@ future_collection_find_indexes_with_opts
 }
 
 future_t *
-future_collection_stats (
-   mongoc_collection_ptr collection,
-   const_bson_ptr options,
-   bson_ptr stats,
-   bson_error_ptr error)
-{
-   future_t *future = future_new (future_value_bool_type,
-                                  4);
-   
-   future_value_set_mongoc_collection_ptr (
-      future_get_param (future, 0), collection);
-   
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 1), options);
-   
-   future_value_set_bson_ptr (
-      future_get_param (future, 2), stats);
-   
-   future_value_set_bson_error_ptr (
-      future_get_param (future, 3), error);
-   
-   future_start (future, background_mongoc_collection_stats);
-   return future;
-}
-
-future_t *
 future_collection_insert_many (
    mongoc_collection_ptr collection,
    const_bson_ptr_ptr documents,
@@ -2148,40 +1889,6 @@ future_collection_write_command_with_opt
 }
 
 future_t *
-future_collection_insert_bulk (
-   mongoc_collection_ptr collection,
-   mongoc_insert_flags_t flags,
-   const_bson_ptr_ptr documents,
-   uint32_t n_documents,
-   const_mongoc_write_concern_ptr write_concern,
-   bson_error_ptr error)
-{
-   future_t *future = future_new (future_value_bool_type,
-                                  6);
-   
-   future_value_set_mongoc_collection_ptr (
-      future_get_param (future, 0), collection);
-   
-   future_value_set_mongoc_insert_flags_t (
-      future_get_param (future, 1), flags);
-   
-   future_value_set_const_bson_ptr_ptr (
-      future_get_param (future, 2), documents);
-   
-   future_value_set_uint32_t (
-      future_get_param (future, 3), n_documents);
-   
-   future_value_set_const_mongoc_write_concern_ptr (
-      future_get_param (future, 4), write_concern);
-   
-   future_value_set_bson_error_ptr (
-      future_get_param (future, 5), error);
-   
-   future_start (future, background_mongoc_collection_insert_bulk);
-   return future;
-}
-
-future_t *
 future_cluster_run_command_parts (
    mongoc_cluster_ptr cluster,
    mongoc_server_stream_ptr server_stream,
@@ -2445,28 +2152,6 @@ future_gridfs_file_readv (
    return future;
 }
 
-future_t *
-future_gridfs_find_one (
-   mongoc_gridfs_ptr gridfs,
-   const_bson_ptr query,
-   bson_error_ptr error)
-{
-   future_t *future = future_new (future_value_mongoc_gridfs_file_ptr_type,
-                                  3);
-   
-   future_value_set_mongoc_gridfs_ptr (
-      future_get_param (future, 0), gridfs);
-   
-   future_value_set_const_bson_ptr (
-      future_get_param (future, 1), query);
-   
-   future_value_set_bson_error_ptr (
-      future_get_param (future, 2), error);
-   
-   future_start (future, background_mongoc_gridfs_find_one);
-   return future;
-}
-
 future_t *
 future_gridfs_file_remove (
    mongoc_gridfs_file_ptr file,
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future-functions.h 2.0.2-1/src/libmongoc/tests/mock_server/future-functions.h
--- 1.30.4-1/src/libmongoc/tests/mock_server/future-functions.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future-functions.h	2025-06-19 15:42:22.000000000 +0000
@@ -130,14 +130,6 @@ future_client_read_write_command_with_op
 
 
 future_t *
-future_client_kill_cursor (
-
-   mongoc_client_ptr client,
-   int64_t cursor_id
-);
-
-
-future_t *
 future_client_watch (
 
    mongoc_client_ptr client,
@@ -158,38 +150,11 @@ future_collection_aggregate (
 
 
 future_t *
-future_collection_count (
-
-   mongoc_collection_ptr collection,
-   mongoc_query_flags_t flags,
-   const_bson_ptr query,
-   int64_t skip,
-   int64_t limit,
-   const_mongoc_read_prefs_ptr read_prefs,
-   bson_error_ptr error
-);
-
-
-future_t *
-future_collection_count_with_opts (
-
-   mongoc_collection_ptr collection,
-   mongoc_query_flags_t flags,
-   const_bson_ptr query,
-   int64_t skip,
-   int64_t limit,
-   const_bson_ptr opts,
-   const_mongoc_read_prefs_ptr read_prefs,
-   bson_error_ptr error
-);
-
-
-future_t *
-future_collection_create_index_with_opts (
+future_collection_create_indexes_with_opts (
 
    mongoc_collection_ptr collection,
-   const_bson_ptr keys,
-   const_mongoc_index_opt_t opt,
+   mongoc_index_model_t_ptr_const_ptr models,
+   size_t num_models,
    const_bson_ptr opts,
    bson_ptr reply,
    bson_error_ptr error
@@ -251,16 +216,6 @@ future_collection_find_indexes_with_opts
 
 
 future_t *
-future_collection_stats (
-
-   mongoc_collection_ptr collection,
-   const_bson_ptr options,
-   bson_ptr stats,
-   bson_error_ptr error
-);
-
-
-future_t *
 future_collection_insert_many (
 
    mongoc_collection_ptr collection,
@@ -319,18 +274,6 @@ future_collection_write_command_with_opt
 
 
 future_t *
-future_collection_insert_bulk (
-
-   mongoc_collection_ptr collection,
-   mongoc_insert_flags_t flags,
-   const_bson_ptr_ptr documents,
-   uint32_t n_documents,
-   const_mongoc_write_concern_ptr write_concern,
-   bson_error_ptr error
-);
-
-
-future_t *
 future_cluster_run_command_parts (
 
    mongoc_cluster_ptr cluster,
@@ -438,15 +381,6 @@ future_gridfs_file_readv (
 );
 
 
-future_t *
-future_gridfs_find_one (
-
-   mongoc_gridfs_ptr gridfs,
-   const_bson_ptr query,
-   bson_error_ptr error
-);
-
-
 future_t *
 future_gridfs_file_remove (
 
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future-value.c 2.0.2-1/src/libmongoc/tests/mock_server/future-value.c
--- 1.30.4-1/src/libmongoc/tests/mock_server/future-value.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future-value.c	2025-06-19 15:42:22.000000000 +0000
@@ -449,20 +449,6 @@ future_value_get_mongoc_query_flags_t (f
 }
 
 void
-future_value_set_const_mongoc_index_opt_t (future_value_t *future_value, const_mongoc_index_opt_t value)
-{
-   future_value->type = future_value_const_mongoc_index_opt_t_type;
-   future_value->value.const_mongoc_index_opt_t_value = value;
-}
-
-const_mongoc_index_opt_t
-future_value_get_const_mongoc_index_opt_t (future_value_t *future_value)
-{
-   BSON_ASSERT (future_value->type == future_value_const_mongoc_index_opt_t_type);
-   return future_value->value.const_mongoc_index_opt_t_value;
-}
-
-void
 future_value_set_mongoc_server_description_ptr (future_value_t *future_value, mongoc_server_description_ptr value)
 {
    future_value->type = future_value_mongoc_server_description_ptr_type;
@@ -615,3 +601,17 @@ future_value_get_const_mongoc_ss_log_con
    BSON_ASSERT (future_value->type == future_value_const_mongoc_ss_log_context_ptr_type);
    return future_value->value.const_mongoc_ss_log_context_ptr_value;
 }
+
+void
+future_value_set_mongoc_index_model_t_ptr_const_ptr (future_value_t *future_value, mongoc_index_model_t_ptr_const_ptr value)
+{
+   future_value->type = future_value_mongoc_index_model_t_ptr_const_ptr_type;
+   future_value->value.mongoc_index_model_t_ptr_const_ptr_value = value;
+}
+
+mongoc_index_model_t_ptr_const_ptr
+future_value_get_mongoc_index_model_t_ptr_const_ptr (future_value_t *future_value)
+{
+   BSON_ASSERT (future_value->type == future_value_mongoc_index_model_t_ptr_const_ptr_type);
+   return future_value->value.mongoc_index_model_t_ptr_const_ptr_value;
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future-value.h 2.0.2-1/src/libmongoc/tests/mock_server/future-value.h
--- 1.30.4-1/src/libmongoc/tests/mock_server/future-value.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future-value.h	2025-06-19 15:42:22.000000000 +0000
@@ -40,7 +40,6 @@ typedef mongoc_gridfs_file_t * mongoc_gr
 typedef mongoc_gridfs_t * mongoc_gridfs_ptr;
 typedef mongoc_iovec_t * mongoc_iovec_ptr;
 typedef mongoc_server_stream_t * mongoc_server_stream_ptr;
-typedef const mongoc_index_opt_t * const_mongoc_index_opt_t;
 typedef mongoc_server_description_t * mongoc_server_description_ptr;
 typedef mongoc_topology_t * mongoc_topology_ptr;
 typedef mongoc_write_concern_t * mongoc_write_concern_ptr;
@@ -50,6 +49,7 @@ typedef const mongoc_iovec_t * const_mon
 typedef const mongoc_read_prefs_t * const_mongoc_read_prefs_ptr;
 typedef const mongoc_write_concern_t * const_mongoc_write_concern_ptr;
 typedef const mongoc_ss_log_context_t * const_mongoc_ss_log_context_ptr;
+typedef mongoc_index_model_t *const * mongoc_index_model_t_ptr_const_ptr;
 
 typedef enum {
    future_value_no_type = 0,
@@ -83,7 +83,6 @@ typedef enum {
    future_value_mongoc_iovec_ptr_type,
    future_value_mongoc_server_stream_ptr_type,
    future_value_mongoc_query_flags_t_type,
-   future_value_const_mongoc_index_opt_t_type,
    future_value_mongoc_server_description_ptr_type,
    future_value_mongoc_ss_optype_t_type,
    future_value_mongoc_topology_ptr_type,
@@ -95,6 +94,7 @@ typedef enum {
    future_value_const_mongoc_read_prefs_ptr_type,
    future_value_const_mongoc_write_concern_ptr_type,
    future_value_const_mongoc_ss_log_context_ptr_type,
+   future_value_mongoc_index_model_t_ptr_const_ptr_type,
    future_value_void_type,
 
 } future_value_type_t;
@@ -133,7 +133,6 @@ typedef struct _future_value_t
       mongoc_iovec_ptr mongoc_iovec_ptr_value;
       mongoc_server_stream_ptr mongoc_server_stream_ptr_value;
       mongoc_query_flags_t mongoc_query_flags_t_value;
-      const_mongoc_index_opt_t const_mongoc_index_opt_t_value;
       mongoc_server_description_ptr mongoc_server_description_ptr_value;
       mongoc_ss_optype_t mongoc_ss_optype_t_value;
       mongoc_topology_ptr mongoc_topology_ptr_value;
@@ -145,6 +144,7 @@ typedef struct _future_value_t
       const_mongoc_read_prefs_ptr const_mongoc_read_prefs_ptr_value;
       const_mongoc_write_concern_ptr const_mongoc_write_concern_ptr_value;
       const_mongoc_ss_log_context_ptr const_mongoc_ss_log_context_ptr_value;
+      mongoc_index_model_t_ptr_const_ptr mongoc_index_model_t_ptr_const_ptr_value;
 
    } value;
 } future_value_t;
@@ -432,15 +432,6 @@ future_value_get_mongoc_query_flags_t (
    future_value_t *future_value);
 
 void
-future_value_set_const_mongoc_index_opt_t(
-   future_value_t *future_value,
-   const_mongoc_index_opt_t value);
-
-const_mongoc_index_opt_t
-future_value_get_const_mongoc_index_opt_t (
-   future_value_t *future_value);
-
-void
 future_value_set_mongoc_server_description_ptr(
    future_value_t *future_value,
    mongoc_server_description_ptr value);
@@ -539,6 +530,15 @@ const_mongoc_ss_log_context_ptr
 future_value_get_const_mongoc_ss_log_context_ptr (
    future_value_t *future_value);
 
+void
+future_value_set_mongoc_index_model_t_ptr_const_ptr(
+   future_value_t *future_value,
+   mongoc_index_model_t_ptr_const_ptr value);
+
+mongoc_index_model_t_ptr_const_ptr
+future_value_get_mongoc_index_model_t_ptr_const_ptr (
+   future_value_t *future_value);
+
 
 #ifdef __clang__
 #pragma clang diagnostic pop
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future.c 2.0.2-1/src/libmongoc/tests/mock_server/future.c
--- 1.30.4-1/src/libmongoc/tests/mock_server/future.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future.c	2025-06-19 15:42:22.000000000 +0000
@@ -334,16 +334,6 @@ future_get_mongoc_query_flags_t (future_
    FUTURE_TIMEOUT_ABORT;
 }
 
-const_mongoc_index_opt_t
-future_get_const_mongoc_index_opt_t (future_t *future)
-{
-   if (future_wait (future)) {
-      return future_value_get_const_mongoc_index_opt_t (&future->return_value);
-   }
-
-   FUTURE_TIMEOUT_ABORT;
-}
-
 mongoc_server_description_ptr
 future_get_mongoc_server_description_ptr (future_t *future)
 {
@@ -452,6 +442,16 @@ future_get_const_mongoc_ss_log_context_p
    }
 
    FUTURE_TIMEOUT_ABORT;
+}
+
+mongoc_index_model_t_ptr_const_ptr
+future_get_mongoc_index_model_t_ptr_const_ptr (future_t *future)
+{
+   if (future_wait (future)) {
+      return future_value_get_mongoc_index_model_t_ptr_const_ptr (&future->return_value);
+   }
+
+   FUTURE_TIMEOUT_ABORT;
 }
 
 
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/future.h 2.0.2-1/src/libmongoc/tests/mock_server/future.h
--- 1.30.4-1/src/libmongoc/tests/mock_server/future.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/future.h	2025-06-19 15:42:22.000000000 +0000
@@ -132,9 +132,6 @@ future_get_mongoc_server_stream_ptr (fut
 mongoc_query_flags_t
 future_get_mongoc_query_flags_t (future_t *future);
 
-const_mongoc_index_opt_t
-future_get_const_mongoc_index_opt_t (future_t *future);
-
 mongoc_server_description_ptr
 future_get_mongoc_server_description_ptr (future_t *future);
 
@@ -168,6 +165,9 @@ future_get_const_mongoc_write_concern_pt
 const_mongoc_ss_log_context_ptr
 future_get_const_mongoc_ss_log_context_ptr (future_t *future);
 
+mongoc_index_model_t_ptr_const_ptr
+future_get_mongoc_index_model_t_ptr_const_ptr (future_t *future);
+
 
 void future_destroy (future_t *future);
 
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/mock-server.c 2.0.2-1/src/libmongoc/tests/mock_server/mock-server.c
--- 1.30.4-1/src/libmongoc/tests/mock_server/mock-server.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/mock-server.c	2025-06-19 15:42:22.000000000 +0000
@@ -30,7 +30,8 @@
 #include "../TestSuite.h"
 #include <common-string-private.h>
 #include <common-json-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/intencode.h>
 
 #ifdef BSON_HAVE_STRINGS_H
 #include <strings.h>
@@ -356,7 +357,7 @@ mock_server_run (mock_server_t *server)
    // socklen_t: an unsigned opaque integral type of length of at least 32 bits.
    // To forestall portability problems, it is recommended that applications
    // should not use values larger than 2^32 - 1.
-   BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, bind_addr_len));
+   BSON_ASSERT (mlib_in_range (uint32_t, bind_addr_len));
 
    if (-1 == mongoc_socket_bind (ssock, (struct sockaddr *) bind_addr, (uint32_t) bind_addr_len)) {
       perror ("Failed to bind socket");
@@ -1803,7 +1804,6 @@ static BSON_THREAD_FUN (worker_thread, d
    mongoc_buffer_t buffer;
    bool handled;
    bson_error_t error;
-   int32_t msg_len;
    sync_queue_t *requests;
    sync_queue_t *replies;
    request_t *request;
@@ -1844,9 +1844,7 @@ again:
    /* loop, checking for requests to receive or replies to send */
    if (_mongoc_buffer_fill (&buffer, client_stream, 4, 10, &error) > 0) {
       BSON_ASSERT (buffer.len >= 4);
-
-      memcpy (&msg_len, buffer.data, 4);
-      msg_len = BSON_UINT32_FROM_LE (msg_len);
+      const int32_t msg_len = mlib_read_u32le (buffer.data);
 
       if (msg_len < 16) {
          MONGOC_WARNING ("No data");
@@ -2065,7 +2063,7 @@ _mock_server_reply_with_stream (mock_ser
 
    const ssize_t n_written = mongoc_stream_writev (client, iov, iovcnt, -1);
 
-   BSON_ASSERT (mcommon_cmp_equal_su (n_written, expected));
+   BSON_ASSERT (mlib_cmp (n_written, ==, expected));
 
    bson_free (iov);
    mcd_rpc_message_destroy (rpc);
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/mock-server.h 2.0.2-1/src/libmongoc/tests/mock_server/mock-server.h
--- 1.30.4-1/src/libmongoc/tests/mock_server/mock-server.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/mock-server.h	2025-06-19 15:42:22.000000000 +0000
@@ -20,6 +20,16 @@
 #include <bson/bson.h>
 
 #include <mongoc/mongoc-flags-private.h>
+
+// mongoc_reply_flags_t represents flags for the legacy OP_REPLY protocol:
+typedef enum {
+   MONGOC_REPLY_NONE = 0,
+   MONGOC_REPLY_CURSOR_NOT_FOUND = 1 << 0,
+   MONGOC_REPLY_QUERY_FAILURE = 1 << 1,
+   MONGOC_REPLY_SHARD_CONFIG_STALE = 1 << 2,
+   MONGOC_REPLY_AWAIT_CAPABLE = 1 << 3,
+} mongoc_reply_flags_t;
+
 #include <mongoc/mongoc-uri.h>
 
 #ifdef MONGOC_ENABLE_SSL
diff -pruN 1.30.4-1/src/libmongoc/tests/mock_server/request.c 2.0.2-1/src/libmongoc/tests/mock_server/request.c
--- 1.30.4-1/src/libmongoc/tests/mock_server/request.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/mock_server/request.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,12 +18,13 @@
 #include <mongoc/mongoc-rpc-private.h>
 #include <mongoc/mongoc.h>
 
+#include <mlib/intencode.h>
 #include "mock-server.h"
 #include "../test-conveniences.h"
 #include "../TestSuite.h"
 #include <common-string-private.h>
 #include <common-json-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 static bool
 is_command_ns (const char *ns);
@@ -56,7 +57,7 @@ request_new (const mongoc_buffer_t *buff
    BSON_ASSERT_PARAM (client);
    BSON_ASSERT_PARAM (replies);
 
-   BSON_ASSERT (mcommon_in_range_signed (size_t, msg_len));
+   BSON_ASSERT (mlib_in_range (size_t, msg_len));
 
    request_t *const request = (request_t *) bson_malloc0 (sizeof *request);
 
@@ -128,7 +129,7 @@ assert_request_matches_flags (const requ
    BSON_ASSERT (request);
 
    const int32_t request_flags = mcd_rpc_op_query_get_flags (request->rpc);
-   if (mcommon_cmp_not_equal_su (request_flags, flags)) {
+   if (mlib_cmp (request_flags, !=, flags)) {
       mcommon_string_append_t str_request_flags, str_flags;
       mcommon_string_new_as_append (&str_request_flags);
       mcommon_string_new_as_append (&str_flags);
@@ -211,7 +212,7 @@ request_matches_query (const request_t *
    assert_request_matches_flags (request, flags);
 
    const int32_t request_skip = mcd_rpc_op_query_get_number_to_skip (request->rpc);
-   if (mcommon_cmp_not_equal_su (request_skip, skip)) {
+   if (mlib_cmp (request_skip, !=, skip)) {
       test_error ("requests's skip = %" PRId32 ", expected %" PRIu32 ": %s", request_skip, skip, doc_as_json);
       goto done;
    }
@@ -523,18 +524,6 @@ query_flags_str (mcommon_string_append_t
 }
 
 
-static int32_t
-length_prefix (const uint8_t *data)
-{
-   uint32_t storage;
-   memcpy (&storage, data, sizeof (storage));
-   storage = BSON_UINT32_FROM_LE (storage);
-   int32_t res;
-   memcpy (&res, &storage, sizeof (storage));
-   return res;
-}
-
-
 static void
 request_from_query (request_t *request)
 {
@@ -551,7 +540,7 @@ request_from_query (request_t *request)
    const void *const request_fields = mcd_rpc_op_query_get_return_fields_selector (request->rpc);
 
    {
-      const int32_t len = length_prefix (request_query);
+      const int32_t len = mlib_read_i32le (request_query);
       bson_t *const query = bson_new_from_data (request_query, (size_t) len);
       BSON_ASSERT (query);
       _mongoc_array_append_val (&request->docs, query);
@@ -572,7 +561,7 @@ request_from_query (request_t *request)
    }
 
    if (request_fields) {
-      const int32_t len = length_prefix (request_fields);
+      const int32_t len = mlib_read_i32le (request_fields);
       bson_t *const fields = bson_new_from_data (request_fields, (size_t) len);
       BSON_ASSERT (fields);
       _mongoc_array_append_val (&request->docs, fields);
@@ -625,7 +614,7 @@ parse_op_msg_doc (request_t *request, co
          mcommon_string_append (msg_as_str, ", ");
       }
 
-      const int32_t doc_len = length_prefix (pos);
+      const int32_t doc_len = mlib_read_i32le (pos);
       const bson_t *const doc = bson_new_from_data (pos, (size_t) doc_len);
       BSON_ASSERT (doc);
       _mongoc_array_append_val (&request->docs, doc);
@@ -653,7 +642,7 @@ request_from_op_msg (request_t *request)
       switch (kind) {
       case 0: { /* a single BSON document */
          const void *const body = mcd_rpc_op_msg_section_get_body (request->rpc, index);
-         parse_op_msg_doc (request, body, (size_t) length_prefix (body), &msg_as_str);
+         parse_op_msg_doc (request, body, (size_t) mlib_read_i32le (body), &msg_as_str);
          break;
       }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/pkg-config-import/CMakeLists.txt 2.0.2-1/src/libmongoc/tests/pkg-config-import/CMakeLists.txt
--- 1.30.4-1/src/libmongoc/tests/pkg-config-import/CMakeLists.txt	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/pkg-config-import/CMakeLists.txt	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,32 @@
+cmake_minimum_required(VERSION 3.15)
+project(pkg-config-import-test LANGUAGES C)
+
+# This is a test case that tries to build against bson/mongoc using pkg-config.
+# Even though this is a CMake project, we import by talking to `pkg-config`
+
+include(CTest)
+
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(thing REQUIRED IMPORTED_TARGET "${PKG_CONFIG_SEARCH}")
+
+add_compile_definitions(
+    "EXPECT_BSON_VERSION=\"${EXPECT_BSON_VERSION}\""
+    "EXPECT_MONGOC_VERSION=\"${EXPECT_MONGOC_VERSION}\""
+    EXPECT_BSON_STATIC=$<BOOL:${EXPECT_BSON_STATIC}>
+    EXPECT_MONGOC_STATIC=$<BOOL:${EXPECT_MONGOC_STATIC}>
+    )
+
+add_executable(my-app app.c)
+target_link_libraries(my-app PRIVATE PkgConfig::thing)
+
+if(EXPECT_BSON_VERSION)
+    add_executable(use-bson use-bson.c)
+    target_link_libraries(use-bson PRIVATE PkgConfig::thing)
+    add_test(use-bson use-bson)
+endif()
+
+if(EXPECT_MONGOC_VERSION)
+    add_executable(use-mongoc use-mongoc.c)
+    target_link_libraries(use-mongoc PRIVATE PkgConfig::thing)
+    add_test(use-mongoc use-mongoc)
+endif()
diff -pruN 1.30.4-1/src/libmongoc/tests/pkg-config-import/app.c 2.0.2-1/src/libmongoc/tests/pkg-config-import/app.c
--- 1.30.4-1/src/libmongoc/tests/pkg-config-import/app.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/pkg-config-import/app.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,4 @@
+int
+main ()
+{
+}
\ No newline at end of file
diff -pruN 1.30.4-1/src/libmongoc/tests/pkg-config-import/use-bson.c 2.0.2-1/src/libmongoc/tests/pkg-config-import/use-bson.c
--- 1.30.4-1/src/libmongoc/tests/pkg-config-import/use-bson.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/pkg-config-import/use-bson.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,22 @@
+#include <bson/bson.h>
+#include <stdio.h>
+
+#ifndef EXPECT_BSON_VERSION
+#error This file requires EXPECT_BSON_VERSION to be defined
+#define EXPECT_BSON_VERSION ""
+#endif
+
+#if EXPECT_BSON_STATIC != defined(BSON_STATIC)
+#error Static/dynamic mismatch
+#endif
+
+int
+main (void)
+{
+   if (strcmp (BSON_VERSION_S, EXPECT_BSON_VERSION)) {
+      fprintf (
+         stderr, "Wrong BSON_MAJOR_VERSION found (Expected “%s”, but got “%s”)", EXPECT_BSON_VERSION, BSON_VERSION_S);
+      return 2;
+   }
+   return 0;
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/pkg-config-import/use-mongoc.c 2.0.2-1/src/libmongoc/tests/pkg-config-import/use-mongoc.c
--- 1.30.4-1/src/libmongoc/tests/pkg-config-import/use-mongoc.c	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/pkg-config-import/use-mongoc.c	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,22 @@
+#include <mongoc/mongoc.h>
+#include <stdio.h>
+
+#ifndef EXPECT_MONGOC_VERSION
+#error This file requires EXPECT_MONGOC_VERSION to be defined
+#define EXPECT_MONGOC_VERSION ""
+#endif
+
+int
+main (void)
+{
+   mongoc_client_t *const cl = mongoc_client_new ("mongodb://foo");
+   mongoc_client_destroy (cl);
+   if (strcmp (MONGOC_VERSION_S, EXPECT_MONGOC_VERSION)) {
+      fprintf (stderr,
+               "Wrong MONGOC_MAJOR_VERSION found (Expected “%s”, but got “%s”)",
+               EXPECT_MONGOC_VERSION,
+               MONGOC_VERSION_S);
+      return 2;
+   }
+   return 0;
+}
diff -pruN 1.30.4-1/src/libmongoc/tests/ssl-test.c 2.0.2-1/src/libmongoc/tests/ssl-test.c
--- 1.30.4-1/src/libmongoc/tests/ssl-test.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/ssl-test.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,8 +16,6 @@
 
 #define NUM_IOVECS 2000
 
-#define LOCALHOST "127.0.0.1"
-
 /** this function is meant to be run from ssl_test as a child thread
  *
  * It:
@@ -234,7 +232,7 @@ static BSON_THREAD_FUN (ssl_test_client,
    wiov.iov_len = 4;
    r = mongoc_stream_writev (ssl_stream, &wiov, 1, TIMEOUT);
 
-   BSON_ASSERT (r == wiov.iov_len);
+   BSON_ASSERT (mlib_cmp (r, ==, wiov.iov_len));
 
    for (i = 0; i < NUM_IOVECS; i++) {
       wiov_many[i].iov_base = (void *) "foo";
@@ -242,7 +240,7 @@ static BSON_THREAD_FUN (ssl_test_client,
    }
 
    r = mongoc_stream_writev (ssl_stream, wiov_many, NUM_IOVECS, TIMEOUT);
-   BSON_ASSERT (r == wiov_many[0].iov_len * NUM_IOVECS);
+   BSON_ASSERT (mlib_cmp (r, ==, wiov_many[0].iov_len * NUM_IOVECS));
 
    riov.iov_len = 1;
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-conveniences.c 2.0.2-1/src/libmongoc/tests/test-conveniences.c
--- 1.30.4-1/src/libmongoc/tests/test-conveniences.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-conveniences.c	2025-06-19 15:42:22.000000000 +0000
@@ -277,19 +277,6 @@ bson_lookup_doc (const bson_t *b, const
    bson_iter_bson (&iter, doc);
 }
 
-void
-bson_lookup_doc_null_ok (const bson_t *b, const char *key, bson_t *doc)
-{
-   bson_iter_t iter;
-
-   bson_lookup (b, key, &iter);
-   if (!BSON_ITER_HOLDS_NULL (&iter)) {
-      bson_iter_bson (&iter, doc);
-   } else {
-      bson_init (doc);
-   }
-}
-
 
 /*--------------------------------------------------------------------------
  *
@@ -840,13 +827,11 @@ derive (match_ctx_t *ctx, match_ctx_t *d
  *
  *       Does "doc" match "pattern"?
  *
- *       mongoc_matcher_t prohibits $-prefixed keys, which is something
- *       we need to test in e.g. test_mongoc_client_read_prefs, so this
- *       does *not* use mongoc_matcher_t. Instead, "doc" matches "pattern"
- *       if its key-value pairs are a simple superset of pattern's. Order
- *       matters.
+ *       "doc" matches "pattern" if its key-value pairs are a simple
+ *       superset of pattern's. Order matters.
  *
- *       The only special pattern syntaxes are:
+ *       Matching $-prefixed keys is supported (e.g. `$readPreference`)
+ *       excluding these special patterns:
  *         "field": {"$exists": true/false}
  *         "field": {"$empty": true/false}
  *         "field": {"$$type": "type string"}
diff -pruN 1.30.4-1/src/libmongoc/tests/test-conveniences.h 2.0.2-1/src/libmongoc/tests/test-conveniences.h
--- 1.30.4-1/src/libmongoc/tests/test-conveniences.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-conveniences.h	2025-06-19 15:42:22.000000000 +0000
@@ -81,6 +81,9 @@ json_with_all_types (void);
 #define realpath(path, expanded) GetFullPathName (path, PATH_MAX, expanded, NULL)
 #endif
 
+void
+bson_lookup (const bson_t *bson, const char *path, bson_iter_t *out);
+
 const char *
 bson_lookup_utf8 (const bson_t *b, const char *key);
 
@@ -96,9 +99,6 @@ bson_lookup_bson (const bson_t *b, const
 void
 bson_lookup_doc (const bson_t *b, const char *key, bson_t *doc);
 
-void
-bson_lookup_doc_null_ok (const bson_t *b, const char *key, bson_t *doc);
-
 bool
 bson_lookup_bool (const bson_t *b, const char *key);
 
@@ -209,7 +209,7 @@ match_json (const bson_t *doc,
 
 #define ASSERT_EQUAL_BSON(expected, actual)                                   \
    do {                                                                       \
-      bson_t *_expected_bson = expected, *_actual_bson = actual;              \
+      const bson_t *_expected_bson = expected, *_actual_bson = actual;        \
       char *_expected_str, *_actual_str;                                      \
       _expected_str = bson_as_canonical_extended_json (_expected_bson, NULL); \
       _actual_str = bson_as_canonical_extended_json (_actual_bson, NULL);     \
diff -pruN 1.30.4-1/src/libmongoc/tests/test-happy-eyeballs.c 2.0.2-1/src/libmongoc/tests/test-happy-eyeballs.c
--- 1.30.4-1/src/libmongoc/tests/test-happy-eyeballs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-happy-eyeballs.c	2025-06-19 15:42:22.000000000 +0000
@@ -319,8 +319,8 @@ _testcase_run (he_testcase_t *testcase)
    duration_ms = (bson_get_monotonic_time () - testcase->state.start) / (1000);
 
    {
-      bool within_expected_duration =
-         duration_ms >= expected->duration_min_ms && duration_ms < expected->duration_max_ms;
+      bool within_expected_duration = mlib_cmp (duration_ms, >=, expected->duration_min_ms) //
+                                      && mlib_cmp (duration_ms, <, expected->duration_max_ms);
       if (!within_expected_duration) {
          /* this is a timing failure, this may have been a fluke, retry once. */
          ASSERT_WITH_MSG (!testcase->state.last_duration,
diff -pruN 1.30.4-1/src/libmongoc/tests/test-libmongoc-main.c 2.0.2-1/src/libmongoc/tests/test-libmongoc-main.c
--- 1.30.4-1/src/libmongoc/tests/test-libmongoc-main.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-libmongoc-main.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,14 +24,14 @@ main (int argc, char *argv[])
    } else                                      \
       ((void) 0)
 
-   TEST_INSTALL (test_atomic_install);
    TEST_INSTALL (test_bcon_basic_install);
    TEST_INSTALL (test_bcon_extract_install);
    TEST_INSTALL (test_bson_corpus_install);
    TEST_INSTALL (test_bson_error_install);
    TEST_INSTALL (test_bson_install);
-   TEST_INSTALL (test_bson_sync_install);
    TEST_INSTALL (test_bson_version_install);
+   TEST_INSTALL (test_bson_vector_install);
+   TEST_INSTALL (test_install_generated_bson_validation);
    TEST_INSTALL (test_clock_install);
    TEST_INSTALL (test_decimal128_install);
    TEST_INSTALL (test_endian_install);
@@ -45,10 +45,9 @@ main (int argc, char *argv[])
    TEST_INSTALL (test_value_install);
    TEST_INSTALL (test_writer_install);
    TEST_INSTALL (test_b64_install);
-   TEST_INSTALL (test_bson_cmp_install);
-   TEST_INSTALL (test_mcommon_cmp_install);
    TEST_INSTALL (test_mcommon_atomic_install);
    TEST_INSTALL (test_mcommon_oid_install);
+   TEST_INSTALL (test_mlib_install);
 
    /* libmongoc */
 
@@ -67,7 +66,6 @@ main (int argc, char *argv[])
    TEST_INSTALL (test_bulk_install);
    TEST_INSTALL (test_cluster_install);
    TEST_INSTALL (test_collection_install);
-   TEST_INSTALL (test_collection_find_install);
    TEST_INSTALL (test_collection_find_with_opts_install);
    TEST_INSTALL (test_connection_uri_install);
    TEST_INSTALL (test_command_logging_and_monitoring_install);
@@ -86,7 +84,6 @@ main (int argc, char *argv[])
    TEST_INSTALL (test_log_install);
    TEST_INSTALL (test_structured_log_install);
    TEST_INSTALL (test_long_namespace_install);
-   TEST_INSTALL (test_matcher_install);
    TEST_INSTALL (test_mongos_pinning_install);
    TEST_INSTALL (test_queue_install);
    TEST_INSTALL (test_primary_stepdown_install);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-libmongoc.c 2.0.2-1/src/libmongoc/tests/test-libmongoc.c
--- 1.30.4-1/src/libmongoc/tests/test-libmongoc.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-libmongoc.c	2025-06-19 15:42:22.000000000 +0000
@@ -2273,6 +2273,8 @@ WIRE_VERSION_CHECKS (23)
 WIRE_VERSION_CHECKS (24)
 /* wire version 25 begins with the 8.0 release. */
 WIRE_VERSION_CHECKS (25)
+/* wire version 26 begins with the 8.1 release. */
+WIRE_VERSION_CHECKS (26)
 
 int
 test_framework_skip_if_no_dual_ip_hostname (void)
diff -pruN 1.30.4-1/src/libmongoc/tests/test-libmongoc.h 2.0.2-1/src/libmongoc/tests/test-libmongoc.h
--- 1.30.4-1/src/libmongoc/tests/test-libmongoc.h	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-libmongoc.h	2025-06-19 15:42:22.000000000 +0000
@@ -216,6 +216,8 @@ WIRE_VERSION_CHECK_DECLS (23)
 WIRE_VERSION_CHECK_DECLS (24)
 /* wire version 25 begins with the 8.0 release. */
 WIRE_VERSION_CHECK_DECLS (25)
+/* wire version 26 begins with the 8.1 release. */
+WIRE_VERSION_CHECK_DECLS (26)
 
 #undef WIRE_VERSION_CHECK_DECLS
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mcd-rpc.c 2.0.2-1/src/libmongoc/tests/test-mcd-rpc.c
--- 1.30.4-1/src/libmongoc/tests/test-mcd-rpc.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mcd-rpc.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,12 +1,13 @@
 #include <mongoc/mcd-rpc.h>
 
 #include <mongoc/mongoc-iovec.h>
+#include <mlib/intencode.h>
 
 #include "test-conveniences.h"
 #include "TestSuite.h"
 
 #include <inttypes.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 // clang-format off
@@ -328,22 +329,6 @@
    } else                                                                                   \
       (void) 0
 
-
-static int32_t
-_int32_from_le (const void *data)
-{
-   BSON_ASSERT_PARAM (data);
-   return bson_iter_int32_unsafe (&(bson_iter_t){.raw = data});
-}
-
-static int64_t
-_int64_from_le (const void *data)
-{
-   BSON_ASSERT_PARAM (data);
-   return bson_iter_int64_unsafe (&(bson_iter_t){.raw = data});
-}
-
-
 static void
 test_rpc_message_from_data_op_compressed_valid (void)
 {
@@ -356,7 +341,7 @@ test_rpc_message_from_data_op_compressed
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -420,7 +405,7 @@ _test_rpc_message_from_data_op_msg_valid
    mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
    ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-   ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+   ASSERT (mlib_in_range (int32_t, data_len));
    ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
    ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
    ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -470,7 +455,7 @@ _test_rpc_message_from_data_op_msg_valid
    mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
    ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-   ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+   ASSERT (mlib_in_range (int32_t, data_len));
    ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
    ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
    ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -507,7 +492,7 @@ _test_rpc_message_from_data_op_msg_valid
       ASSERT (sequence);
       ASSERT_CMPSIZE_T (mcd_rpc_op_msg_section_get_document_sequence_length (rpc, 1u), ==, 15u);
 
-      const int32_t bson_len = _int32_from_le (sequence);
+      const int32_t bson_len = mlib_read_i32le (sequence);
       ASSERT_CMPINT32 (bson_len, ==, 15);
 
       bson_t bson;
@@ -542,7 +527,7 @@ _test_rpc_message_from_data_op_msg_valid
    mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
    ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-   ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+   ASSERT (mlib_in_range (int32_t, data_len));
    ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
    ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
    ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -578,7 +563,7 @@ _test_rpc_message_from_data_op_msg_valid
       const void *const sequence = mcd_rpc_op_msg_section_get_document_sequence (rpc, 1u);
       ASSERT (sequence);
 
-      const int32_t bson_len = _int32_from_le (sequence);
+      const int32_t bson_len = mlib_read_i32le (sequence);
       ASSERT_CMPINT32 (bson_len, ==, 15);
 
       bson_t bson;
@@ -598,7 +583,7 @@ _test_rpc_message_from_data_op_msg_valid
       // BSON objects, index 0.
       {
          const uint8_t *const doc_0 = sequence;
-         const int32_t bson_len = _int32_from_le (doc_0);
+         const int32_t bson_len = mlib_read_i32le (doc_0);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -610,7 +595,7 @@ _test_rpc_message_from_data_op_msg_valid
       // BSON objects, index 1.
       {
          const uint8_t *const doc_1 = sequence + 16;
-         const int32_t bson_len = _int32_from_le (doc_1);
+         const int32_t bson_len = mlib_read_i32le (doc_1);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -659,7 +644,7 @@ test_rpc_message_from_data_op_reply_vali
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -681,7 +666,7 @@ test_rpc_message_from_data_op_reply_vali
       // Documents, index 0.
       {
          const uint8_t *const doc_0 = documents;
-         const int32_t bson_len = _int32_from_le (doc_0);
+         const int32_t bson_len = mlib_read_i32le (doc_0);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -693,7 +678,7 @@ test_rpc_message_from_data_op_reply_vali
       // Documents, index 1.
       {
          const uint8_t *const doc_1 = documents + 16;
-         const int32_t bson_len = _int32_from_le (doc_1);
+         const int32_t bson_len = mlib_read_i32le (doc_1);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -759,7 +744,7 @@ test_rpc_message_from_data_op_update_val
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -773,7 +758,7 @@ test_rpc_message_from_data_op_update_val
          const uint8_t *const selector = mcd_rpc_op_update_get_selector (rpc);
          ASSERT_CMPSIZE_T ((size_t) (selector - data), ==, 32u);
 
-         const int32_t selector_len = _int32_from_le (selector);
+         const int32_t selector_len = mlib_read_i32le (selector);
          ASSERT_CMPINT32 (selector_len, ==, 16);
 
          bson_t bson;
@@ -786,7 +771,7 @@ test_rpc_message_from_data_op_update_val
          const uint8_t *const update = mcd_rpc_op_update_get_update (rpc);
          ASSERT_CMPSIZE_T ((size_t) (update - data), ==, 48u);
 
-         const int32_t update_len = _int32_from_le (update);
+         const int32_t update_len = mlib_read_i32le (update);
          ASSERT_CMPINT32 (update_len, ==, 14);
 
          bson_t bson;
@@ -822,7 +807,7 @@ test_rpc_message_from_data_op_insert_val
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -839,7 +824,7 @@ test_rpc_message_from_data_op_insert_val
       // Documents, index 0.
       {
          const uint8_t *const doc_0 = documents;
-         const int32_t bson_len = _int32_from_le (doc_0);
+         const int32_t bson_len = mlib_read_i32le (doc_0);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -851,7 +836,7 @@ test_rpc_message_from_data_op_insert_val
       // Documents, index 1.
       {
          const uint8_t *const doc_1 = documents + 16;
-         const int32_t bson_len = _int32_from_le (doc_1);
+         const int32_t bson_len = mlib_read_i32le (doc_1);
          ASSERT_CMPINT32 (bson_len, ==, 16);
 
          bson_t bson;
@@ -901,7 +886,7 @@ test_rpc_message_from_data_op_query_vali
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -919,7 +904,7 @@ test_rpc_message_from_data_op_query_vali
          const uint8_t *const query = mcd_rpc_op_query_get_query (rpc);
          ASSERT_CMPSIZE_T ((size_t) (query - data), ==, 36u);
 
-         const int32_t query_len = _int32_from_le (query);
+         const int32_t query_len = mlib_read_i32le (query);
          ASSERT_CMPINT32 (query_len, ==, 13);
 
          bson_t bson;
@@ -932,7 +917,7 @@ test_rpc_message_from_data_op_query_vali
          const uint8_t *const selector = mcd_rpc_op_query_get_return_fields_selector (rpc);
          ASSERT_CMPSIZE_T ((size_t) (selector - data), ==, 49u);
 
-         const int32_t selector_len = _int32_from_le (selector);
+         const int32_t selector_len = mlib_read_i32le (selector);
          ASSERT_CMPINT32 (selector_len, ==, 16);
 
          bson_t bson;
@@ -1005,7 +990,7 @@ test_rpc_message_from_data_op_get_more_v
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -1033,7 +1018,7 @@ test_rpc_message_from_data_op_delete_val
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -1047,7 +1032,7 @@ test_rpc_message_from_data_op_delete_val
          const uint8_t *const selector = mcd_rpc_op_delete_get_selector (rpc);
          ASSERT_CMPSIZE_T ((size_t) (selector - data), ==, 32u);
 
-         const int32_t selector_len = _int32_from_le (selector);
+         const int32_t selector_len = mlib_read_i32le (selector);
          ASSERT_CMPINT32 (selector_len, ==, 16);
 
          bson_t bson;
@@ -1072,7 +1057,7 @@ test_rpc_message_from_data_op_kill_curso
       mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end);
 
       ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len);
-      ASSERT (mcommon_in_range_unsigned (int32_t, data_len));
+      ASSERT (mlib_in_range (int32_t, data_len));
       ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len);
       ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060);
       ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096);
@@ -2104,8 +2089,8 @@ test_rpc_message_to_iovecs_op_kill_curso
 
       const int64_t *const cursor_ids = (const int64_t *) iovec->iov_base;
 
-      const int64_t cursor_id_0 = _int64_from_le (cursor_ids + 0);
-      const int64_t cursor_id_1 = _int64_from_le (cursor_ids + 1);
+      const int64_t cursor_id_0 = mlib_read_i64le (cursor_ids + 0);
+      const int64_t cursor_id_1 = mlib_read_i64le (cursor_ids + 1);
 
       ASSERT_CMPINT64 (cursor_id_0, ==, 1230066625199609624);
       ASSERT_CMPINT64 (cursor_id_1, ==, 2387509390608836392);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-aggregate.c 2.0.2-1/src/libmongoc/tests/test-mongoc-aggregate.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-aggregate.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-aggregate.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,5 +1,6 @@
 #include <mongoc/mongoc.h>
 #include <mongoc/mongoc-client-private.h>
+#include <mlib/loop.h>
 
 #include "TestSuite.h"
 #include "mock_server/mock-server.h"
@@ -74,8 +75,6 @@ _test_query_flag (mongoc_query_flags_t f
 static void
 test_query_flags (void)
 {
-   int i;
-
    typedef struct {
       mongoc_query_flags_t flag;
       bson_t *opt;
@@ -86,9 +85,9 @@ test_query_flags (void)
       {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, tmp_bson ("{'tailable': true, 'awaitData': true}")}};
 
    /* test with both flag and opt */
-   for (i = 0; i < (sizeof flags_and_opts) / (sizeof (flag_and_opt_t)); i++) {
-      _test_query_flag (flags_and_opts[i].flag, NULL);
-      _test_query_flag (MONGOC_QUERY_NONE, flags_and_opts[i].opt);
+   mlib_foreach_arr (flag_and_opt_t, opts, flags_and_opts) {
+      _test_query_flag (opts->flag, NULL);
+      _test_query_flag (MONGOC_QUERY_NONE, opts->opt);
    }
 }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-async.c 2.0.2-1/src/libmongoc/tests/test-mongoc-async.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-async.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-async.c	2025-06-19 15:42:22.000000000 +0000
@@ -10,9 +10,6 @@
 #include <mongoc/mongoc-errno-private.h>
 #include "test-libmongoc.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "async-test"
-
 #define TIMEOUT 10000 /* milliseconds */
 #define NSERVERS 10
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-aws.c 2.0.2-1/src/libmongoc/tests/test-mongoc-aws.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-aws.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-aws.c	2025-06-19 15:42:22.000000000 +0000
@@ -8,17 +8,16 @@
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
  */
 
 #include "TestSuite.h"
 #include "test-libmongoc.h"
 #include <mongoc/mongoc-cluster-aws-private.h>
 
-void
+static void
 test_obtain_credentials (void *unused)
 {
    mongoc_uri_t *uri;
@@ -29,21 +28,22 @@ test_obtain_credentials (void *unused)
    BSON_UNUSED (unused);
 
    /* A username specified with a password is parsed correctly. */
-   uri = mongoc_uri_new ("mongodb://"
-                         "access_key_id:secret_access_key@localhost/?"
-                         "authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://access_key_id:secret_access_key@localhost/?authMechanism=MONGODB-AWS",
+                                    &error);
+   ASSERT_OR_PRINT (uri, error);
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
    ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR (creds.access_key_id, "access_key_id");
    ASSERT_CMPSTR (creds.secret_access_key, "secret_access_key");
-   BSON_ASSERT (creds.session_token == NULL);
+   ASSERT_CMPSTR (creds.session_token, NULL);
    _mongoc_aws_credentials_cleanup (&creds);
    mongoc_uri_destroy (uri);
 
    /* A username specified with no password is an error. */
-   uri = mongoc_uri_new ("mongodb://access_key_id:@localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://access_key_id:@localhost/?authMechanism=MONGODB-AWS", &error);
+   ASSERT_OR_PRINT (uri, error);
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
@@ -52,9 +52,11 @@ test_obtain_credentials (void *unused)
    mongoc_uri_destroy (uri);
 
    /* Password not set at all (not empty string) */
-   uri = mongoc_uri_new ("mongodb://access_key_id@localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/?authMechanism=MONGODB-AWS", &error);
+   ASSERT (mongoc_uri_set_username (uri, "access_key_id"));
+   ASSERT_OR_PRINT (uri, error);
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
@@ -64,10 +66,10 @@ test_obtain_credentials (void *unused)
 
    /* A session token may be set through the AWS_SESSION_TOKEN auth mechanism
     * property */
-   uri = mongoc_uri_new ("mongodb://"
-                         "access_key_id:secret_access_key@localhost/?"
-                         "authMechanism=MONGODB-AWS&authMechanismProperties="
-                         "AWS_SESSION_TOKEN:token");
+   uri = mongoc_uri_new_with_error ("mongodb://access_key_id:secret_access_key@localhost/"
+                                    "?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:token",
+                                    &error);
+   ASSERT_OR_PRINT (uri, error);
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
    ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR (creds.access_key_id, "access_key_id");
@@ -77,21 +79,20 @@ test_obtain_credentials (void *unused)
    mongoc_uri_destroy (uri);
 
    /* A session token in the URI with no username/password is an error. */
-   uri = mongoc_uri_new ("mongodb://localhost/"
-                         "?authMechanism=MONGODB-AWS&authMechanismProperties="
-                         "AWS_SESSION_TOKEN:token");
+   uri = mongoc_uri_new_with_error (
+      "mongodb://localhost/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:token", &error);
+   ASSERT_OR_PRINT (uri, error);
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                          "AWS_SESSION_TOKEN is set, but ACCESS_KEY_ID and "
-                          "SECRET_ACCESS_KEY are missing");
+                          "AWS_SESSION_TOKEN is set, but ACCESS_KEY_ID and SECRET_ACCESS_KEY are missing");
    _mongoc_aws_credentials_cleanup (&creds);
    mongoc_uri_destroy (uri);
 }
 
-void
+static void
 test_obtain_credentials_from_env (void *unused)
 {
    mongoc_uri_t *uri;
@@ -109,21 +110,25 @@ test_obtain_credentials_from_env (void *
    /* Environment variables are used if username/password is not set. */
    _mongoc_setenv ("AWS_ACCESS_KEY_ID", "access_key_id");
    _mongoc_setenv ("AWS_SECRET_ACCESS_KEY", "secret_access_key");
-   uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT (mongoc_uri_set_auth_mechanism (uri, "MONGODB-AWS"));
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
    ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR (creds.access_key_id, "access_key_id");
    ASSERT_CMPSTR (creds.secret_access_key, "secret_access_key");
-   BSON_ASSERT (creds.session_token == NULL);
+   ASSERT_CMPSTR (creds.session_token, NULL);
    _mongoc_aws_credentials_cleanup (&creds);
    mongoc_uri_destroy (uri);
 
    /* Omitting one of the required environment variables is an error. */
    _mongoc_setenv ("AWS_ACCESS_KEY_ID", "access_key_id");
    _mongoc_setenv ("AWS_SECRET_ACCESS_KEY", "");
-   uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT (mongoc_uri_set_auth_mechanism (uri, "MONGODB-AWS"));
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
@@ -134,9 +139,11 @@ test_obtain_credentials_from_env (void *
    /* Omitting one of the required environment variables is an error. */
    _mongoc_setenv ("AWS_ACCESS_KEY_ID", "");
    _mongoc_setenv ("AWS_SECRET_ACCESS_KEY", "secret_access_key");
-   uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT (mongoc_uri_set_auth_mechanism (uri, "MONGODB-AWS"));
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
@@ -148,14 +155,15 @@ test_obtain_credentials_from_env (void *
    _mongoc_setenv ("AWS_ACCESS_KEY_ID", "");
    _mongoc_setenv ("AWS_SECRET_ACCESS_KEY", "");
    _mongoc_setenv ("AWS_SESSION_TOKEN", "token");
-   uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT (mongoc_uri_set_auth_mechanism (uri, "MONGODB-AWS"));
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_CLIENT,
                           MONGOC_ERROR_CLIENT_AUTHENTICATE,
-                          "AWS_SESSION_TOKEN is set, but ACCESS_KEY_ID and "
-                          "SECRET_ACCESS_KEY are missing");
+                          "AWS_SESSION_TOKEN is set, but ACCESS_KEY_ID and SECRET_ACCESS_KEY are missing");
    _mongoc_aws_credentials_cleanup (&creds);
    mongoc_uri_destroy (uri);
 
@@ -163,7 +171,9 @@ test_obtain_credentials_from_env (void *
    _mongoc_setenv ("AWS_ACCESS_KEY_ID", "access_key_id");
    _mongoc_setenv ("AWS_SECRET_ACCESS_KEY", "secret_access_key");
    _mongoc_setenv ("AWS_SESSION_TOKEN", "token");
-   uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
+   uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT (mongoc_uri_set_auth_mechanism (uri, "MONGODB-AWS"));
    ret = _mongoc_aws_credentials_obtain (uri, &creds, &error);
    ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR (creds.access_key_id, "access_key_id");
@@ -191,42 +201,42 @@ test_derive_region (void *unused)
 #define WITH_LEN(s) s, strlen (s)
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("abc..def"), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part");
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("."), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part");
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("..."), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part");
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("first."), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part");
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("sts.amazonaws.com"), &region, &error);
-   BSON_ASSERT (ret);
+   ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR ("us-east-1", region);
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("first.second"), &region, &error);
-   BSON_ASSERT (ret);
+   ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR ("second", region);
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN ("first"), &region, &error);
-   BSON_ASSERT (ret);
+   ASSERT_OR_PRINT (ret, error);
    ASSERT_CMPSTR ("us-east-1", region);
    bson_free (region);
 
    ret = _mongoc_validate_and_derive_region (WITH_LEN (""), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty");
    bson_free (region);
 
@@ -234,7 +244,7 @@ test_derive_region (void *unused)
    memset (large, 'a', 256);
 
    ret = _mongoc_validate_and_derive_region (large, strlen (large), &region, &error);
-   BSON_ASSERT (!ret);
+   ASSERT (!ret);
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: too large");
    bson_free (region);
    bson_free (large);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-background-monitoring.c 2.0.2-1/src/libmongoc/tests/test-mongoc-background-monitoring.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-background-monitoring.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-background-monitoring.c	2025-06-19 15:42:22.000000000 +0000
@@ -30,8 +30,6 @@
 
 #include <inttypes.h>
 
-#define LOG_DOMAIN "test_monitoring"
-
 typedef struct {
    uint32_t n_heartbeat_started;
    uint32_t n_heartbeat_succeeded;
@@ -677,8 +675,8 @@ test_flip_flop (void)
       OBSERVE (tf, request);
       reply_to_request_with_ok_and_destroy (request);
       _signal_shutdown (tf);
-      OBSERVE_SOON (tf, tf->observations->n_heartbeat_started == i);
-      OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == i);
+      OBSERVE_SOON (tf, mlib_cmp (tf->observations->n_heartbeat_started, ==, i));
+      OBSERVE_SOON (tf, mlib_cmp (tf->observations->n_heartbeat_succeeded, ==, i));
       _add_server_monitor (tf);
    }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-bulk.c 2.0.2-1/src/libmongoc/tests/test-mongoc-bulk.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-bulk.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-bulk.c	2025-06-19 15:42:22.000000000 +0000
@@ -12,7 +12,7 @@
 #include "mock_server/mock-server.h"
 #include "test-conveniences.h"
 #include "mock_server/mock-rs.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 typedef void (*update_fn) (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, bool upsert);
@@ -128,15 +128,12 @@ oid_created_on_client (const bson_t *doc
 static void
 create_unique_index (mongoc_collection_t *collection)
 {
-   mongoc_index_opt_t opt;
    bson_error_t error;
 
-   mongoc_index_opt_init (&opt);
-   opt.unique = true;
+   mongoc_index_model_t *im = mongoc_index_model_new (tmp_bson ("{'a': 1}"), tmp_bson ("{'unique': true}"));
 
-   BEGIN_IGNORE_DEPRECATIONS
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, tmp_bson ("{'a': 1}"), &opt, &error), error);
-   END_IGNORE_DEPRECATIONS
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
+   mongoc_index_model_destroy (im);
 }
 
 
@@ -445,7 +442,7 @@ test_insert_check_keys (void)
    mongoc_bulk_operation_insert (bulk, tmp_bson ("{'': 1}"));
    r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);
    BSON_ASSERT (!r);
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key");
+   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty string");
 
    BSON_ASSERT (bson_empty (&reply));
 
@@ -460,7 +457,7 @@ test_insert_check_keys (void)
    mongoc_bulk_operation_insert (bulk, tmp_bson ("{'': 1}"));
    r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);
    BSON_ASSERT (!r);
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key");
+   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty string");
 
    BSON_ASSERT (bson_empty (&reply));
 
@@ -836,7 +833,7 @@ test_update_with_opts_validate (void)
       ASSERT_ERROR_CONTAINS (error,
                              MONGOC_ERROR_COMMAND,
                              MONGOC_ERROR_COMMAND_INVALID_ARG,
-                             "invalid argument for update: keys cannot contain \".\": \"a.a\"");
+                             "invalid argument for update: Disallowed '.' in element key: \"a.a\"");
       mongoc_bulk_operation_destroy (bulk);
 
       /* Test a valid update_one with explicit validation on the server. */
@@ -1175,7 +1172,7 @@ test_replace_one_with_opts_validate (voi
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
-                          "invalid argument for replace: keys cannot contain \".\": \"a.a\"");
+                          "invalid argument for replace: Disallowed '.' in element key: \"a.a\"");
 
    mongoc_bulk_operation_destroy (bulk);
 
@@ -1786,7 +1783,7 @@ _test_insert_invalid (bool with_opts, bo
    bson_t reply;
    bson_error_t error;
    bool r;
-   const char *err = "empty key";
+   const char *err = "empty string";
 
    client = test_framework_new_default_client ();
    collection = get_test_collection (client, "test_insert_validate");
@@ -1902,7 +1899,7 @@ test_insert_with_opts_validate (void)
    bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);
 
    BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'': 1}"), NULL, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key");
+   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty string");
 
    ASSERT_OR_PRINT (mongoc_bulk_operation_insert_with_opts (
                        bulk, tmp_bson ("{'': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_NONE), &error),
@@ -1916,7 +1913,7 @@ test_insert_with_opts_validate (void)
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
-                          "invalid document for insert: keys cannot contain \".\": \"a.a\"");
+                          "invalid document for insert: Disallowed '.' in element key: \"a.a\"");
 
    mongoc_bulk_operation_destroy (bulk);
 
@@ -1970,7 +1967,7 @@ _test_remove_validate (remove_validate_t
                              MONGOC_ERROR_COMMAND,
                              MONGOC_ERROR_COMMAND_INVALID_ARG,
                              "Bulk operation is invalid from prior error: "
-                             "invalid document for insert: empty key");
+                             "invalid document for insert: Element key cannot be an empty string");
    } else {
       test->remove (bulk, tmp_bson (NULL));
    }
@@ -1982,8 +1979,10 @@ _test_remove_validate (remove_validate_t
    r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);
    BSON_ASSERT (!r);
    BSON_ASSERT (bson_empty (&reply));
-   ASSERT_ERROR_CONTAINS (
-      error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document for insert: empty key");
+   ASSERT_ERROR_CONTAINS (error,
+                          MONGOC_ERROR_COMMAND,
+                          MONGOC_ERROR_COMMAND_INVALID_ARG,
+                          "invalid document for insert: Element key cannot be an empty string");
 
    bson_destroy (&reply);
    mongoc_bulk_operation_destroy (bulk);
@@ -3573,7 +3572,7 @@ test_bulk_max_msg_size (void)
    /* fill up to the 48 000 000 bytes message size */
    bson_init (&doc);
    bson_append_int32 (&doc, "_id", -1, 3);
-   ASSERT (mcommon_in_range_unsigned (int, filler_string));
+   ASSERT (mlib_in_range (int, filler_string));
    bson_append_utf8 (&doc, "msg", -1, msg, (int) filler_string);
    mongoc_bulk_operation_insert (bulk, &doc);
    bson_destroy (&doc);
@@ -3608,7 +3607,7 @@ test_bulk_max_msg_size (void)
    /* fill up to the 48 000 001 bytes message size */
    bson_init (&doc);
    bson_append_int32 (&doc, "_id", -1, 3);
-   ASSERT (mcommon_in_range_unsigned (int, filler_string + 1u));
+   ASSERT (mlib_in_range (int, filler_string + 1u));
    bson_append_utf8 (&doc, "msg", -1, msg, (int) (filler_string + 1u));
    mongoc_bulk_operation_insert (bulk, &doc);
    bson_destroy (&doc);
@@ -3753,7 +3752,6 @@ test_bulk_max_batch_size (void)
 static void
 test_bulk_new (void)
 {
-   mongoc_bulk_operation_t *bulk;
    mongoc_collection_t *collection;
    mongoc_client_t *client;
    bson_error_t error;
@@ -3761,43 +3759,69 @@ test_bulk_new (void)
    uint32_t r;
 
    client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
+   ASSERT (client);
 
    collection = get_test_collection (client, "bulk_new");
-   BSON_ASSERT (collection);
+   ASSERT (collection);
 
-   bulk = mongoc_bulk_operation_new (true);
-   mongoc_bulk_operation_destroy (bulk);
-
-   bulk = mongoc_bulk_operation_new (true);
-
-   r = mongoc_bulk_operation_execute (bulk, NULL, &error);
-   BSON_ASSERT (!r);
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COMMAND);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_COMMAND_INVALID_ARG);
+   // Can create and destroy:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
-   mongoc_bulk_operation_set_database (bulk, "test");
-   r = mongoc_bulk_operation_execute (bulk, NULL, &error);
-   BSON_ASSERT (!r);
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COMMAND);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_COMMAND_INVALID_ARG);
+   // Execute without a client is an error:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      r = mongoc_bulk_operation_execute (bulk, NULL, &error);
+      ASSERT (!r);
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "requires a client");
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
-   mongoc_bulk_operation_set_collection (bulk, "test");
-   r = mongoc_bulk_operation_execute (bulk, NULL, &error);
-   BSON_ASSERT (!r);
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COMMAND);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_COMMAND_INVALID_ARG);
+   // Execute with a database and no client is an error:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      mongoc_bulk_operation_set_database (bulk, "test");
+      r = mongoc_bulk_operation_execute (bulk, NULL, &error);
+      ASSERT (!r);
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "requires a client");
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
-   mongoc_bulk_operation_set_client (bulk, client);
-   r = mongoc_bulk_operation_execute (bulk, NULL, &error);
-   BSON_ASSERT (!r);
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COMMAND);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_COMMAND_INVALID_ARG);
+   // Execute with a database and collection and no client is an error:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      mongoc_bulk_operation_set_database (bulk, "test");
+      mongoc_bulk_operation_set_collection (bulk, "test");
+      r = mongoc_bulk_operation_execute (bulk, NULL, &error);
+      ASSERT (!r);
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "requires a client");
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
-   mongoc_bulk_operation_insert (bulk, &empty);
-   ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error);
+   // Execute with no operations is an error:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      mongoc_bulk_operation_set_database (bulk, "test");
+      mongoc_bulk_operation_set_collection (bulk, "test");
+      mongoc_bulk_operation_set_client (bulk, client);
+      r = mongoc_bulk_operation_execute (bulk, NULL, &error);
+      ASSERT (!r);
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty bulk write");
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
-   mongoc_bulk_operation_destroy (bulk);
+   // Execute with operations is OK:
+   {
+      mongoc_bulk_operation_t *bulk = mongoc_bulk_operation_new (true);
+      mongoc_bulk_operation_set_database (bulk, "test");
+      mongoc_bulk_operation_set_collection (bulk, "test");
+      mongoc_bulk_operation_set_client (bulk, client);
+      mongoc_bulk_operation_insert (bulk, &empty);
+      ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error);
+      mongoc_bulk_operation_destroy (bulk);
+   }
 
    mongoc_collection_drop (collection, NULL);
 
@@ -4664,12 +4688,12 @@ test_bulk_write_multiple_errors (void *u
 
    mongoc_bulk_operation_insert (bulk,
                                  tmp_bson ("{'_id': 1}")); // fail via failPoint
-   mongoc_bulk_operation_delete (bulk,
+   mongoc_bulk_operation_remove (bulk,
                                  tmp_bson ("{'_id': 1}")); // fail via failPoint
 
    mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 4}")); // succeed
 
-   mongoc_bulk_operation_delete (bulk, tmp_bson ("{'_id': 4}")); // suceed
+   mongoc_bulk_operation_remove (bulk, tmp_bson ("{'_id': 4}")); // suceed
 
    mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 5}")); // suceed
    mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 5}")); // duplicate key error
@@ -4766,6 +4790,23 @@ test_bulk_write_set_client_updates_opera
    mock_server_destroy (mock_server);
 }
 
+static void
+test_multiple_execution (void)
+{
+   mongoc_client_t *client = test_framework_new_default_client ();
+   mongoc_collection_t *coll = get_test_collection (client, "test_multiple_execution");
+   bson_error_t error;
+   mongoc_bulk_operation_t *bulk = mongoc_collection_create_bulk_operation_with_opts (coll, NULL);
+   mongoc_bulk_operation_insert (bulk, tmp_bson ("{}"));
+   ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error);
+   ASSERT (!mongoc_bulk_operation_execute (bulk, NULL, &error));
+   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "bulk write already executed");
+   mongoc_bulk_operation_destroy (bulk);
+   mongoc_collection_destroy (coll);
+   mongoc_client_destroy (client);
+}
+
+
 void
 test_bulk_install (TestSuite *suite)
 {
@@ -4944,4 +4985,5 @@ test_bulk_install (TestSuite *suite)
    TestSuite_AddMockServerTest (suite,
                                 "/BulkOperation/set_client_updates_operation_id_when_client_changes",
                                 test_bulk_write_set_client_updates_operation_id_when_client_changes);
+   TestSuite_AddLive (suite, "/BulkOperation/multiple_execution", test_multiple_execution);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-bulkwrite.c 2.0.2-1/src/libmongoc/tests/test-mongoc-bulkwrite.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-bulkwrite.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-bulkwrite.c	2025-06-19 15:42:22.000000000 +0000
@@ -659,7 +659,7 @@ test_bulkwrite_two_large_inserts (void *
    char *large_string = bson_malloc (large_len + 1);
    memset (large_string, 'a', large_len);
    large_string[large_len] = '\0';
-   ASSERT (mcommon_in_range_unsigned (int, large_len));
+   ASSERT (mlib_in_range (int, large_len));
 
    // Create two large documents:
    bson_t *docs[2];
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-change-stream.c 2.0.2-1/src/libmongoc/tests/test-mongoc-change-stream.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-change-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-change-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -996,7 +996,7 @@ test_change_stream_live_read_prefs (void
    ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &next_doc), err);
 
    raw_cursor = stream->cursor;
-   ASSERT (first_cursor_id != mongoc_cursor_get_id (raw_cursor));
+   ASSERT (mlib_cmp (first_cursor_id, !=, mongoc_cursor_get_id (raw_cursor)));
    ASSERT (test_framework_server_is_secondary (client, raw_cursor->server_id));
 
    mongoc_read_prefs_destroy (prefs);
@@ -2120,6 +2120,132 @@ prose_test_18 (void)
    mock_server_destroy (server);
 }
 
+typedef struct {
+   bson_t *commands[6];
+   size_t commands_len;
+   bson_t *replies[6];
+   size_t replies_len;
+} test_events_t;
+
+static void
+test_events_started_cb (const mongoc_apm_command_started_t *e)
+{
+   test_events_t *te = mongoc_apm_command_started_get_context (e);
+   ASSERT_CMPSIZE_T (te->commands_len, <, sizeof (te->commands) / sizeof (te->commands[0]));
+   te->commands[te->commands_len++] = bson_copy (mongoc_apm_command_started_get_command (e));
+}
+
+static void
+test_events_succeeded_cb (const mongoc_apm_command_succeeded_t *e)
+{
+   test_events_t *te = mongoc_apm_command_succeeded_get_context (e);
+   ASSERT_CMPSIZE_T (te->replies_len, <, sizeof (te->replies) / sizeof (te->replies[0]));
+   te->replies[te->replies_len++] = bson_copy (mongoc_apm_command_succeeded_get_reply (e));
+}
+
+// Test that batchSize:0 is applied to the `aggregate` command.
+static void
+test_change_stream_batchSize0 (void *test_ctx)
+{
+   BSON_UNUSED (test_ctx);
+
+   bson_error_t error;
+
+   // Create a change stream. Capture a resume token. Insert documents to create future events.
+   bson_t *resumeToken;
+   {
+      mongoc_client_t *client = test_framework_new_default_client ();
+      mongoc_collection_t *coll = drop_and_get_coll (client, "db", "coll");
+      // Insert with majority write concern to ensure documents are visible to change stream.
+      {
+         mongoc_write_concern_t *wc = mongoc_write_concern_new ();
+         mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY);
+         mongoc_collection_set_write_concern (coll, wc);
+         mongoc_write_concern_destroy (wc);
+      }
+      mongoc_change_stream_t *cs = mongoc_collection_watch (coll, tmp_bson ("{}"), NULL);
+      resumeToken = bson_copy (mongoc_change_stream_get_resume_token (cs));
+      // Insert documents to create future events.
+      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), NULL, NULL, &error), error);
+      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2}"), NULL, NULL, &error), error);
+      mongoc_change_stream_destroy (cs);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+
+   // Create another change stream with the resumeToken and batchSize:0.
+   test_events_t te = {.commands_len = 0, .replies_len = 0};
+   {
+      mongoc_client_t *client = test_framework_new_default_client ();
+      // Capture events.
+      {
+         mongoc_apm_callbacks_t *cbs = mongoc_apm_callbacks_new ();
+         mongoc_apm_set_command_started_cb (cbs, test_events_started_cb);
+         mongoc_apm_set_command_succeeded_cb (cbs, test_events_succeeded_cb);
+         ASSERT (mongoc_client_set_apm_callbacks (client, cbs, &te));
+         mongoc_apm_callbacks_destroy (cbs);
+      }
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "coll");
+      // Iterate change stream.
+      {
+         bson_t *opts = BCON_NEW ("resumeAfter", BCON_DOCUMENT (resumeToken), "batchSize", BCON_INT32 (0));
+         mongoc_change_stream_t *cs = mongoc_collection_watch (coll, tmp_bson ("{}"), opts);
+         const bson_t *ignored;
+         while (mongoc_change_stream_next (cs, &ignored))
+            ;
+         ASSERT_OR_PRINT (!mongoc_change_stream_error_document (cs, &error, NULL), error);
+         bson_destroy (opts);
+         mongoc_change_stream_destroy (cs);
+      }
+      mongoc_collection_destroy (coll);
+
+      // Check captured events.
+      {
+         // Expect aggregate is sent with `batchSize:0`
+         ASSERT (te.commands[0]);
+         ASSERT_MATCH (te.commands[0], BSON_STR ({"aggregate" : "coll", "cursor" : {"batchSize" : 0}}));
+         // Expect reply has no documents.
+         ASSERT (te.replies[0]);
+         ASSERT_MATCH (te.replies[0], BSON_STR ({"cursor" : {"firstBatch" : []}}));
+
+         // Expect getMore is sent without `batchSize`
+         ASSERT (te.commands[1]);
+         ASSERT_MATCH (te.commands[1], BSON_STR ({"getMore" : {"$$type" : "long"}, "batchSize" : {"$exists" : false}}));
+         // Expect reply has both documents.
+         ASSERT (te.replies[1]);
+         ASSERT_MATCH (
+            te.replies[1],
+            BSON_STR ({"cursor" : {"nextBatch" : [ {"operationType" : "insert"}, {"operationType" : "insert"} ]}}));
+
+         // Expect another getMore is sent without `batchSize`
+         ASSERT (te.commands[2]);
+         ASSERT_MATCH (te.commands[2], BSON_STR ({"getMore" : {"$$type" : "long"}, "batchSize" : {"$exists" : false}}));
+         // Expect reply has no more documents
+         ASSERT (te.replies[2]);
+         ASSERT_MATCH (te.replies[2], BSON_STR ({"cursor" : {"nextBatch" : []}}));
+
+         // Expect killCursors is sent to kill server-side cursor.
+         ASSERT (te.commands[3]);
+         ASSERT_MATCH (te.commands[3], BSON_STR ({"killCursors" : "coll"}));
+         ASSERT (te.replies[3]);
+         ASSERT_MATCH (te.replies[3], BSON_STR ({"ok" : 1}));
+
+         ASSERT (!te.commands[4]);
+         ASSERT (!te.replies[4]);
+      }
+      mongoc_client_destroy (client);
+   }
+
+   bson_destroy (resumeToken);
+   for (size_t i = 0; i < te.commands_len; i++) {
+      bson_destroy (te.commands[i]);
+   }
+   for (size_t i = 0; i < te.replies_len; i++) {
+      bson_destroy (te.replies[i]);
+   }
+}
+
 
 void
 test_change_stream_install (TestSuite *suite)
@@ -2263,4 +2389,10 @@ test_change_stream_install (TestSuite *s
                       test_framework_skip_if_not_rs_version_7);
    TestSuite_AddMockServerTest (suite, "/change_streams/prose_test_17", prose_test_17);
    TestSuite_AddMockServerTest (suite, "/change_streams/prose_test_18", prose_test_18);
+   TestSuite_AddFull (suite,
+                      "/change_stream/batchSize0",
+                      test_change_stream_batchSize0,
+                      NULL,
+                      NULL,
+                      test_framework_skip_if_not_replset);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-client-pool.c 2.0.2-1/src/libmongoc/tests/test-mongoc-client-pool.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-client-pool.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-client-pool.c	2025-06-19 15:42:22.000000000 +0000
@@ -101,68 +101,6 @@ test_mongoc_client_pool_min_size_zero (v
 }
 
 static void
-test_mongoc_client_pool_min_size_dispose (void)
-{
-   mongoc_client_pool_t *pool;
-   mongoc_client_t *client;
-   mongoc_uri_t *uri;
-   mongoc_client_t *c0, *c1, *c2, *c3;
-
-   capture_logs (true);
-   uri = mongoc_uri_new ("mongodb://127.0.0.1/?minpoolsize=2");
-   pool = test_framework_client_pool_new_from_uri (uri, NULL);
-
-   c0 = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (c0);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 1);
-
-   c1 = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (c1);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 2);
-
-   c2 = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (c2);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 3);
-
-   c3 = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (c3);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 4);
-
-   mongoc_client_pool_push (pool, c0); /* queue is [c0] */
-   ASSERT_CMPSIZE_T (mongoc_client_pool_num_pushed (pool), ==, (size_t) 1);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 4);
-
-   mongoc_client_pool_push (pool, c1); /* queue is [c1, c0] */
-   ASSERT_CMPSIZE_T (mongoc_client_pool_num_pushed (pool), ==, (size_t) 2);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 4);
-
-   mongoc_client_pool_push (pool, c2); /* queue is [c2, c1] */
-   ASSERT_CMPSIZE_T (mongoc_client_pool_num_pushed (pool), ==, (size_t) 2);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 3);
-
-   mongoc_client_pool_push (pool, c3); /* queue is [c3, c2] */
-   ASSERT_CMPSIZE_T (mongoc_client_pool_num_pushed (pool), ==, (size_t) 2);
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 2);
-
-   /* BSON_ASSERT oldest client was destroyed, newest were stored */
-   client = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (client);
-   BSON_ASSERT (client == c3);
-
-   client = mongoc_client_pool_pop (pool);
-   BSON_ASSERT (client);
-   BSON_ASSERT (client == c2);
-
-   ASSERT_CMPSIZE_T (mongoc_client_pool_get_size (pool), ==, (size_t) 2);
-
-   /* clean up */
-   mongoc_client_pool_push (pool, c2);
-   mongoc_client_pool_push (pool, c3);
-   mongoc_client_pool_destroy (pool);
-   mongoc_uri_destroy (uri);
-}
-
-static void
 test_mongoc_client_pool_set_max_size (void)
 {
    mongoc_client_pool_t *pool;
@@ -180,7 +118,7 @@ test_mongoc_client_pool_set_max_size (vo
       client = mongoc_client_pool_pop (pool);
       BSON_ASSERT (client);
       _mongoc_array_append_val (&conns, client);
-      BSON_ASSERT (mongoc_client_pool_get_size (pool) == i + 1);
+      BSON_ASSERT (mlib_cmp (mongoc_client_pool_get_size (pool), ==, i + 1));
    }
 
    mongoc_client_pool_max_size (pool, 3);
@@ -199,50 +137,6 @@ test_mongoc_client_pool_set_max_size (vo
    mongoc_client_pool_destroy (pool);
 }
 
-static void
-test_mongoc_client_pool_set_min_size (void)
-{
-   mongoc_client_pool_t *pool;
-   mongoc_client_t *client;
-   mongoc_uri_t *uri;
-   mongoc_array_t conns;
-   int i;
-
-   _mongoc_array_init (&conns, sizeof client);
-
-   uri = mongoc_uri_new ("mongodb://127.0.0.1/?maxpoolsize=10&minpoolsize=3");
-   capture_logs (true);
-   pool = test_framework_client_pool_new_from_uri (uri, NULL);
-   ASSERT_CAPTURED_LOG ("minpoolsize URI option", MONGOC_LOG_LEVEL_WARNING, "is deprecated");
-
-   for (i = 0; i < 10; i++) {
-      client = mongoc_client_pool_pop (pool);
-      BSON_ASSERT (client);
-      _mongoc_array_append_val (&conns, client);
-      BSON_ASSERT (mongoc_client_pool_get_size (pool) == i + 1);
-   }
-
-   capture_logs (true);
-   BEGIN_IGNORE_DEPRECATIONS
-   mongoc_client_pool_min_size (pool, 7);
-   END_IGNORE_DEPRECATIONS
-   ASSERT_CAPTURED_LOG (
-      "mongoc_client_pool_min_size", MONGOC_LOG_LEVEL_WARNING, "mongoc_client_pool_min_size is deprecated");
-
-   for (i = 0; i < 10; i++) {
-      client = _mongoc_array_index (&conns, mongoc_client_t *, i);
-      BSON_ASSERT (client);
-      mongoc_client_pool_push (pool, client);
-   }
-
-   BSON_ASSERT (mongoc_client_pool_get_size (pool) == 7);
-
-   _mongoc_array_clear (&conns);
-   _mongoc_array_destroy (&conns);
-   mongoc_uri_destroy (uri);
-   mongoc_client_pool_destroy (pool);
-}
-
 #ifndef MONGOC_ENABLE_SSL
 static void
 test_mongoc_client_pool_ssl_disabled (void)
@@ -652,7 +546,38 @@ test_mongoc_client_pool_change_openssl_c
 
    mongoc_client_pool_destroy (pool);
 }
-#endif
+#endif // MONGOC_ENABLE_SSL_OPENSSL
+
+#if defined(MONGOC_ENABLE_SSL)
+static void
+test_mongoc_client_set_ssl_opts_on_pool (void)
+{
+   // Test calling `mongoc_client_set_ssl_opts` on a pooled client logs an error.
+   mongoc_client_pool_t *pool = test_framework_new_default_client_pool ();
+   mongoc_client_t *client_from_pool = mongoc_client_pool_pop (pool);
+   capture_logs (true);
+   mongoc_client_set_ssl_opts (client_from_pool, mongoc_ssl_opt_get_default ());
+   ASSERT_CAPTURED_LOG ("mongoc_client_set_ssl_opts", MONGOC_LOG_LEVEL_ERROR, "cannot be called on a pooled client");
+   capture_logs (false);
+   mongoc_client_pool_push (pool, client_from_pool);
+   mongoc_client_pool_destroy (pool);
+}
+#endif // MONGOC_ENABLE_SSL
+
+static void
+test_mongoc_client_set_stream_initiator (void)
+{
+   // Test calling `mongoc_client_set_initiator` on a pooled client logs an error.
+   mongoc_client_pool_t *pool = test_framework_new_default_client_pool ();
+   mongoc_client_t *client_from_pool = mongoc_client_pool_pop (pool);
+   capture_logs (true);
+   mongoc_client_set_stream_initiator (client_from_pool, mongoc_client_default_stream_initiator, NULL);
+   ASSERT_CAPTURED_LOG (
+      "mongoc_client_set_stream_initiator", MONGOC_LOG_LEVEL_ERROR, "cannot be called on a pooled client");
+   capture_logs (false);
+   mongoc_client_pool_push (pool, client_from_pool);
+   mongoc_client_pool_destroy (pool);
+}
 
 void
 test_client_pool_install (TestSuite *suite)
@@ -661,9 +586,7 @@ test_client_pool_install (TestSuite *sui
    TestSuite_Add (suite, "/ClientPool/try_pop", test_mongoc_client_pool_try_pop);
    TestSuite_Add (suite, "/ClientPool/pop_timeout", test_mongoc_client_pool_pop_timeout);
    TestSuite_Add (suite, "/ClientPool/min_size_zero", test_mongoc_client_pool_min_size_zero);
-   TestSuite_Add (suite, "/ClientPool/min_size_dispose", test_mongoc_client_pool_min_size_dispose);
    TestSuite_Add (suite, "/ClientPool/set_max_size", test_mongoc_client_pool_set_max_size);
-   TestSuite_Add (suite, "/ClientPool/set_min_size", test_mongoc_client_pool_set_min_size);
 
    TestSuite_Add (suite, "/ClientPool/handshake", test_mongoc_client_pool_handshake);
 
@@ -701,4 +624,9 @@ test_client_pool_install (TestSuite *sui
 #if defined(MONGOC_ENABLE_SSL_OPENSSL)
    TestSuite_Add (suite, "/ClientPool/openssl/change_ssl_opts", test_mongoc_client_pool_change_openssl_ctx);
 #endif
+
+#if defined(MONGOC_ENABLE_SSL)
+   TestSuite_AddLive (suite, "/ClientPool/mongoc_client_set_ssl_opts", test_mongoc_client_set_ssl_opts_on_pool);
+#endif // MONGOC_ENABLE_SSL
+   TestSuite_AddLive (suite, "/ClientPool/mongoc_client_set_stream_initiator", test_mongoc_client_set_stream_initiator);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-client-session.c 2.0.2-1/src/libmongoc/tests/test-mongoc-client-session.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-client-session.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-client-session.c	2025-06-19 15:42:22.000000000 +0000
@@ -4,6 +4,7 @@
 #include <mongoc/mongoc-change-stream-private.h>
 #include <mongoc/mongoc-collection-private.h>
 #include <mongoc/utlist.h>
+#include <mlib/loop.h>
 #include "TestSuite.h"
 #include "test-conveniences.h"
 #include "test-libmongoc.h"
@@ -14,9 +15,6 @@
 
 #include <inttypes.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "session-test"
-
 static void
 test_session_opts_clone (void)
 {
@@ -787,7 +785,6 @@ _test_end_sessions_many (bool pooled)
 {
    endsessions_test_t test;
    mongoc_client_t *client;
-   int i;
    mongoc_client_session_t *sessions[10001];
    bson_error_t error;
    bson_t ended_lsids;
@@ -801,14 +798,13 @@ _test_end_sessions_many (bool pooled)
    /*
     * create and destroy 10,001 sessions
     */
-   for (i = 0; i < sizeof sessions / sizeof (mongoc_client_session_t *); i++) {
-      sessions[i] = mongoc_client_start_session (client, NULL, &error);
-      ASSERT_OR_PRINT (sessions[i], error);
-      send_ping (client, sessions[i]);
+   mlib_foreach_arr (mongoc_client_session_t *, session, sessions) {
+      *session = mongoc_client_start_session (client, NULL, &error);
+      ASSERT_OR_PRINT (*session, error);
+      send_ping (client, *session);
    }
-
-   for (i = 0; i < sizeof sessions / sizeof (mongoc_client_session_t *); i++) {
-      mongoc_client_session_destroy (sessions[i]);
+   mlib_foreach_arr (mongoc_client_session_t *, session, sessions) {
+      mongoc_client_session_destroy (*session);
    }
 
    endsessions_test_destroy_client (&test);
@@ -1605,15 +1601,6 @@ run_session_test_bulk_operation (void *c
 
 
 static void
-run_count_test (void *ctx)
-{
-   /* CDRIVER-3612: mongoc_collection_estimated_document_count does not support
-    * explicit sessions */
-   _test_implicit_session_lsid (((session_test_helper_t *) ctx)->test_fn);
-}
-
-
-static void
 insert_10_docs (session_test_t *test)
 {
    mongoc_bulk_operation_t *bulk;
@@ -1686,14 +1673,6 @@ test_db_cmd (session_test_t *test)
 
 
 static void
-test_count (session_test_t *test)
-{
-   test->succeeded = (-1 != mongoc_collection_count_with_opts (
-                               test->collection, MONGOC_QUERY_NONE, NULL, 0, 0, &test->opts, NULL, &test->error));
-}
-
-
-static void
 test_cursor (session_test_t *test)
 {
    mongoc_cursor_t *cursor;
@@ -1742,10 +1721,10 @@ test_drop_index (session_test_t *test)
 static void
 test_create_index (session_test_t *test)
 {
-   BEGIN_IGNORE_DEPRECATIONS
-   test->succeeded = mongoc_collection_create_index_with_opts (
-      test->collection, tmp_bson ("{'a': 1}"), NULL, &test->opts, NULL, &test->error);
-   END_IGNORE_DEPRECATIONS
+   mongoc_index_model_t *im = mongoc_index_model_new (tmp_bson ("{'a': 1}"), NULL);
+   test->succeeded =
+      mongoc_collection_create_indexes_with_opts (test->collection, &im, 1, &test->opts, NULL, &test->error);
+   mongoc_index_model_destroy (im);
 }
 
 static void
@@ -2751,17 +2730,6 @@ test_session_install (TestSuite *suite)
    add_session_test (suite, "/Session/write_cmd", test_write_cmd, false);
    add_session_test (suite, "/Session/read_write_cmd", test_read_write_cmd, true);
    add_session_test (suite, "/Session/db_cmd", test_db_cmd, false);
-   {
-      session_test_helper_t *const helper = bson_malloc (sizeof (*helper));
-      *helper = (session_test_helper_t){.test_fn = test_count};
-      TestSuite_AddFull (suite,
-                         "/Session/count",
-                         run_count_test,
-                         bson_free,
-                         helper,
-                         test_framework_skip_if_no_cluster_time,
-                         test_framework_skip_if_no_crypto);
-   }
    add_session_test (suite, "/Session/cursor", test_cursor, true);
    add_session_test (suite, "/Session/drop", test_drop, false);
    add_session_test (suite, "/Session/drop_index", test_drop_index, false);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-client-side-encryption.c 2.0.2-1/src/libmongoc/tests/test-mongoc-client-side-encryption.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-client-side-encryption.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-client-side-encryption.c	2025-06-19 15:42:22.000000000 +0000
@@ -32,7 +32,7 @@
 
 #include <mongoc/mongoc-uri.h>
 #include <mongoc/mongoc-http-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 static void
 _before_test (json_test_ctx_t *ctx, const bson_t *test)
@@ -602,7 +602,7 @@ test_datakey_and_double_encryption_creat
       to_encrypt.value.v_utf8.str = bson_strdup (hello);
 
       const size_t len = strlen (to_encrypt.value.v_utf8.str);
-      ASSERT (mcommon_in_range_unsigned (uint32_t, len));
+      ASSERT (mlib_in_range (uint32_t, len));
       to_encrypt.value.v_utf8.len = (uint32_t) len;
    }
 
@@ -2545,8 +2545,6 @@ test_kms_tls_cert_expired (void *unused)
    ASSERT_CONTAINS (error.message, "CSSMERR_TP_CERT_EXPIRED");
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
    ASSERT_CONTAINS (error.message, "certificate has expired");
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-   ASSERT_CONTAINS (error.message, "certificate has expired");
 #endif
 
    mongoc_client_encryption_datakey_opts_destroy (opts);
@@ -2589,8 +2587,6 @@ test_kms_tls_cert_wrong_host (void *unus
    ASSERT_CONTAINS (error.message, "Host name mismatch");
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
    ASSERT_CONTAINS (error.message, "hostname doesn't match certificate");
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-   ASSERT_CONTAINS (error.message, "not present in server certificate");
 #endif
 
    mongoc_client_encryption_datakey_opts_destroy (opts);
@@ -2822,8 +2818,6 @@ _tls_test_make_client_encryption (mongoc
 #define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "CSSMERR_TP_CERT_EXPIRED")
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
 #define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "certificate has expired")
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-#define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "certificate has expired")
 #else
 #define ASSERT_EXPIRED(error)
 #endif
@@ -2834,8 +2828,6 @@ _tls_test_make_client_encryption (mongoc
 #define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "Host name mismatch")
 #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
 #define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "hostname doesn't match certificate")
-#elif defined(MONGOC_ENABLE_SSL_LIBRESSL)
-#define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "not present in server certificate")
 #else
 #define ASSERT_INVALID_HOSTNAME(error)
 #endif
@@ -4737,7 +4729,7 @@ decryption_events_setup (void)
       plaintext.value.v_utf8.str = "hello";
 
       const size_t len = strlen (plaintext.value.v_utf8.str);
-      ASSERT (mcommon_in_range_unsigned (uint32_t, len));
+      ASSERT (mlib_in_range (uint32_t, len));
 
       plaintext.value.v_utf8.len = (uint32_t) len;
 
@@ -6364,6 +6356,8 @@ _test_retry_with_masterkey (const char *
 static void
 test_kms_retry (void *unused)
 {
+   BSON_UNUSED (unused);
+
    bson_t *aws_masterkey = tmp_bson (BSON_STR ({"region" : "r", "key" : "k", "endpoint" : "127.0.0.1:9003"}));
    bson_t *azure_masterkey = tmp_bson (BSON_STR ({"keyVaultEndpoint" : "127.0.0.1:9003", "keyName" : "foo"}));
    bson_t *gcp_masterkey = tmp_bson (BSON_STR (
@@ -6374,6 +6368,510 @@ test_kms_retry (void *unused)
    _test_retry_with_masterkey ("gcp", gcp_masterkey);
 }
 
+static mongoc_client_t *
+create_encrypted_client (void)
+{
+   mongoc_client_t *client = test_framework_new_default_client ();
+   bson_error_t error;
+   mongoc_auto_encryption_opts_t *ao = mongoc_auto_encryption_opts_new ();
+   {
+      bson_t extra = BSON_INITIALIZER;
+      _set_extra_bypass (&extra);
+      _set_extra_crypt_shared (&extra);
+      mongoc_auto_encryption_opts_set_extra (ao, &extra);
+      bson_destroy (&extra);
+   }
+   bson_t *kms_providers =
+      BCON_NEW ("local", "{", "key", BCON_BIN (BSON_SUBTYPE_UUID, (uint8_t *) LOCAL_MASTERKEY, 96), "}");
+   mongoc_auto_encryption_opts_set_keyvault_namespace (ao, "db", "keyvault");
+   mongoc_auto_encryption_opts_set_kms_providers (ao, kms_providers);
+   ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client, ao, &error), error);
+   bson_destroy (kms_providers);
+   mongoc_auto_encryption_opts_destroy (ao);
+   return client;
+}
+
+#define ASSERT_COLL_MATCHES_ONE(coll, expect)                                                           \
+   if (1) {                                                                                             \
+      mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ((coll), tmp_bson ("{}"), NULL, NULL); \
+      const bson_t *got;                                                                                \
+      bool found = mongoc_cursor_next (cursor, &got);                                                   \
+      if (!found) {                                                                                     \
+         ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);                                \
+         test_error ("expected 1 document, but got 0");                                                 \
+      }                                                                                                 \
+      assert_match_bson (got, expect, false);                                                           \
+      ASSERT (!mongoc_cursor_next (cursor, &got)); /* expect exactly one document */                    \
+      mongoc_cursor_destroy (cursor);                                                                   \
+   } else                                                                                               \
+      (void) 0
+
+#define ASSERT_AGG_RETURNS_ONE(coll, pipeline, expect)                                           \
+   if (1) {                                                                                      \
+      mongoc_cursor_t *cursor = mongoc_collection_aggregate ((coll), 0, (pipeline), NULL, NULL); \
+      const bson_t *got;                                                                         \
+      bool found = mongoc_cursor_next (cursor, &got);                                            \
+      if (!found) {                                                                              \
+         ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);                         \
+         test_error ("expected 1 document, but got 0");                                          \
+      }                                                                                          \
+      ASSERT_EQUAL_BSON (expect, got);                                                           \
+      ASSERT (!mongoc_cursor_next (cursor, &got)); /* expect exactly one document */             \
+      mongoc_cursor_destroy (cursor);                                                            \
+   } else                                                                                        \
+      (void) 0
+
+#define ASSERT_AGG_ERROR(coll, pipeline, msg)                                                    \
+   if (1) {                                                                                      \
+      mongoc_cursor_t *cursor = mongoc_collection_aggregate ((coll), 0, (pipeline), NULL, NULL); \
+      const bson_t *got;                                                                         \
+      bool found = mongoc_cursor_next (cursor, &got);                                            \
+      ASSERT (!found);                                                                           \
+      ASSERT (mongoc_cursor_error (cursor, &error));                                             \
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, msg);                \
+      mongoc_cursor_destroy (cursor);                                                            \
+   } else                                                                                        \
+      (void) 0
+
+#define MAKE_BSON(...) tmp_bson (BSON_STR (__VA_ARGS__))
+
+static void
+drop_coll (mongoc_database_t *db, const char *collname)
+{
+   bson_error_t error;
+   mongoc_collection_t *coll = mongoc_database_get_collection (db, collname);
+   bool ok = mongoc_collection_drop (coll, &error);
+   if (!ok && error.code != MONGOC_SERVER_ERR_NS_NOT_FOUND) {
+      test_error ("unexpected error dropping %s: %s", collname, error.message);
+   }
+   mongoc_collection_destroy (coll);
+}
+
+static void
+test_lookup_setup (void)
+{
+   bool ok;
+   bson_error_t error;
+
+   mongoc_client_t *encrypted_client = create_encrypted_client ();
+   mongoc_client_t *setup_client = test_framework_new_default_client ();
+
+
+#define TESTDIR "./src/libmongoc/tests/client_side_encryption_prose/lookup/"
+   // Insert key into key vault:
+   {
+      mongoc_collection_t *keyvault = mongoc_client_get_collection (encrypted_client, "db", "keyvault");
+      mongoc_collection_drop (keyvault, NULL);
+      bson_t *keydoc = get_bson_from_json_file (TESTDIR "key-doc.json");
+      bson_t opts = BSON_INITIALIZER;
+      // Apply majority write concern.
+      {
+         mongoc_write_concern_t *wc = mongoc_write_concern_new ();
+         mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY);
+         mongoc_write_concern_append (wc, &opts);
+         mongoc_write_concern_destroy (wc);
+      }
+      ASSERT_OR_PRINT (mongoc_collection_insert_one (keyvault, keydoc, NULL, &opts, &error), error);
+      bson_destroy (&opts);
+      bson_destroy (keydoc);
+      mongoc_collection_destroy (keyvault);
+   }
+
+   // Create collections:
+   {
+      mongoc_database_t *db = mongoc_client_get_database (encrypted_client, "db");
+      // Create db.csfle:
+      {
+         drop_coll (db, "csfle");
+         bson_t *schema = get_bson_from_json_file (TESTDIR "schema-csfle.json");
+         bson_t *create_opts = BCON_NEW ("validator", "{", "$jsonSchema", BCON_DOCUMENT (schema), "}");
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "csfle", create_opts, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+         bson_destroy (create_opts);
+         bson_destroy (schema);
+      }
+
+      // Create db.csfle2:
+      {
+         drop_coll (db, "csfle2");
+         bson_t *schema = get_bson_from_json_file (TESTDIR "schema-csfle2.json");
+         bson_t *create_opts = BCON_NEW ("validator", "{", "$jsonSchema", BCON_DOCUMENT (schema), "}");
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "csfle2", create_opts, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+         bson_destroy (create_opts);
+         bson_destroy (schema);
+      }
+
+      // Create db.qe:
+      {
+         drop_coll (db, "qe");
+         bson_t *schema = get_bson_from_json_file (TESTDIR "schema-qe.json");
+         bson_t *create_opts = BCON_NEW ("encryptedFields", BCON_DOCUMENT (schema));
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "qe", create_opts, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+         bson_destroy (create_opts);
+         bson_destroy (schema);
+      }
+
+      // Create db.qe2:
+      {
+         drop_coll (db, "qe2");
+         bson_t *schema = get_bson_from_json_file (TESTDIR "schema-qe2.json");
+         bson_t *create_opts = BCON_NEW ("encryptedFields", BCON_DOCUMENT (schema));
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "qe2", create_opts, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+         bson_destroy (create_opts);
+         bson_destroy (schema);
+      }
+
+      // Create db.no_schema:
+      {
+         drop_coll (db, "no_schema");
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "noschema", NULL, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+      }
+
+      // Create db.no_schema2:
+      {
+         drop_coll (db, "no_schema2");
+         mongoc_collection_t *coll = mongoc_database_create_collection (db, "noschema2", NULL, &error);
+         ASSERT_OR_PRINT (coll, error);
+         mongoc_collection_destroy (coll);
+      }
+
+      mongoc_database_destroy (db);
+   }
+#undef TESTDIR
+
+   // Insert initial documents:
+   {
+      mongoc_client_t *client = create_encrypted_client ();
+
+      // Insert to db.csfle:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"csfle" : "csfle"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "csfle");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"csfle" : {"$$type" : "binData"}}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      // Insert to db.csfle2:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle2");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"csfle2" : "csfle2"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "csfle2");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"csfle2" : {"$$type" : "binData"}}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      // Insert to db.qe:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "qe");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"qe" : "qe"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "qe");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"qe" : {"$$type" : "binData"}}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      // Insert to db.qe2:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "qe2");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"qe2" : "qe2"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "qe2");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"qe2" : {"$$type" : "binData"}}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      // Insert to db.no_schema:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "no_schema");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"no_schema" : "no_schema"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is not encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "no_schema");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"no_schema" : "no_schema"}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      // Insert to db.no_schema2:
+      {
+         mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "no_schema2");
+         ok = mongoc_collection_insert_one (coll, MAKE_BSON ({"no_schema2" : "no_schema2"}), NULL, NULL, &error);
+         ASSERT_OR_PRINT (ok, error);
+         mongoc_collection_destroy (coll);
+         // Find document with unencrypted client to check it is not encrypted.
+         mongoc_collection_t *coll_unencrypted = mongoc_client_get_collection (setup_client, "db", "no_schema2");
+         ASSERT_COLL_MATCHES_ONE (coll_unencrypted, MAKE_BSON ({"no_schema2" : "no_schema2"}));
+         mongoc_collection_destroy (coll_unencrypted);
+      }
+
+      mongoc_client_destroy (client);
+   }
+
+   mongoc_client_destroy (setup_client);
+   mongoc_client_destroy (encrypted_client);
+}
+
+static void
+test_lookup (void *unused)
+{
+   BSON_UNUSED (unused);
+
+   test_lookup_setup ();
+   bson_error_t error;
+
+   // Case 1: db.csfle joins db.no_schema:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"csfle" : "csfle"}},
+            {
+               "$lookup" : {
+                  "from" : "no_schema",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"no_schema" : "no_schema"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"csfle" : "csfle", "matched" : [ {"no_schema" : "no_schema"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 2: db.qe joins db.no_schema.
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "qe");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"qe" : "qe"}},
+            {
+               "$lookup" : {
+                  "from" : "no_schema",
+                  "as" : "matched",
+                  "pipeline" :
+                     [ {"$match" : {"no_schema" : "no_schema"}}, {"$project" : {"_id" : 0, "__safeContent__" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0, "__safeContent__" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"qe" : "qe", "matched" : [ {"no_schema" : "no_schema"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 3: db.no_schema joins db.csfle:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "no_schema");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"no_schema" : "no_schema"}},
+            {
+               "$lookup" : {
+                  "from" : "csfle",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"csfle" : "csfle"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"no_schema" : "no_schema", "matched" : [ {"csfle" : "csfle"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 4: db.no_schema joins db.qe:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "no_schema");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"no_schema" : "no_schema"}},
+            {
+               "$lookup" : {
+                  "from" : "qe",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"qe" : "qe"}}, {"$project" : {"_id" : 0, "__safeContent__" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"no_schema" : "no_schema", "matched" : [ {"qe" : "qe"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 5: db.csfle joins db.csfle2:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"csfle" : "csfle"}},
+            {
+               "$lookup" : {
+                  "from" : "csfle2",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"csfle2" : "csfle2"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"csfle" : "csfle", "matched" : [ {"csfle2" : "csfle2"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 6: qe joins db.qe2:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "qe");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"qe" : "qe"}},
+            {
+               "$lookup" : {
+                  "from" : "qe2",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"qe2" : "qe2"}}, {"$project" : {"_id" : 0, "__safeContent__" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0, "__safeContent__" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"qe" : "qe", "matched" : [ {"qe2" : "qe2"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 7: db.no_schema joins db.no_schema2:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "no_schema");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"no_schema" : "no_schema"}},
+            {
+               "$lookup" : {
+                  "from" : "no_schema2",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"no_schema2" : "no_schema2"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      bson_t *expect = MAKE_BSON ({"no_schema" : "no_schema", "matched" : [ {"no_schema2" : "no_schema2"} ]});
+      ASSERT_AGG_RETURNS_ONE (coll, pipeline, expect);
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+
+   // Case 8: db.csfle joins db.qe:
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"csfle" : "qe"}},
+            {
+               "$lookup" : {
+                  "from" : "qe",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"qe" : "qe"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      ASSERT_AGG_ERROR (coll, pipeline, "not supported");
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+}
+
+static void
+test_lookup_pre81 (void *unused)
+{
+   BSON_UNUSED (unused);
+   test_lookup_setup ();
+   bson_error_t error;
+
+   // Case 9: test error with <8.1
+   {
+      mongoc_client_t *client = create_encrypted_client (); // Create new client to avoid schema caching.
+      mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "csfle");
+
+      bson_t *pipeline = MAKE_BSON ({
+         "pipeline" : [
+            {"$match" : {"csfle" : "no_schema"}},
+            {
+               "$lookup" : {
+                  "from" : "no_schema",
+                  "as" : "matched",
+                  "pipeline" : [ {"$match" : {"no_schema" : "no_schema"}}, {"$project" : {"_id" : 0}} ]
+               }
+            },
+            {"$project" : {"_id" : 0}}
+         ]
+      });
+
+      ASSERT_AGG_ERROR (coll, pipeline, "Upgrade");
+      mongoc_collection_destroy (coll);
+      mongoc_client_destroy (client);
+   }
+}
+
 void
 test_client_side_encryption_install (TestSuite *suite)
 {
@@ -6822,5 +7320,23 @@ test_client_side_encryption_install (Tes
                          NULL,
                          // No need to test for server version requirements. Test does not contact server.
                          test_framework_skip_if_no_client_side_encryption);
+
+      TestSuite_AddFull (suite,
+                         "/client_side_encryption/test_lookup",
+                         test_lookup,
+                         NULL,
+                         NULL,
+                         test_framework_skip_if_max_wire_version_less_than_26 /* require server 8.1+ */,
+                         test_framework_skip_if_single, /* QE not supported on standalone */
+                         test_framework_skip_if_no_client_side_encryption);
+      TestSuite_AddFull (suite,
+                         "/client_side_encryption/test_lookup/pre-8.1",
+                         test_lookup_pre81,
+                         NULL,
+                         NULL,
+                         test_framework_skip_if_max_wire_version_more_than_25 /* require server < 8.1 */,
+                         test_framework_skip_if_max_wire_version_less_than_21 /* require server > 7.0 for QE support */,
+                         test_framework_skip_if_single, /* QE not supported on standalone */
+                         test_framework_skip_if_no_client_side_encryption);
    }
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-client.c 2.0.2-1/src/libmongoc/tests/test-mongoc-client.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-client.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-client.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,15 +25,13 @@
 #include "mock_server/mock-rs.h"
 #include <common-macros-private.h> // BEGIN_IGNORE_DEPRECATIONS
 #include <common-oid-private.h>
+#include <mlib/loop.h>
 
 
 #ifdef BSON_HAVE_STRINGS_H
 #include <strings.h>
 #endif
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "client-test"
-
 
 static void
 test_client_cmd_w_server_id (void)
@@ -826,106 +824,7 @@ test_wire_version (void)
 
 
 static void
-test_mongoc_client_command (void)
-{
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   const bson_t *doc;
-   bool r;
-   bson_t cmd = BSON_INITIALIZER;
-
-   client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
-
-   bson_append_int32 (&cmd, "ping", 4, 1);
-
-   cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL);
-
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (r);
-   BSON_ASSERT (doc);
-
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (!r);
-   BSON_ASSERT (!doc);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
-   bson_destroy (&cmd);
-}
-
-
-static void
-test_mongoc_client_command_defaults (void)
-{
-   mongoc_client_t *client;
-   mongoc_read_prefs_t *read_prefs;
-   mongoc_read_concern_t *read_concern;
-   mongoc_cursor_t *cursor;
-
-
-   read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-
-   read_concern = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (read_concern, "majority");
-
-   client = test_framework_new_default_client ();
-   mongoc_client_set_read_prefs (client, read_prefs);
-   mongoc_client_set_read_concern (client, read_concern);
-
-   cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL);
-
-   /* Read and Write Concern spec: "If your driver offers a generic RunCommand
-    * method on your database object, ReadConcern MUST NOT be applied
-    * automatically to any command. A user wishing to use a ReadConcern in a
-    * generic command must supply it manually." Server Selection Spec: "The
-    * generic command method MUST ignore any default read preference from
-    * client, database or collection configuration. The generic command method
-    * SHOULD allow an optional read preference argument."
-    */
-   ASSERT (cursor->read_concern->level == NULL);
-   ASSERT (cursor->read_prefs->mode == MONGOC_READ_PRIMARY);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_read_concern_destroy (read_concern);
-   mongoc_read_prefs_destroy (read_prefs);
-   mongoc_client_destroy (client);
-}
-
-
-static void
-test_mongoc_client_command_secondary (void)
-{
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   mongoc_read_prefs_t *read_prefs;
-   bson_t cmd = BSON_INITIALIZER;
-   const bson_t *reply;
-
-   client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
-
-   BSON_APPEND_INT32 (&cmd, "invalid_command_here", 1);
-
-   read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-
-   cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, read_prefs);
-   mongoc_cursor_next (cursor, &reply);
-
-   if (test_framework_is_replset ()) {
-      BSON_ASSERT (test_framework_server_is_secondary (client, mongoc_cursor_get_server_id (cursor)));
-   }
-
-   mongoc_read_prefs_destroy (read_prefs);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
-   bson_destroy (&cmd);
-}
-
-
-static void
-_test_command_read_prefs (bool simple, bool pooled)
+_test_command_read_prefs (bool pooled)
 {
    mock_server_t *server;
    mongoc_uri_t *uri;
@@ -936,8 +835,6 @@ _test_command_read_prefs (bool simple, b
    future_t *future;
    bson_error_t error;
    request_t *request;
-   mongoc_cursor_t *cursor;
-   const bson_t *reply;
 
    /* mock mongos: easiest way to test that read preference is configured */
    server = mock_mongos_new (WIRE_VERSION_MIN);
@@ -958,52 +855,26 @@ _test_command_read_prefs (bool simple, b
 
    cmd = tmp_bson ("{'foo': 1}");
 
-   if (simple) {
-      /* simple, without read preference */
-      future = future_client_command_simple (client, "db", cmd, NULL, NULL, &error);
+   /* without read preference */
+   future = future_client_command_simple (client, "db", cmd, NULL, NULL, &error);
 
-      request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
+   request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
 
-      reply_to_request_with_ok_and_destroy (request);
-      ASSERT_OR_PRINT (future_get_bool (future), error);
-      future_destroy (future);
-
-      /* with read preference */
-      future = future_client_command_simple (client, "db", cmd, secondary_pref, NULL, &error);
-
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'foo': 1,"
-                                                    " '$readPreference': {'mode': 'secondary'}}"));
-      reply_to_request_with_ok_and_destroy (request);
-      ASSERT_OR_PRINT (future_get_bool (future), error);
-      future_destroy (future);
-   } else {
-      /* not simple, no read preference */
-      cursor = mongoc_client_command (client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL);
-      future = future_cursor_next (cursor, &reply);
-      request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
-
-      reply_to_request_with_ok_and_destroy (request);
-      ASSERT (future_get_bool (future));
-      future_destroy (future);
-      mongoc_cursor_destroy (cursor);
+   reply_to_request_with_ok_and_destroy (request);
+   ASSERT_OR_PRINT (future_get_bool (future), error);
+   future_destroy (future);
 
-      /* with read preference */
-      cursor = mongoc_client_command (client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref);
-      future = future_cursor_next (cursor, &reply);
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'foo': 1,"
-                                                    " '$readPreference': {'mode': 'secondary'}}"));
+   /* with read preference */
+   future = future_client_command_simple (client, "db", cmd, secondary_pref, NULL, &error);
 
-      reply_to_request_with_ok_and_destroy (request);
-      ASSERT (future_get_bool (future));
-      future_destroy (future);
-      mongoc_cursor_destroy (cursor);
-   }
+   request = mock_server_receives_msg (server,
+                                       MONGOC_MSG_NONE,
+                                       tmp_bson ("{'$db': 'db',"
+                                                 " 'foo': 1,"
+                                                 " '$readPreference': {'mode': 'secondary'}}"));
+   reply_to_request_with_ok_and_destroy (request);
+   ASSERT_OR_PRINT (future_get_bool (future), error);
+   future_destroy (future);
 
    mongoc_uri_destroy (uri);
 
@@ -1022,49 +893,14 @@ _test_command_read_prefs (bool simple, b
 static void
 test_command_simple_read_prefs_single (void)
 {
-   _test_command_read_prefs (true, false);
+   _test_command_read_prefs (false);
 }
 
 
 static void
 test_command_simple_read_prefs_pooled (void)
 {
-   _test_command_read_prefs (true, true);
-}
-
-
-static void
-test_command_read_prefs_single (void)
-{
-   _test_command_read_prefs (false, false);
-}
-
-
-static void
-test_command_read_prefs_pooled (void)
-{
-   _test_command_read_prefs (false, true);
-}
-
-
-static void
-test_command_not_found (void)
-{
-   mongoc_client_t *client;
-   const bson_t *doc;
-   bson_error_t error;
-   mongoc_cursor_t *cursor;
-
-   client = test_framework_new_default_client ();
-   cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'foo': 1}"), NULL, NULL);
-
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_QUERY);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
+   _test_command_read_prefs (true);
 }
 
 
@@ -1528,14 +1364,13 @@ test_unavailable_seeds (void)
    const bson_t *doc;
    bson_error_t error;
 
-   int i;
-
-   for (i = 0; i < 2; i++) {
-      servers[i] = mock_server_down (); /* hangs up on all requests */
-      mock_server_run (servers[i]);
+   mlib_foreach_arr (mock_server_t *, srv, servers) {
+      *srv = mock_server_down (); /* hangs up on all requests */
+      mock_server_run (*srv);
    }
 
-   uri_str = uri_strs = bson_malloc0 (7 * sizeof (char *));
+   const int num_uris = 6;
+   uri_str = uri_strs = bson_malloc0 ((num_uris + 1) * sizeof (char *));
    *(uri_str++) = bson_strdup_printf ("mongodb://%s", mock_server_get_host_and_port (servers[0]));
 
    *(uri_str++) = bson_strdup_printf (
@@ -1554,8 +1389,8 @@ test_unavailable_seeds (void)
                                       mock_server_get_host_and_port (servers[0]),
                                       mock_server_get_host_and_port (servers[1]));
 
-   for (i = 0; i < (sizeof (uri_strs) / sizeof (const char *)); i++) {
-      client = test_framework_client_new (uri_strs[i], NULL);
+   mlib_foreach (char *, uri, uri_strs, num_uris) {
+      client = test_framework_client_new (*uri, NULL);
       BSON_ASSERT (client);
 
       collection = mongoc_client_get_collection (client, "test", "test");
@@ -1570,8 +1405,8 @@ test_unavailable_seeds (void)
       mongoc_client_destroy (client);
    }
 
-   for (i = 0; i < 2; i++) {
-      mock_server_destroy (servers[i]);
+   mlib_foreach_arr (mock_server_t *, srv, servers) {
+      mock_server_destroy (*srv);
    }
 
    bson_strfreev (uri_strs);
@@ -1885,31 +1720,6 @@ test_recovering (void *ctx)
 
 
 static void
-test_server_status (void)
-{
-   mongoc_client_t *client;
-   bson_error_t error;
-   bson_iter_t iter;
-   bson_t reply;
-
-   client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
-
-   BEGIN_IGNORE_DEPRECATIONS
-   ASSERT_OR_PRINT (mongoc_client_get_server_status (client, NULL, &reply, &error), error);
-   END_IGNORE_DEPRECATIONS
-
-   BSON_ASSERT (bson_iter_init_find (&iter, &reply, "host"));
-   BSON_ASSERT (bson_iter_init_find (&iter, &reply, "version"));
-   BSON_ASSERT (bson_iter_init_find (&iter, &reply, "ok"));
-
-   bson_destroy (&reply);
-
-   mongoc_client_destroy (client);
-}
-
-
-static void
 test_get_database_names (void)
 {
    mock_server_t *server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
@@ -3488,7 +3298,7 @@ test_client_reset_cursors (void)
       This test should timeout and fail if the client does send killCursors. */
 
    coll = mongoc_client_get_collection (client, "test", "test");
-   cursor = mongoc_collection_find (coll, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (coll, tmp_bson (NULL), NULL, NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test'}"));
@@ -3961,22 +3771,49 @@ test_failure_to_auth (void)
 }
 
 static void
-test_does_not_support_mongodbcr (void)
+test_killCursors (void)
 {
-   mongoc_uri_t *uri = test_framework_get_uri ();
-   mongoc_uri_set_username (uri, "foo");
-   mongoc_uri_set_password (uri, "bar");
-   mongoc_uri_set_auth_mechanism (uri, "MONGODB-CR");
-   mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL);
-   ASSERT (client);
-   test_framework_set_ssl_opts (client);
+   mongoc_client_t *client = test_framework_new_default_client ();
+   mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "coll");
    bson_error_t error;
-   bool ok = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error);
-   ASSERT_WITH_MSG (!ok, "expected command to fail, got success");
-   ASSERT_ERROR_CONTAINS (
-      error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unknown authentication mechanism");
+
+   mongoc_collection_drop (coll, NULL); // Ignore error.
+
+   // Insert two documents.
+   {
+      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), error);
+      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), error);
+   }
+
+   uint32_t server_id;
+   int64_t cursor_id;
+
+   // Create cursor.
+   {
+      // Use batchSize:1 so cursor is not exhausted (has non-zero cursor ID) after iterating first result.
+      mongoc_cursor_t *cursor =
+         mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL);
+      // Iterate cursor once to send initial `find` command and create server-side cursor.
+      const bson_t *got;
+      ASSERT (mongoc_cursor_next (cursor, &got));
+      server_id = mongoc_cursor_get_server_id (cursor);
+      cursor_id = mongoc_cursor_get_id (cursor);
+      ASSERT_CMPINT64 (cursor_id, >, 0);
+      mongoc_cursor_destroy (cursor);
+   }
+
+   // Code snippet for NEWS ... begin
+   bson_t *cmd = BCON_NEW ("killCursors", "coll", "cursors", "[", BCON_INT64 (cursor_id), "]");
+   bool ok = mongoc_client_command_simple_with_server_id (client, "db", cmd, NULL, server_id, NULL, &error);
+   if (!ok) {
+      printf ("Failed to send 'killCursors': %s\n", error.message);
+   }
+   bson_destroy (cmd);
+   // Code snippet for NEWS ... end
+
+   ASSERT_OR_PRINT (ok, error);
+   mongoc_collection_destroy (coll);
    mongoc_client_destroy (client);
-   mongoc_uri_destroy (uri);
 }
 
 void
@@ -4029,9 +3866,6 @@ test_client_install (TestSuite *suite)
                       NULL,
                       NULL,
                       test_framework_skip_if_no_auth);
-   TestSuite_AddLive (suite, "/Client/command", test_mongoc_client_command);
-   TestSuite_AddLive (suite, "/Client/command_defaults", test_mongoc_client_command_defaults);
-   TestSuite_AddLive (suite, "/Client/command_secondary", test_mongoc_client_command_secondary);
    TestSuite_AddMockServerTest (suite, "/Client/command_w_server_id", test_client_cmd_w_server_id);
    TestSuite_AddMockServerTest (suite, "/Client/command_w_server_id/sharded", test_client_cmd_w_server_id_sharded);
    TestSuite_AddFull (
@@ -4044,9 +3878,6 @@ test_client_install (TestSuite *suite)
       suite, "/Client/command/read_prefs/simple/single", test_command_simple_read_prefs_single);
    TestSuite_AddMockServerTest (
       suite, "/Client/command/read_prefs/simple/pooled", test_command_simple_read_prefs_pooled);
-   TestSuite_AddMockServerTest (suite, "/Client/command/read_prefs/single", test_command_read_prefs_single);
-   TestSuite_AddMockServerTest (suite, "/Client/command/read_prefs/pooled", test_command_read_prefs_pooled);
-   TestSuite_AddLive (suite, "/Client/command_not_found/cursor", test_command_not_found);
    TestSuite_AddLive (suite, "/Client/command_not_found/simple", test_command_not_found_simple);
    TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/read_prefs", test_command_with_opts_read_prefs);
    TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/read_write", test_read_write_cmd_with_opts);
@@ -4069,7 +3900,6 @@ test_client_install (TestSuite *suite)
    TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_reconnect/single", test_mongos_seeds_reconnect_single);
    TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_reconnect/pooled", test_mongos_seeds_reconnect_pooled);
    TestSuite_AddFull (suite, "/Client/recovering", test_recovering, NULL, NULL, test_framework_skip_if_slow);
-   TestSuite_AddLive (suite, "/Client/server_status", test_server_status);
    TestSuite_AddMockServerTest (suite, "/Client/database_names", test_get_database_names);
    TestSuite_AddFull (
       suite, "/Client/connect/uds", test_mongoc_client_unix_domain_socket, NULL, NULL, test_framework_skip_if_no_uds);
@@ -4172,5 +4002,5 @@ test_client_install (TestSuite *suite)
                       NULL,
                       test_framework_skip_if_no_server_ssl);
 #endif
-   TestSuite_AddLive (suite, "/Client/does_not_support_MONGODB-CR", test_does_not_support_mongodbcr);
+   TestSuite_AddLive (suite, "/Client/killCursors", test_killCursors);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-cluster.c 2.0.2-1/src/libmongoc/tests/test-mongoc-cluster.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-cluster.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-cluster.c	2025-06-19 15:42:22.000000000 +0000
@@ -549,39 +549,6 @@ test_cluster_time_command_simple_pooled
 }
 
 
-/* test the deprecated mongoc_client_command function with $clusterTime */
-static bool
-client_command (mongoc_client_t *client, bson_error_t *error)
-{
-   mongoc_cursor_t *cursor;
-   const bson_t *doc;
-   bool r;
-
-   ASSERT (client);
-
-   cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL);
-
-   mongoc_cursor_next (cursor, &doc);
-   r = !mongoc_cursor_error (cursor, error);
-   mongoc_cursor_destroy (cursor);
-   return r;
-}
-
-
-static void
-test_cluster_time_command_single (void)
-{
-   _test_cluster_time (false, client_command);
-}
-
-
-static void
-test_cluster_time_command_pooled (void)
-{
-   _test_cluster_time (true, client_command);
-}
-
-
 /* test modern mongoc_client_read_command_with_opts with $clusterTime */
 static bool
 client_command_with_opts (mongoc_client_t *client, bson_error_t *error)
@@ -1107,204 +1074,6 @@ test_not_primary_auth_pooled (void)
 }
 
 
-typedef struct {
-   const char *name;
-   const char *q;
-   const char *e;
-   bool secondary;
-   bool cluster_time;
-} dollar_query_test_t;
-
-
-static bool
-auto_hello_callback (request_t *request, void *data, bson_t *hello_response)
-{
-   dollar_query_test_t *test;
-   bson_t cluster_time;
-
-   BSON_UNUSED (request);
-
-   test = (dollar_query_test_t *) data;
-
-   bson_init (hello_response);
-   BSON_APPEND_INT32 (hello_response, "ok", 1);
-   BSON_APPEND_BOOL (hello_response, "isWritablePrimary", !test->secondary);
-   BSON_APPEND_BOOL (hello_response, "secondary", test->secondary);
-   BSON_APPEND_INT32 (hello_response, "minWireVersion", WIRE_VERSION_MIN);
-   BSON_APPEND_INT32 (hello_response, "maxWireVersion", WIRE_VERSION_MAX);
-   BSON_APPEND_UTF8 (hello_response, "setName", "rs");
-
-   if (test->cluster_time) {
-      BSON_APPEND_DOCUMENT_BEGIN (hello_response, "$clusterTime", &cluster_time);
-      BSON_APPEND_TIMESTAMP (&cluster_time, "clusterTime", 1, 1);
-      bson_append_document_end (hello_response, &cluster_time);
-   }
-
-   return true;
-}
-
-
-static void
-_test_dollar_query (void *ctx)
-{
-   dollar_query_test_t *test;
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_read_prefs_t *read_prefs;
-   mongoc_cursor_t *cursor;
-   future_t *future;
-   request_t *request;
-   const bson_t *doc;
-   bson_error_t error;
-
-   test = (dollar_query_test_t *) ctx;
-
-   server = mock_server_new ();
-   mock_server_auto_hello_callback (server, auto_hello_callback, test, NULL);
-   mock_server_run (server);
-
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-   if (test->secondary) {
-      read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-   } else {
-      read_prefs = NULL;
-   }
-
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (test->q), NULL, read_prefs);
-
-   future = future_cursor_next (cursor, &doc);
-   request = mock_server_receives_msg (server, 0, tmp_bson (test->e));
-   reply_to_op_msg_request (request,
-                            MONGOC_MSG_NONE,
-                            tmp_bson ("{'ok': 1,"
-                                      " 'cursor': {"
-                                      "    'id': {'$numberLong': '0'},"
-                                      "    'ns': 'db.collection',"
-                                      "    'firstBatch': []}}"));
-
-   BSON_ASSERT (!future_get_bool (future));
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-
-   future_destroy (future);
-   request_destroy (request);
-   mongoc_read_prefs_destroy (read_prefs);
-   mongoc_cursor_destroy (cursor);
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-dollar_query_test_t tests[] = {{"/Cluster/cluster_time/query/",
-                                "{'a': 1}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': false}"
-                                "}",
-                                false,
-                                false},
-                               {"/Cluster/cluster_time/query/cluster_time",
-                                "{'a': 1}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': true}"
-                                "}",
-                                false,
-                                true},
-                               {"/Cluster/cluster_time/query/secondary",
-                                "{'a': 1}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1}, "
-                                "   '$clusterTime': {'$exists': false},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                false},
-                               {"/Cluster/cluster_time/query/cluster_time_secondary",
-                                "{'a': 1}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1}, "
-                                "   '$clusterTime': {'$exists': true},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                true},
-                               {"/Cluster/cluster_time/dollar_query/from_user",
-                                "{'$query': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': false}"
-                                "}",
-                                false,
-                                false},
-                               {"/Cluster/cluster_time/dollar_query/from_user/cluster_time",
-                                "{'$query': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': true}"
-                                "}",
-                                false,
-                                true},
-                               {"/Cluster/cluster_time/dollar_query/from_user/secondary",
-                                "{'$query': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': false},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                false},
-                               {"/Cluster/cluster_time/dollar_query/from_user/cluster_time_secondary",
-                                "{'$query': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   '$clusterTime': {'$exists': true},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                true},
-                               {"/Cluster/cluster_time/dollar_orderby",
-                                "{'$query': {'a': 1}, '$orderby': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   'sort': {'a': 1}"
-                                "}",
-                                false,
-                                false},
-                               {"/Cluster/cluster_time/dollar_orderby/secondary",
-                                "{'$query': {'a': 1}, '$orderby': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   'sort': {'a': 1},"
-                                "   '$clusterTime': {'$exists': false},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                false},
-                               {"/Cluster/cluster_time/dollar_orderby/cluster_time",
-                                "{'$query': {'a': 1}, '$orderby': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   'sort': {'a': 1},"
-                                "   '$clusterTime': {'$exists': true}"
-                                "}",
-                                false,
-                                true},
-                               {"/Cluster/cluster_time/dollar_orderby/cluster_time_secondary",
-                                "{'$query': {'a': 1}, '$orderby': {'a': 1}}",
-                                "{"
-                                "   'find': 'collection', 'filter': {'a': 1},"
-                                "   'sort': {'a': 1},"
-                                "   '$clusterTime': {'$exists': true},"
-                                "   '$readPreference': {'mode': 'secondary'}"
-                                "}",
-                                true,
-                                true},
-                               {NULL}};
-
 static void
 _test_cluster_hello_fails (bool hangup)
 {
@@ -1553,7 +1322,7 @@ test_hello_on_unknown (void)
 
    client = mongoc_client_pool_pop (pool);
 
-   mongoc_client_set_stream_initiator (client, _initiator_fn, pool);
+   _mongoc_client_set_stream_initiator_single_or_pooled (client, _initiator_fn, pool);
 
    /* The other client marked the server as unknown after this client selected
     * the server and created a stream, but *before* constructing the initial
@@ -1775,14 +1544,6 @@ test_cluster_stream_invalidation_pooled
 void
 test_cluster_install (TestSuite *suite)
 {
-   dollar_query_test_t *p = tests;
-
-   while (p->name) {
-      TestSuite_AddFull (suite, p->name, _test_dollar_query, NULL, p, TestSuite_CheckMockServerAllowed);
-
-      p++;
-   }
-
    TestSuite_AddLive (suite, "/Cluster/test_get_max_bson_obj_size", test_get_max_bson_obj_size);
    TestSuite_AddLive (suite, "/Cluster/test_get_max_msg_size", test_get_max_msg_size);
    TestSuite_AddFull (suite,
@@ -1807,8 +1568,6 @@ test_cluster_install (TestSuite *suite)
                       test_framework_skip_if_slow);
    TestSuite_AddLive (suite, "/Cluster/cluster_time/command_simple/single", test_cluster_time_command_simple_single);
    TestSuite_AddLive (suite, "/Cluster/cluster_time/command_simple/pooled", test_cluster_time_command_simple_pooled);
-   TestSuite_AddLive (suite, "/Cluster/cluster_time/command/single", test_cluster_time_command_single);
-   TestSuite_AddLive (suite, "/Cluster/cluster_time/command/pooled", test_cluster_time_command_pooled);
    TestSuite_AddLive (
       suite, "/Cluster/cluster_time/command_with_opts/single", test_cluster_time_command_with_opts_single);
    TestSuite_AddLive (
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-cmd.c 2.0.2-1/src/libmongoc/tests/test-mongoc-cmd.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-cmd.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-cmd.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,9 +25,6 @@
 #include "test-libmongoc.h"
 #include <mongoc/mongoc-cluster-private.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "cmd-test-options"
-
 
 /* CDRIVER-3303 - mongoc_cmd_parts_assemble sometimes fails to set options;
  * the fix was to refactor the code and this test guards against regressions
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c 2.0.2-1/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c	2025-06-19 15:42:22.000000000 +0000
@@ -9,6 +9,7 @@
 #include "mock_server/future-functions.h"
 #include "test-libmongoc.h"
 #include "mock_server/mock-rs.h"
+#include <mlib/loop.h>
 
 
 typedef struct {
@@ -396,7 +397,6 @@ test_unrecognized_dollar_option (void)
 static void
 test_query_flags (void)
 {
-   int i;
    char *opts;
    char *find_cmd;
    test_collection_find_with_opts_t test_data = {0};
@@ -415,12 +415,12 @@ test_query_flags (void)
       {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, "'tailable': true, 'awaitData': true"},
    };
 
-   for (i = 0; i < (sizeof flags_and_frags) / (sizeof (flag_and_name_t)); i++) {
-      opts = bson_strdup_printf ("{%s}", flags_and_frags[i].json_fragment);
-      find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", flags_and_frags[i].json_fragment);
+   mlib_foreach_arr (flag_and_name_t, it, flags_and_frags) {
+      opts = bson_strdup_printf ("{%s}", it->json_fragment);
+      find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", it->json_fragment);
 
       test_data.opts = opts;
-      test_data.expected_flags = flags_and_frags[i].flag;
+      test_data.expected_flags = it->flag;
       test_data.expected_find_command = find_cmd;
 
       _test_collection_find_with_opts (&test_data);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-collection-find.c 2.0.2-1/src/libmongoc/tests/test-mongoc-collection-find.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-collection-find.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-collection-find.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,1057 +0,0 @@
-#include <mongoc/mongoc.h>
-#include <mongoc/mongoc-cursor-private.h>
-#include <mongoc/mongoc-client-private.h>
-
-#include "TestSuite.h"
-#include "test-libmongoc.h"
-#include "test-conveniences.h"
-#include "mock_server/mock-server.h"
-#include "mock_server/future.h"
-#include "mock_server/future-functions.h"
-
-#include <inttypes.h>
-
-
-typedef struct {
-   /* if do_live is true (the default), actually query the server using the
-    * appropriate wire protocol: either OP_QUERY or a "find" command */
-   bool do_live;
-   int32_t max_wire_version;
-   const char *docs;
-   bson_t *docs_bson;
-   const char *query_input;
-   bson_t *query_bson;
-   const char *fields;
-   bson_t *fields_bson;
-   const char *expected_find_command;
-   int32_t n_return;
-   const char *expected_result;
-   bson_t *expected_result_bson;
-   uint32_t skip;
-   int32_t limit;
-   uint32_t batch_size;
-   mongoc_query_flags_t flags;
-   mongoc_read_prefs_t *read_prefs;
-   const char *filename;
-   int lineno;
-   const char *funcname;
-   uint32_t n_results;
-} test_collection_find_t;
-
-
-#define TEST_COLLECTION_FIND_INIT \
-   {                              \
-      true, INT32_MAX             \
-   }
-
-
-static void
-_insert_test_docs (mongoc_collection_t *collection, const bson_t *docs)
-{
-   bson_iter_t iter;
-   uint32_t len;
-   const uint8_t *data;
-   bson_t doc;
-   bool r;
-   bson_error_t error;
-
-   bson_iter_init (&iter, docs);
-   while (bson_iter_next (&iter)) {
-      bson_iter_document (&iter, &len, &data);
-      BSON_ASSERT (bson_init_static (&doc, data, len));
-      r = mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error);
-      ASSERT_OR_PRINT (r, error);
-   }
-}
-
-
-static void
-_check_cursor (mongoc_cursor_t *cursor, test_collection_find_t *test_data)
-{
-   const bson_t *doc;
-   bson_t actual_result = BSON_INITIALIZER;
-   char str[16];
-   const char *key;
-   uint32_t i = 0;
-   bson_error_t error;
-
-   while (mongoc_cursor_next (cursor, &doc)) {
-      bson_uint32_to_string (i, &key, str, sizeof str);
-      bson_append_document (&actual_result, key, -1, doc);
-      i++;
-   }
-
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-
-   if (i != test_data->n_results) {
-      test_error ("expect %" PRIu32 " results, got %" PRIu32 "", test_data->n_results, i);
-   }
-
-   ASSERT (match_json (&actual_result,
-                       false /* is_command */,
-                       test_data->filename,
-                       test_data->lineno,
-                       test_data->funcname,
-                       test_data->expected_result));
-
-   bson_destroy (&actual_result);
-}
-
-
-static void
-_test_collection_find_live (test_collection_find_t *test_data)
-
-{
-   mongoc_client_t *client;
-   mongoc_database_t *database;
-   char *collection_name;
-   mongoc_collection_t *collection;
-   char *drop_cmd;
-   bool r;
-   bson_error_t error;
-   mongoc_cursor_t *cursor;
-
-   client = test_framework_new_default_client ();
-   database = mongoc_client_get_database (client, "test");
-   collection_name = gen_collection_name ("test");
-   collection = mongoc_database_create_collection (
-      database, collection_name, tmp_bson ("{'capped': true, 'size': 10000}"), &error);
-
-   ASSERT_OR_PRINT (collection, error);
-
-   _insert_test_docs (collection, test_data->docs_bson);
-
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_NONE,
-                                    test_data->skip,
-                                    test_data->limit,
-                                    test_data->batch_size,
-                                    test_data->query_bson,
-                                    test_data->fields_bson,
-                                    test_data->read_prefs);
-
-   _check_cursor (cursor, test_data);
-
-   drop_cmd = bson_strdup_printf ("{'drop': '%s'}", collection_name);
-   r = mongoc_client_command_simple (client, "test", tmp_bson (drop_cmd), NULL, NULL, &error);
-   ASSERT_OR_PRINT (r, error);
-
-   bson_free (drop_cmd);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_database_destroy (database);
-   bson_free (collection_name);
-   mongoc_client_destroy (client);
-}
-
-
-static request_t *
-_check_find_command (mock_server_t *server, test_collection_find_t *test_data)
-{
-   return mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (test_data->expected_find_command));
-}
-
-
-static void
-_reply_to_find_command (request_t *request, test_collection_find_t *test_data)
-{
-   const char *result_json;
-   char *reply_json;
-
-   result_json = test_data->expected_result ? test_data->expected_result : "[]";
-
-   reply_json = bson_strdup_printf ("{'ok': 1,"
-                                    " 'cursor': {"
-                                    "    'id': 0,"
-                                    "    'ns': 'db.collection',"
-                                    "    'firstBatch': %s}}",
-                                    result_json);
-
-   reply_to_request_simple (request, reply_json);
-
-   bson_free (reply_json);
-}
-
-
-/*--------------------------------------------------------------------------
- *
- * _test_collection_find_command --
- *
- *       Start a mock server with @max_wire_version, connect a client, and
- *       execute @test_data->query. Check that the client cursor's results
- *       match @test_data->expected_result.
- *
- *--------------------------------------------------------------------------
- */
-
-static void
-_test_collection_find_command (test_collection_find_t *test_data)
-{
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   bson_error_t error;
-   future_t *future;
-   request_t *request;
-   const bson_t *doc;
-   bool cursor_next_result;
-   bson_t actual_result = BSON_INITIALIZER;
-   char str[16];
-   const char *key;
-   uint32_t i = 0;
-
-   if (!TestSuite_CheckMockServerAllowed ()) {
-      bson_destroy (&actual_result);
-      return;
-   }
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-   cursor = mongoc_collection_find (collection,
-                                    test_data->flags,
-                                    test_data->skip,
-                                    test_data->limit,
-                                    test_data->batch_size,
-                                    test_data->query_bson,
-                                    test_data->fields_bson,
-                                    test_data->read_prefs);
-
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-   future = future_cursor_next (cursor, &doc);
-   request = _check_find_command (server, test_data);
-   ASSERT (request);
-   _reply_to_find_command (request, test_data);
-
-   cursor_next_result = future_get_bool (future);
-   /* did we expect at least one result? */
-   ASSERT (cursor_next_result == (test_data->n_results > 0));
-   BSON_ASSERT (!mongoc_cursor_error (cursor, NULL));
-
-   if (cursor_next_result) {
-      bson_append_document (&actual_result, "0", -1, doc);
-      i++;
-
-      /* check remaining results */
-      while (mongoc_cursor_next (cursor, &doc)) {
-         bson_uint32_to_string (i, &key, str, sizeof str);
-         bson_append_document (&actual_result, key, -1, doc);
-         i++;
-      }
-
-      BSON_ASSERT (!mongoc_cursor_error (cursor, NULL));
-   }
-
-   if (i != test_data->n_results) {
-      test_error ("Expected %" PRIu32 " results, got %" PRIu32 "\n", test_data->n_results, i);
-   }
-
-   ASSERT (match_json (&actual_result,
-                       false /* is_command */,
-                       test_data->filename,
-                       test_data->lineno,
-                       test_data->funcname,
-                       test_data->expected_result));
-
-   bson_destroy (&actual_result);
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-_test_collection_find (test_collection_find_t *test_data)
-{
-   BSON_ASSERT (test_data->expected_find_command);
-
-   test_data->docs_bson = tmp_bson (test_data->docs);
-   test_data->query_bson = tmp_bson (test_data->query_input);
-   test_data->fields_bson = test_data->fields ? tmp_bson (test_data->fields) : NULL;
-   test_data->expected_result_bson = tmp_bson (test_data->expected_result);
-   test_data->n_results = bson_count_keys (test_data->expected_result_bson);
-
-   if (test_data->do_live) {
-      int64_t max_version;
-
-      test_framework_get_max_wire_version (&max_version);
-      if (test_data->max_wire_version >= max_version) {
-         _test_collection_find_live (test_data);
-      }
-   }
-
-   _test_collection_find_command (test_data);
-}
-
-
-static void
-test_dollar_query (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}, {'_id': 2}]";
-   test_data.query_input = "{'$query': {'_id': 1}}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'_id': 1}}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_dollar_or (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-
-   test_data.docs = "[{'_id': 1}, {'_id': 2}, {'_id': 3}]";
-   test_data.query_input = "{'$or': [{'_id': 1}, {'_id': 3}]}";
-   test_data.expected_find_command = "{'$db': 'db',"
-                                     " 'find': 'collection',"
-                                     " 'filter': {'$or': [{'_id': 1}, {'_id': 3}]}}";
-
-   test_data.expected_result = "[{'_id': 1}, {'_id': 3}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_mixed_dollar_nondollar (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-
-   test_data.docs = "[{'a': 1}, {'a': 1, 'b': 2}, {'a': 2}]";
-   test_data.query_input = "{'a': 1, '$or': [{'b': 1}, {'b': 2}]}";
-   test_data.expected_find_command = "{'$db': 'db',"
-                                     " 'find': 'collection',"
-                                     " 'filter': {'a': 1, '$or': [{'b': 1}, {'b': 2}]}}";
-
-   test_data.expected_result = "[{'a': 1, 'b': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-/* test that we can query for a document by a key named "filter" */
-static void
-test_key_named_filter (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1, 'filter': 1}, {'_id': 2, 'filter': 2}]";
-   test_data.query_input = "{'filter': 2}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}";
-   test_data.expected_result = "[{'_id': 2, 'filter': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-/* test that we can query for a document by a key named "filter" using $query */
-static void
-test_key_named_filter_with_dollar_query (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1, 'filter': 1}, {'_id': 2, 'filter': 2}]";
-   test_data.query_input = "{'$query': {'filter': 2}}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}";
-   test_data.expected_result = "[{'_id': 2, 'filter': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-/* test 'filter': {'i': 2} */
-static void
-test_subdoc_named_filter (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]";
-   test_data.query_input = "{'filter': {'i': 2}}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}";
-   test_data.expected_result = "[{'_id': 2, 'filter': {'i': 2}}]";
-
-   _test_collection_find (&test_data);
-}
-
-
-/* test '$query': {'filter': {'i': 2}} */
-static void
-test_subdoc_named_filter_with_dollar_query (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]";
-   test_data.query_input = "{'$query': {'filter': {'i': 2}}}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}";
-   test_data.expected_result = "[{'_id': 2, 'filter': {'i': 2}}]";
-   _test_collection_find (&test_data);
-}
-
-
-/* test future-compatibility with a new server's find command options */
-static void
-test_newoption (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.query_input = "{'$query': {'_id': 1}, '$newOption': true}";
-   test_data.expected_find_command = "{'$db': 'db',"
-                                     " 'find': 'collection',"
-                                     " 'filter': {'_id': 1},"
-                                     " 'newOption': true}";
-
-   /* won't work today */
-   test_data.do_live = false;
-
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_orderby (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}, {'_id': 2}]";
-   test_data.query_input = "{'$query': {}, '$orderby': {'_id': -1}}";
-   test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {}, 'sort': {'_id': -1}}";
-   test_data.expected_result = "[{'_id': 2}, {'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_fields (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1, 'a': 1, 'b': 2}]";
-   test_data.fields = "{'_id': 0, 'b': 1}";
-   test_data.expected_find_command = "{'$db': 'db',"
-                                     " 'find': 'collection',"
-                                     " 'filter': {},"
-                                     " 'projection': {'_id': 0, 'b': 1}}";
-   test_data.expected_result = "[{'b': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-_test_int_modifier (const char *mod)
-{
-   char *query;
-   char *find_command;
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-
-   test_data.expected_result = test_data.docs = "[{'_id': 1}]";
-
-   query = bson_strdup_printf ("{'$query': {}, '$%s': 9999}", mod);
-
-   /* find command has same modifier, without the $-prefix */
-   find_command = bson_strdup_printf ("{'find': 'collection', 'filter': {}, '%s': 9999}", mod);
-
-   test_data.query_input = query;
-   test_data.expected_find_command = find_command;
-   _test_collection_find (&test_data);
-   bson_free (query);
-   bson_free (find_command);
-}
-
-
-static void
-test_maxtimems (void)
-{
-   _test_int_modifier ("maxTimeMS");
-}
-
-
-static void
-test_comment (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.query_input = "{'$query': {}, '$comment': 'hi'}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'comment': 'hi'}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_hint (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.query_input = "{'$query': {}, '$hint': { '_id': 1 }}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'hint': { '_id': 1 }}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_max (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   /* MongoDB 4.2 requires that max/min also use hint */
-   test_data.query_input = "{'$query': {}, '$max': {'_id': 100}, '$hint': { '_id': 1 }}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, "
-                                     "'max': {'_id': 100}, 'hint': { '_id': 1 }}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_min (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   /* MongoDB 4.2 requires that max/min also use hint */
-   test_data.query_input = "{'$query': {}, '$min': {'_id': 1}, '$hint': { '_id': 1 }}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, "
-                                     "'min': {'_id': 1}, 'hint': { '_id': 1 }}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_snapshot (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   /* "snapshot" dropped in MongoDB 4.0, wire version 7 */
-   test_data.max_wire_version = 6;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.query_input = "{'$query': {}, '$snapshot': true}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'snapshot': true}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-/* $showDiskLoc becomes showRecordId */
-static void
-test_diskloc (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.query_input = "{'$query': {}, '$showDiskLoc': true}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'showRecordId': true}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_returnkey (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.query_input = "{'$query': {}, '$returnKey': true}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'returnKey': true}";
-   test_data.expected_result = "[{}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_skip (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}, {'_id': 2}]";
-   test_data.skip = 1;
-   test_data.query_input = "{'$query': {}, '$orderby': {'_id': 1}}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, "
-                                     "'sort': {'_id': 1}, 'skip': "
-                                     "{'$numberLong': '1'}}";
-   test_data.expected_result = "[{'_id': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_batch_size (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}]";
-   test_data.batch_size = 2;
-   test_data.n_return = 2;
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'batchSize': {'$numberLong': '2'}}";
-   test_data.expected_result = "[{'_id': 1}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_limit (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}, {'_id': 2}, {'_id': 3}]";
-   test_data.limit = 2;
-   test_data.query_input = "{'$query': {}, '$orderby': {'_id': 1}}";
-   test_data.n_return = 2;
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, "
-                                     "'sort': {'_id': 1}, 'limit': "
-                                     "{'$numberLong': '2'}}";
-   test_data.expected_result = "[{'_id': 1}, {'_id': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_negative_limit (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-   test_data.docs = "[{'_id': 1}, {'_id': 2}, {'_id': 3}]";
-   test_data.limit = -2;
-   test_data.query_input = "{'$query': {}, '$orderby': {'_id': 1}}";
-   test_data.n_return = -2;
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {}, "
-                                     "'sort': {'_id': 1}, 'singleBatch': true, "
-                                     "'limit': {'$numberLong': '2'}}";
-   test_data.expected_result = "[{'_id': 1}, {'_id': 2}]";
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_unrecognized_dollar_option (void)
-{
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-
-   test_data.query_input = "{'$query': {'a': 1}, '$dumb': 1}";
-   test_data.expected_find_command = "{'find': 'collection', 'filter': {'a': 1}, 'dumb': 1}";
-
-   test_data.do_live = false;
-   _test_collection_find (&test_data);
-}
-
-
-static void
-test_query_flags (void)
-{
-   int i;
-   char *find_cmd;
-   test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT;
-
-   typedef struct {
-      mongoc_query_flags_t flag;
-      const char *json_fragment;
-   } flag_and_name_t;
-
-   /* secondaryOk is not supported as an option, exhaust is tested separately */
-   flag_and_name_t flags_and_frags[] = {
-      {MONGOC_QUERY_TAILABLE_CURSOR, "'tailable': true"},
-      {MONGOC_QUERY_OPLOG_REPLAY, "'oplogReplay': true"},
-      {MONGOC_QUERY_NO_CURSOR_TIMEOUT, "'noCursorTimeout': true"},
-      {MONGOC_QUERY_PARTIAL, "'allowPartialResults': true"},
-      {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, "'tailable': true, 'awaitData': true"},
-   };
-
-   test_data.expected_result = test_data.docs = "[{'_id': 1}]";
-
-   for (i = 0; i < (sizeof flags_and_frags) / (sizeof (flag_and_name_t)); i++) {
-      find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", flags_and_frags[i].json_fragment);
-
-      test_data.flags = flags_and_frags[i].flag;
-      test_data.expected_find_command = find_cmd;
-
-      _test_collection_find (&test_data);
-
-      bson_free (find_cmd);
-   }
-}
-
-
-static void
-test_exhaust (void)
-{
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   request_t *request;
-   future_t *future;
-   const bson_t *doc;
-   bson_error_t error;
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson (NULL), NULL, NULL);
-
-   future = future_cursor_next (cursor, &doc);
-
-   /* Find, getMore and killCursors commands spec: "The find command does not
-    * support the exhaust flag from OP_QUERY. Drivers that support exhaust MUST
-    * fallback to existing OP_QUERY wire protocol messages."
-    */
-   request = mock_server_receives_request (server);
-   reply_to_find_request (
-      request, MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, 0, 0, "db.collection", "{}", false /* is_command */);
-
-   ASSERT (future_get_bool (future));
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_getmore_batch_size (void)
-{
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   future_t *future;
-   request_t *request;
-   const bson_t *doc;
-   uint32_t batch_sizes[] = {0, 1, 2};
-   size_t i;
-   char *batch_size_json;
-   bson_error_t error;
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-
-   for (i = 0; i < sizeof (batch_sizes) / sizeof (uint32_t); i++) {
-      cursor =
-         mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, batch_sizes[i], tmp_bson ("{}"), NULL, NULL);
-
-      future = future_cursor_next (cursor, &doc);
-
-      if (batch_sizes[i]) {
-         batch_size_json = bson_strdup_printf ("{'$numberLong': '%u'}", batch_sizes[i]);
-      } else {
-         batch_size_json = bson_strdup ("{'$exists': false}");
-      }
-
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'find': 'collection',"
-                                                    " 'filter': {},"
-                                                    " 'batchSize': %s}",
-                                                    batch_size_json));
-
-      reply_to_request_simple (request,
-                               "{'ok': 1,"
-                               " 'cursor': {"
-                               "    'id': 0,"
-                               "    'ns': 'db.collection',"
-                               "    'firstBatch': []}}");
-
-      /* no result */
-      ASSERT (!future_get_bool (future));
-      ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-
-      future_destroy (future);
-      request_destroy (request);
-      bson_free (batch_size_json);
-      mongoc_cursor_destroy (cursor);
-   }
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_getmore_invalid_reply (void *ctx)
-{
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   future_t *future;
-   request_t *request;
-   const bson_t *doc;
-   bson_error_t error;
-
-   BSON_UNUSED (ctx);
-
-   if (!TestSuite_CheckMockServerAllowed ()) {
-      return;
-   }
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
-
-   future = future_cursor_next (cursor, &doc);
-   request = mock_server_receives_msg (
-      server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'find': 'collection', 'filter': {}}"));
-
-   reply_to_request_simple (request,
-                            "{'ok': 1,"
-                            " 'cursor': {"
-                            "    'id': {'$numberLong': '123'},"
-                            "    'ns': 'db.collection',"
-                            "    'firstBatch': [{}]}}");
-
-   ASSERT (future_get_bool (future));
-
-   future_destroy (future);
-   request_destroy (request);
-
-   future = future_cursor_next (cursor, &doc);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'db',"
-                                                 " 'getMore': {'$numberLong': '123'},"
-                                                 " 'collection': 'collection'}"));
-
-   /* missing "cursor" */
-   reply_to_request_with_ok_and_destroy (request);
-
-   ASSERT (!future_get_bool (future));
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_PROTOCOL);
-   ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_PROTOCOL_INVALID_REPLY);
-   ASSERT_CONTAINS (error.message, "getMore");
-
-   future_destroy (future);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_getmore_await (void)
-{
-   typedef struct {
-      mongoc_query_flags_t flags;
-      bool expect_await;
-   } await_test_t;
-
-   await_test_t await_tests[] = {
-      {MONGOC_QUERY_NONE, false},
-      {MONGOC_QUERY_TAILABLE_CURSOR, false},
-      {MONGOC_QUERY_AWAIT_DATA, false},
-      {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, true},
-   };
-
-   mock_server_t *server;
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   future_t *future;
-   request_t *request;
-   const bson_t *doc;
-   size_t i;
-   char *max_time_json;
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-
-   for (i = 3; i < sizeof (await_tests) / sizeof (await_test_t); i++) {
-      cursor = mongoc_collection_find (collection, await_tests[i].flags, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
-
-      ASSERT (mongoc_cursor_more (cursor));
-
-      ASSERT_CMPINT (0, ==, mongoc_cursor_get_max_await_time_ms (cursor));
-      mongoc_cursor_set_max_await_time_ms (cursor, 123);
-      future = future_cursor_next (cursor, &doc);
-
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'find': 'collection',"
-                                                    " 'maxTimeMS': {'$exists': false},"
-                                                    " 'maxAwaitTimeMS': {'$exists': false}}"));
-
-      /* reply with cursor id 1 */
-      reply_to_request_simple (request,
-                               "{'ok': 1,"
-                               " 'cursor': {"
-                               "    'id': 1,"
-                               "    'ns': 'db.collection',"
-                               "    'firstBatch': [{}]}}");
-
-      /* no result or error */
-      ASSERT (future_get_bool (future));
-      ASSERT (mongoc_cursor_more (cursor));
-
-      future_destroy (future);
-      request_destroy (request);
-
-      future = future_cursor_next (cursor, &doc);
-
-      if (await_tests[i].expect_await) {
-         max_time_json = "123";
-      } else {
-         max_time_json = "{'$exists': false}";
-      }
-
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'getMore': {'$numberLong': '1'},"
-                                                    " 'collection': 'collection',"
-                                                    " 'maxAwaitTimeMS': {'$exists': false},"
-                                                    " 'maxTimeMS': {'$numberLong': '%s'}}",
-                                                    max_time_json));
-
-      BSON_ASSERT (request);
-      /* reply with cursor id 0 */
-      reply_to_request_simple (request,
-                               "{'ok': 1,"
-                               " 'cursor': {"
-                               "    'id': 0,"
-                               "    'ns': 'db.collection',"
-                               "    'nextBatch': []}}");
-
-      /* no result or error */
-      ASSERT (!future_get_bool (future));
-      ASSERT (!mongoc_cursor_error (cursor, NULL));
-      ASSERT (!mongoc_cursor_more (cursor));
-      ASSERT (!doc);
-
-      future_destroy (future);
-      request_destroy (request);
-      mongoc_cursor_destroy (cursor);
-   }
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-_test_tailable_timeout (bool pooled)
-{
-   mongoc_client_pool_t *pool = NULL;
-   mongoc_client_t *client;
-   mongoc_database_t *database;
-   char *collection_name;
-   mongoc_collection_t *collection;
-   bool r;
-   bson_error_t error;
-   mongoc_cursor_t *cursor;
-   const bson_t *doc;
-   bson_t reply;
-
-   capture_logs (true);
-
-   if (pooled) {
-      pool = test_framework_new_default_client_pool ();
-      client = mongoc_client_pool_pop (pool);
-   } else {
-      client = test_framework_new_default_client ();
-   }
-
-   database = mongoc_client_get_database (client, "test");
-   collection_name = gen_collection_name ("test");
-
-   collection = mongoc_database_get_collection (database, collection_name);
-   mongoc_collection_drop (collection, NULL);
-   mongoc_collection_destroy (collection);
-
-   collection = mongoc_database_create_collection (
-      database, collection_name, tmp_bson ("{'capped': true, 'size': 10000}"), &error);
-
-   ASSERT_OR_PRINT (collection, error);
-
-   r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error);
-
-   ASSERT_OR_PRINT (r, error);
-
-   client->cluster.sockettimeoutms = 100;
-   cursor = mongoc_collection_find (
-      collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson ("{'a': 1}"), NULL, NULL);
-
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-
-   client->cluster.sockettimeoutms = 30 * 1000 * 1000;
-   r = mongoc_client_command_simple (client, "test", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error);
-
-   ASSERT_OR_PRINT (r, error);
-   ASSERT_HAS_FIELD (&reply, "version");
-
-   bson_destroy (&reply);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_database_destroy (database);
-   bson_free (collection_name);
-
-   if (pooled) {
-      mongoc_client_pool_push (pool, client);
-      mongoc_client_pool_destroy (pool);
-   } else {
-      mongoc_client_destroy (client);
-   }
-}
-
-
-static void
-test_tailable_timeout_single (void)
-{
-   _test_tailable_timeout (false);
-}
-
-
-#ifndef MONGOC_ENABLE_SSL_SECURE_TRANSPORT
-#ifndef MONGOC_ENABLE_SSL_SECURE_CHANNEL
-static void
-test_tailable_timeout_pooled (void)
-{
-   _test_tailable_timeout (true);
-}
-#endif
-#endif
-
-
-void
-test_collection_find_install (TestSuite *suite)
-{
-   TestSuite_AddLive (suite, "/Collection/find/dollar_query", test_dollar_query);
-   TestSuite_AddLive (suite, "/Collection/find/dollar_or", test_dollar_or);
-   TestSuite_AddLive (suite, "/Collection/find/mixed_dollar_nondollar", test_mixed_dollar_nondollar);
-   TestSuite_AddLive (suite, "/Collection/find/key_named_filter", test_key_named_filter);
-   TestSuite_AddLive (suite, "/Collection/find/key_named_filter/$query", test_key_named_filter_with_dollar_query);
-   TestSuite_AddLive (suite, "/Collection/find/subdoc_named_filter", test_subdoc_named_filter);
-   TestSuite_AddLive (suite, "/Collection/find/subdoc_named_filter/$query", test_subdoc_named_filter_with_dollar_query);
-   TestSuite_AddLive (suite, "/Collection/find/newoption", test_newoption);
-   TestSuite_AddLive (suite, "/Collection/find/orderby", test_orderby);
-   TestSuite_AddLive (suite, "/Collection/find/fields", test_fields);
-   TestSuite_AddLive (suite, "/Collection/find/modifiers/maxtimems", test_maxtimems);
-   TestSuite_AddLive (suite, "/Collection/find/comment", test_comment);
-   TestSuite_AddLive (suite, "/Collection/find/hint", test_hint);
-   TestSuite_AddLive (suite, "/Collection/find/max", test_max);
-   TestSuite_AddLive (suite, "/Collection/find/min", test_min);
-   TestSuite_AddLive (suite, "/Collection/find/modifiers/bool", test_snapshot);
-   TestSuite_AddLive (suite, "/Collection/find/showdiskloc", test_diskloc);
-   TestSuite_AddLive (suite, "/Collection/find/returnkey", test_returnkey);
-   TestSuite_AddLive (suite, "/Collection/find/skip", test_skip);
-   TestSuite_AddLive (suite, "/Collection/find/batch_size", test_batch_size);
-   TestSuite_AddLive (suite, "/Collection/find/limit", test_limit);
-   TestSuite_AddLive (suite, "/Collection/find/negative_limit", test_negative_limit);
-   TestSuite_Add (suite, "/Collection/find/unrecognized", test_unrecognized_dollar_option);
-   TestSuite_AddLive (suite, "/Collection/find/flags", test_query_flags);
-   TestSuite_AddMockServerTest (suite, "/Collection/find/exhaust", test_exhaust);
-   TestSuite_AddMockServerTest (suite, "/Collection/getmore/batch_size", test_getmore_batch_size);
-   TestSuite_AddFull (
-      suite, "/Collection/getmore/invalid_reply", test_getmore_invalid_reply, NULL, NULL, test_framework_skip_if_slow);
-   TestSuite_AddMockServerTest (suite, "/Collection/getmore/await", test_getmore_await);
-   TestSuite_AddLive (suite, "/Collection/tailable/timeout/single", test_tailable_timeout_single);
-#ifndef MONGOC_ENABLE_SSL_SECURE_TRANSPORT
-#ifndef MONGOC_ENABLE_SSL_SECURE_CHANNEL
-   TestSuite_AddLive (suite, "/Collection/tailable/timeout/pooled", test_tailable_timeout_pooled);
-#endif
-#endif
-}
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-collection.c 2.0.2-1/src/libmongoc/tests/test-mongoc-collection.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-collection.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-collection.c	2025-06-19 15:42:22.000000000 +0000
@@ -332,27 +332,10 @@ test_read_prefs_is_valid (void *ctx)
    ASSERT (mongoc_cursor_error (cursor, &error));
    mongoc_cursor_destroy (cursor);
 
-   /* mongoc_collection_command */
-   cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs);
-   ASSERT (cursor);
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   mongoc_cursor_destroy (cursor);
-
    /* mongoc_collection_command_simple */
    ASSERT (!mongoc_collection_command_simple (collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error));
    bson_destroy (&reply);
 
-   /* mongoc_collection_count_with_opts */
-   ASSERT (mongoc_collection_count_with_opts (
-              collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, NULL, read_prefs, &error) == -1);
-
-   /* mongoc_collection_find */
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs);
-
-   ASSERT (cursor);
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   mongoc_cursor_destroy (cursor);
-
    /* mongoc_collection_find_with_opts */
    cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, read_prefs);
 
@@ -372,27 +355,10 @@ test_read_prefs_is_valid (void *ctx)
    ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
    mongoc_cursor_destroy (cursor);
 
-   /* mongoc_collection_command */
-   cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs);
-   ASSERT (cursor);
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-   mongoc_cursor_destroy (cursor);
-
    /* mongoc_collection_command_simple */
    ASSERT_OR_PRINT (mongoc_collection_command_simple (collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error),
                     error);
    bson_destroy (&reply);
-   /* mongoc_collection_count_with_opts */
-   ASSERT_OR_PRINT (mongoc_collection_count_with_opts (
-                       collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, NULL, read_prefs, &error) != -1,
-                    error);
-
-   /* mongoc_collection_find */
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs);
-
-   ASSERT (cursor);
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-   mongoc_cursor_destroy (cursor);
 
    /* mongoc_collection_find_with_opts */
    cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, read_prefs);
@@ -716,34 +682,6 @@ test_insert_many (void)
    mongoc_client_destroy (client);
 }
 
-
-static void
-test_insert_bulk_empty (void)
-{
-   mongoc_collection_t *collection;
-   mongoc_database_t *database;
-   mongoc_client_t *client;
-   bson_error_t error;
-   bson_t *bptr = NULL;
-
-   client = test_framework_new_default_client ();
-   database = get_test_database (client);
-   collection = get_test_collection (client, "test_insert_bulk_empty");
-
-   BEGIN_IGNORE_DEPRECATIONS
-   ASSERT (!mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) &bptr, 0, NULL, &error));
-   END_IGNORE_DEPRECATIONS
-
-   ASSERT_CMPINT (MONGOC_ERROR_COLLECTION, ==, error.domain);
-   ASSERT_CMPINT (MONGOC_ERROR_COLLECTION_INSERT_FAILED, ==, error.code);
-   ASSERT_CONTAINS (error.message, "empty insert");
-
-   mongoc_collection_destroy (collection);
-   mongoc_database_destroy (database);
-   mongoc_client_destroy (client);
-}
-
-
 char *
 make_string (size_t len)
 {
@@ -855,59 +793,6 @@ test_insert_command_keys (void)
 
 
 static void
-test_save (void)
-{
-   mongoc_collection_t *collection;
-   mongoc_database_t *database;
-   mongoc_client_t *client;
-   bson_context_t *context;
-   bson_error_t error;
-   bson_oid_t oid;
-   unsigned i;
-   bson_t b;
-   bool r;
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   database = get_test_database (client);
-   ASSERT (database);
-
-   collection = get_test_collection (client, "test_save");
-   ASSERT (collection);
-
-   /* don't care if ns not found. */
-   (void) mongoc_collection_drop (collection, &error);
-
-   context = bson_context_new (BSON_CONTEXT_NONE);
-   ASSERT (context);
-
-   BEGIN_IGNORE_DEPRECATIONS
-
-   for (i = 0; i < 10; i++) {
-      bson_init (&b);
-      bson_oid_init (&oid, context);
-      bson_append_oid (&b, "_id", 3, &oid);
-      bson_append_utf8 (&b, "hello", 5, "/world", 5);
-      ASSERT_OR_PRINT (mongoc_collection_save (collection, &b, NULL, &error), error);
-      bson_destroy (&b);
-   }
-
-   r = mongoc_collection_save (collection, tmp_bson ("{'': 1}"), NULL, &error);
-
-   END_IGNORE_DEPRECATIONS
-
-   ASSERT (!r);
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document");
-
-   mongoc_collection_destroy (collection);
-   mongoc_database_destroy (database);
-   bson_context_destroy (context);
-   mongoc_client_destroy (client);
-}
-
-
-static void
 test_regex (void)
 {
    mongoc_collection_t *collection;
@@ -998,7 +883,7 @@ test_decimal128 (void *ctx)
    count = mongoc_collection_count_documents (collection, &query, NULL, NULL, NULL, &error);
    ASSERT (count > 0);
 
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, &query, NULL, NULL);
    ASSERT (mongoc_cursor_next (cursor, &dec));
 
    ASSERT (bson_iter_init (&dec_iter, dec));
@@ -1059,7 +944,7 @@ test_update (void)
       bson_t *u = tmp_bson ("{'': 1 }");
       bool ok = mongoc_collection_update (coll, MONGOC_UPDATE_NONE, q, u, NULL, &error);
       ASSERT (!ok);
-      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key");
+      ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty string");
    }
 
    // Test a successful replacement:
@@ -1288,7 +1173,6 @@ test_insert_w0 (void)
    mongoc_write_concern_append (wc, &opts);
    r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error);
    ASSERT_OR_PRINT (r, error);
-   ASSERT (mongoc_collection_get_last_error (collection) == NULL);
 
    bson_destroy (&opts);
    mongoc_write_concern_destroy (wc);
@@ -1313,7 +1197,6 @@ test_update_w0 (void)
    r = mongoc_collection_update (
       collection, MONGOC_UPDATE_NONE, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), wc, &error);
    ASSERT_OR_PRINT (r, error);
-   ASSERT (bson_empty (mongoc_collection_get_last_error (collection)));
 
    mongoc_write_concern_destroy (wc);
    mongoc_collection_destroy (collection);
@@ -1366,13 +1249,11 @@ test_insert_twice_w0 (void)
    mongoc_write_concern_append (wc, &opts);
    r = mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error);
    ASSERT_OR_PRINT (r, error);
-   ASSERT (mongoc_collection_get_last_error (collection) == NULL);
 
    /* Insert same document for the second time, but we should not get
     * an error since we don't wait for a server response */
    r = mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error);
    ASSERT_OR_PRINT (r, error);
-   ASSERT (mongoc_collection_get_last_error (collection) == NULL);
 
    bson_destroy (&opts);
    mongoc_write_concern_destroy (wc);
@@ -1387,15 +1268,14 @@ test_index (void)
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
-   mongoc_index_opt_t opt;
    bson_error_t error;
    bson_t keys;
+   mongoc_index_model_t *im;
    bson_t *opts = NULL;
    mongoc_write_concern_t *bad_wc;
    mongoc_write_concern_t *good_wc;
    bool r;
 
-   mongoc_index_opt_init (&opt);
    opts = bson_new ();
 
    client = test_framework_new_default_client ();
@@ -1413,13 +1293,14 @@ test_index (void)
 
    bson_init (&keys);
    bson_append_int32 (&keys, "hello", -1, 1);
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   im = mongoc_index_model_new (&keys, NULL);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, NULL, &error), error);
 
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, NULL, &error), error);
 
    ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1", &error), error);
 
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, NULL, &error), error);
 
    /* invalid writeConcern */
    bad_wc->wtimeout = -10;
@@ -1443,7 +1324,7 @@ test_index (void)
    mongoc_write_concern_set_w (bad_wc, 99);
 
    if (!test_framework_is_mongos ()) { /* skip if sharded */
-      ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+      ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, NULL, &error), error);
       bson_reinit (opts);
       mongoc_write_concern_append_bad (bad_wc, opts);
       r = mongoc_collection_drop_index_with_opts (collection, "hello_1", opts, &error);
@@ -1454,6 +1335,7 @@ test_index (void)
    ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
 
    bson_destroy (&keys);
+   mongoc_index_model_destroy (im);
    bson_destroy (opts);
    mongoc_write_concern_destroy (bad_wc);
    mongoc_write_concern_destroy (good_wc);
@@ -1468,17 +1350,16 @@ test_index_w_write_concern (void)
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
-   mongoc_index_opt_t opt;
    mongoc_write_concern_t *good_wc;
    mongoc_write_concern_t *bad_wc;
    bson_error_t error;
    bson_t keys;
+   mongoc_index_model_t *im;
    bson_t reply;
    bson_t *opts = NULL;
    bool result;
    bool is_mongos = test_framework_is_mongos ();
 
-   mongoc_index_opt_init (&opt);
    opts = bson_new ();
 
    client = test_framework_new_default_client ();
@@ -1497,12 +1378,13 @@ test_index_w_write_concern (void)
 
    bson_init (&keys);
    bson_append_int32 (&keys, "hello", -1, 1);
+   im = mongoc_index_model_new (&keys, NULL);
 
    /* writeConcern that will not pass validation */
    bad_wc->wtimeout = -10;
    bson_reinit (opts);
    mongoc_write_concern_append_bad (bad_wc, opts);
-   ASSERT (!mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error));
+   ASSERT (!mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, &reply, &error));
    bson_destroy (&reply);
 
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern");
@@ -1514,7 +1396,7 @@ test_index_w_write_concern (void)
    mongoc_write_concern_set_w (good_wc, 1);
    bson_reinit (opts);
    mongoc_write_concern_append (good_wc, opts);
-   result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error);
+   result = mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, &reply, &error);
    ASSERT_OR_PRINT (result, error);
    ASSERT (!error.code);
 
@@ -1533,8 +1415,9 @@ test_index_w_write_concern (void)
    bson_reinit (opts);
    mongoc_write_concern_append_bad (bad_wc, opts);
    /* skip this part of the test if sharded cluster */
-   if (!is_mongos) {
-      ASSERT (!mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error));
+   const bool CDRIVER5945_fixed = false; // TODO(CDRIVER-5945): once fixed, unskip this test
+   if (!is_mongos && CDRIVER5945_fixed) {
+      ASSERT (!mongoc_collection_create_indexes_with_opts (collection, &im, 1, opts, &reply, &error));
       assert_wc_oob_error (&error);
 
       ASSERT (!bson_empty (&reply));
@@ -1542,13 +1425,15 @@ test_index_w_write_concern (void)
    }
 
    /* Make sure it doesn't crash with a NULL reply or writeConcern */
-   result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, NULL, &error);
+   result = mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error);
    ASSERT_OR_PRINT (result, error);
 
    ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1", &error), error);
 
    /* Now attempt to create an invalid index which the server will reject */
    bson_reinit (&keys);
+   mongoc_index_model_destroy (im);
+   im = mongoc_index_model_new (&keys, NULL);
 
    /* Try to create an index like {abc: "hallo thar"} (won't work,
       should really be something like {abc: 1})
@@ -1556,7 +1441,7 @@ test_index_w_write_concern (void)
       This fails both on legacy and modern versions of the server
    */
    BSON_APPEND_UTF8 (&keys, "abc", "hallo thar");
-   result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, &reply, &error);
+   result = mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, &reply, &error);
    bson_destroy (&reply);
 
    ASSERT (!result);
@@ -1564,11 +1449,12 @@ test_index_w_write_concern (void)
    memset (&error, 0, sizeof (error));
 
    /* Try again but with reply NULL. Shouldn't crash */
-   result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, NULL, &error);
+   result = mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error);
    ASSERT (!result);
    ASSERT (strlen (error.message) > 0);
 
    bson_destroy (&keys);
+   mongoc_index_model_destroy (im);
 
    ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
 
@@ -1586,12 +1472,9 @@ test_index_compound (void)
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
-   mongoc_index_opt_t opt;
    bson_error_t error;
    bson_t keys;
 
-   mongoc_index_opt_init (&opt);
-
    client = test_framework_new_default_client ();
    ASSERT (client);
 
@@ -1604,13 +1487,15 @@ test_index_compound (void)
    bson_init (&keys);
    bson_append_int32 (&keys, "hello", -1, 1);
    bson_append_int32 (&keys, "world", -1, -1);
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   mongoc_index_model_t *im = mongoc_index_model_new (&keys, NULL);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
    ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1_world_-1", &error), error);
 
    bson_destroy (&keys);
+   mongoc_index_model_destroy (im);
 
    ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
 
@@ -1626,18 +1511,14 @@ test_index_geo (void *unused)
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
-   mongoc_index_opt_t opt;
-   mongoc_index_opt_geo_t geo_opt;
    bson_error_t error;
    bool r;
    bson_t keys;
+   mongoc_index_model_t *im;
    uint32_t id;
 
    BSON_UNUSED (unused);
 
-   mongoc_index_opt_init (&opt);
-   mongoc_index_opt_geo_init (&geo_opt);
-
    client = test_framework_new_default_client ();
    ASSERT (client);
 
@@ -1650,7 +1531,8 @@ test_index_geo (void *unused)
    /* Create a basic 2d index */
    bson_init (&keys);
    BSON_APPEND_UTF8 (&keys, "location", "2d");
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   im = mongoc_index_model_new (&keys, NULL);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
    ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "location_2d", &error), error);
 
@@ -1658,11 +1540,8 @@ test_index_geo (void *unused)
    bson_destroy (&keys);
    bson_init (&keys);
    BSON_APPEND_UTF8 (&keys, "location", "2d");
-
-   geo_opt.twod_location_min = -123;
-   geo_opt.twod_location_max = +123;
-   geo_opt.twod_bits_precision = 30;
-   opt.geo_options = &geo_opt;
+   mongoc_index_model_destroy (im);
+   im = mongoc_index_model_new (&keys, tmp_bson (BSON_STR ({"min" : -123.0, "max" : 123.0, "bits" : 30})));
 
    /* TODO this hack is needed for single-threaded tests */
    id = mc_tpld_servers_const (mc_tpld_unsafe_get_const (client->topology))->items[0].id;
@@ -1671,7 +1550,7 @@ test_index_geo (void *unused)
    ASSERT_OR_PRINT (description, error);
 
    if (description->max_wire_version > 0) {
-      ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+      ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
       ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "location_2d", &error), error);
    }
@@ -1681,22 +1560,20 @@ test_index_geo (void *unused)
    bson_init (&keys);
    BSON_APPEND_UTF8 (&keys, "location", "geoHaystack");
    BSON_APPEND_INT32 (&keys, "category", 1);
-
-   mongoc_index_opt_geo_init (&geo_opt);
-   geo_opt.haystack_bucket_size = 5;
-
-   opt.geo_options = &geo_opt;
+   mongoc_index_model_destroy (im);
+   im = mongoc_index_model_new (&keys, tmp_bson (BSON_STR ({"bucketSize" : 5})));
 
    description =
       mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), id, &error);
    ASSERT_OR_PRINT (description, error);
    if (description->max_wire_version > 0) {
-      ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+      ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
       r = mongoc_collection_drop_index (collection, "location_geoHaystack_category_1", &error);
       ASSERT_OR_PRINT (r, error);
    }
 
+   mongoc_index_model_destroy (im);
    bson_destroy (&keys);
    mongoc_collection_destroy (collection);
    mongoc_database_destroy (database);
@@ -1735,10 +1612,9 @@ test_index_storage (void)
    mongoc_collection_t *collection = NULL;
    mongoc_database_t *database = NULL;
    mongoc_client_t *client = NULL;
-   mongoc_index_opt_t opt;
-   mongoc_index_opt_wt_t wt_opt;
    bson_error_t error;
    bson_t keys;
+   mongoc_index_model_t *im = NULL;
    char *engine = NULL;
 
    client = test_framework_new_default_client ();
@@ -1750,9 +1626,6 @@ test_index_storage (void)
       goto cleanup;
    }
 
-   mongoc_index_opt_init (&opt);
-   mongoc_index_opt_wt_init (&wt_opt);
-
    database = get_test_database (client);
    ASSERT (database);
 
@@ -1763,15 +1636,13 @@ test_index_storage (void)
    bson_init (&keys);
    bson_append_int32 (&keys, "hello", -1, 1);
 
-   /* Add storage option to the index */
-   wt_opt.base.type = MONGOC_INDEX_STORAGE_OPT_WIREDTIGER;
-   wt_opt.config_str = "block_compressor=zlib";
-
-   opt.storage_options = (mongoc_index_opt_storage_t *) &wt_opt;
+   im = mongoc_index_model_new (
+      &keys, tmp_bson (BSON_STR ({"storageEngine" : {"wiredTiger" : {"configString" : "block_compressor=zlib"}}})));
 
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error);
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, NULL, &error), error);
 
 cleanup:
+   mongoc_index_model_destroy (im);
    if (engine)
       bson_free (engine);
    if (collection)
@@ -1782,304 +1653,6 @@ cleanup:
       mongoc_client_destroy (client);
 }
 
-static void
-test_count (void)
-{
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   bson_error_t error;
-   int64_t count;
-   bson_t b;
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   collection = mongoc_client_get_collection (client, "test", "test");
-   ASSERT (collection);
-
-   bson_init (&b);
-   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-
-   if (count == -1) {
-      MONGOC_WARNING ("%s\n", error.message);
-   }
-   ASSERT (count != -1);
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-}
-
-
-static void
-test_count_read_pref (void)
-{
-   mock_server_t *server;
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   mongoc_read_prefs_t *prefs;
-   future_t *future;
-   request_t *request;
-   bson_error_t error;
-
-   server = mock_mongos_new (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   mock_server_auto_endsessions (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-   prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-
-   mongoc_collection_set_read_prefs (collection, prefs);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'db',"
-                                                 " 'count': 'collection',"
-                                                 " '$readPreference': {'mode': 'secondary'}}"));
-
-   reply_to_request_simple (request, "{'ok': 1, 'n': 1}");
-   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);
-
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_read_prefs_destroy (prefs);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_count_read_concern (void)
-{
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   mongoc_read_concern_t *rc;
-   mock_server_t *server;
-   request_t *request;
-   bson_error_t error;
-   future_t *future;
-   int64_t count;
-   bson_t b;
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   ASSERT (client);
-
-   collection = mongoc_client_get_collection (client, "test", "test");
-   ASSERT (collection);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request =
-      mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'count': 'test', 'query': {}}"));
-
-   reply_to_request_simple (request, "{ 'n' : 42, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 42, error);
-   request_destroy (request);
-   future_destroy (future);
-
-   /* readConcern: { level: majority } */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'count': 'test',"
-                                                 " 'query': {},"
-                                                 " 'readConcern': {'level': 'majority'}}"));
-
-   reply_to_request_simple (request, "{ 'n' : 43, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 43, error);
-   mongoc_read_concern_destroy (rc);
-   request_destroy (request);
-   future_destroy (future);
-
-   /* readConcern: { level: local } */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'count': 'test',"
-                                                 " 'query': {},"
-                                                 " 'readConcern': {'level': 'local'}}"));
-
-   reply_to_request_simple (request, "{ 'n' : 44, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 44, error);
-   mongoc_read_concern_destroy (rc);
-   request_destroy (request);
-   future_destroy (future);
-
-   /* readConcern: { level: futureCompatible } */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, "futureCompatible");
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'count': 'test',"
-                                                 " 'query': {},"
-                                                 " 'readConcern': {'level': 'futureCompatible'}}"));
-
-   reply_to_request_simple (request, "{ 'n' : 45, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 45, error);
-   mongoc_read_concern_destroy (rc);
-   request_destroy (request);
-   future_destroy (future);
-
-   /* Setting readConcern to NULL should not send readConcern */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, NULL);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'count': 'test',"
-                                                 " 'query': {},"
-                                                 " 'readConcern': { '$exists': false }}"));
-
-   reply_to_request_simple (request, "{ 'n' : 46, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 46, error);
-   mongoc_read_concern_destroy (rc);
-   request_destroy (request);
-   future_destroy (future);
-
-   /* Fresh read_concern should not send readConcern */
-   rc = mongoc_read_concern_new ();
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'count': 'test',"
-                                                 " 'query': {},"
-                                                 " 'readConcern': { '$exists': false }}"));
-
-   reply_to_request_simple (request, "{ 'n' : 47, 'ok' : 1 } ");
-   count = future_get_int64_t (future);
-   ASSERT_OR_PRINT (count == 47, error);
-
-   mongoc_read_concern_destroy (rc);
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_count_read_concern_live (void *unused)
-{
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   mongoc_read_concern_t *rc;
-   bson_error_t error;
-   int64_t count;
-   bson_t b;
-
-   BSON_UNUSED (unused);
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   collection = mongoc_client_get_collection (client, "test", "test");
-   ASSERT (collection);
-
-   // Drop collection.
-   // Use writeConcern=majority so later readConcern=majority observes dropped
-   // collection.
-   {
-      mongoc_write_concern_t *wc = mongoc_write_concern_new ();
-      mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY);
-      bson_t drop_opts = BSON_INITIALIZER;
-      mongoc_write_concern_append (wc, &drop_opts);
-      if (!mongoc_collection_drop_with_opts (collection, &drop_opts, &error)) {
-         // Ignore an "ns not found" error.
-         if (NULL == strstr (error.message, "ns not found")) {
-            ASSERT_OR_PRINT (false, error);
-         }
-      }
-
-      bson_destroy (&drop_opts);
-      mongoc_write_concern_destroy (wc);
-   }
-
-   bson_init (&b);
-   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   ASSERT_OR_PRINT (count != -1, error);
-   ASSERT_CMPINT64 (count, ==, 0);
-
-   /* Setting readConcern to NULL should not send readConcern */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, NULL);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   ASSERT_OR_PRINT (count != -1, error);
-   ASSERT_CMPINT64 (count, ==, 0);
-   mongoc_read_concern_destroy (rc);
-
-   /* readConcern: { level: local } should raise error pre 3.2 */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   ASSERT_OR_PRINT (count != -1, error);
-   ASSERT_CMPINT64 (count, ==, 0);
-   mongoc_read_concern_destroy (rc);
-
-   /* readConcern: { level: majority } should raise error pre 3.2 */
-   rc = mongoc_read_concern_new ();
-   mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY);
-   mongoc_collection_set_read_concern (collection, rc);
-
-   bson_init (&b);
-   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error);
-   bson_destroy (&b);
-   ASSERT_OR_PRINT (count != -1, error);
-   ASSERT_CMPINT64 (count, ==, 0);
-   mongoc_read_concern_destroy (rc);
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-}
-
 int
 skip_unless_server_has_decimal128 (void)
 {
@@ -2103,76 +1676,6 @@ mongod_supports_majority_read_concern (v
 
 
 static void
-test_count_with_opts (void)
-{
-   mock_server_t *server;
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   future_t *future;
-   request_t *request;
-   bson_error_t error;
-
-   /* use a mongos since we don't send SECONDARY_OK to mongos by default */
-   server = mock_mongos_new (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   mock_server_auto_endsessions (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-
-   future = future_collection_count_with_opts (
-      collection, MONGOC_QUERY_SECONDARY_OK, NULL, 0, 0, tmp_bson ("{'opt': 1}"), NULL, &error);
-
-   request =
-      mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'count': 'collection', 'opt': 1}"));
-
-   reply_to_request_simple (request, "{'ok': 1, 'n': 1}");
-   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);
-
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
-test_count_with_collation (void)
-{
-   mock_server_t *server;
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   future_t *future;
-   request_t *request;
-   bson_error_t error;
-
-   server = mock_server_with_auto_hello (WIRE_VERSION_MIN);
-   mock_server_run (server);
-
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-
-   future = future_collection_count_with_opts (
-      collection, MONGOC_QUERY_SECONDARY_OK, NULL, 0, 0, tmp_bson ("{'collation': {'locale': 'en'}}"), NULL, &error);
-
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'db',"
-                                                 " 'count': 'collection',"
-                                                 " 'collation': {'locale': 'en'}}"));
-   reply_to_request_simple (request, "{'ok': 1, 'n': 1}");
-   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);
-   request_destroy (request);
-
-
-   future_destroy (future);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
 test_count_documents (void)
 {
    mock_server_t *server;
@@ -2900,74 +2403,6 @@ test_aggregate_server_id_option (void *c
    mongoc_client_destroy (client);
 }
 
-
-static void
-test_validate (void *ctx)
-{
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   bson_iter_t iter;
-   bson_error_t error;
-   bson_t doc = BSON_INITIALIZER;
-   bson_t opts = BSON_INITIALIZER;
-   bson_t reply;
-   bool r;
-   const uint32_t expected_err_domain = MONGOC_ERROR_BSON;
-   const uint32_t expected_err_code = MONGOC_ERROR_BSON_INVALID;
-
-   BSON_UNUSED (ctx);
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   collection = get_test_collection (client, "test_validate");
-   ASSERT (collection);
-
-   ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error);
-
-   BSON_APPEND_BOOL (&opts, "full", true);
-
-   ASSERT_OR_PRINT (mongoc_collection_validate (collection, &opts, &reply, &error), error);
-
-   BSON_ASSERT (bson_iter_init_find (&iter, &reply, "valid"));
-
-   bson_destroy (&reply);
-
-   /* Make sure we don't segfault when reply is NULL */
-   ASSERT_OR_PRINT (mongoc_collection_validate (collection, &opts, NULL, &error), error);
-
-   bson_reinit (&opts);
-   BSON_APPEND_UTF8 (&opts, "full", "bad_value");
-
-   /* invalidate reply */
-   reply.len = 0;
-   BSON_ASSERT (!bson_validate (&reply, BSON_VALIDATE_NONE, NULL));
-
-   r = mongoc_collection_validate (collection, &opts, &reply, &error);
-   BSON_ASSERT (!r);
-   BSON_ASSERT (error.domain == expected_err_domain);
-   BSON_ASSERT (error.code == expected_err_code);
-
-   /* check that reply has been initialized */
-   BSON_ASSERT (bson_validate (&reply, 0, NULL));
-
-   /* Make sure we don't segfault when reply is NULL */
-   memset (&error, 0, sizeof (error));
-   r = mongoc_collection_validate (collection, &opts, NULL, &error);
-   BSON_ASSERT (!r);
-   BSON_ASSERT (error.domain == expected_err_domain);
-   BSON_ASSERT (error.code == expected_err_code);
-
-   ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
-
-   bson_destroy (&reply);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   bson_destroy (&doc);
-   bson_destroy (&opts);
-}
-
-
 static void
 test_rename (void)
 {
@@ -3067,82 +2502,6 @@ test_rename (void)
 
 
 static void
-test_stats (void *unused)
-{
-   BSON_UNUSED (unused);
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   bson_error_t error;
-   bson_iter_t iter;
-   bson_t stats;
-   bson_t doc = BSON_INITIALIZER;
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   collection = get_test_collection (client, "test_stats");
-   ASSERT (collection);
-
-   ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error);
-
-   BEGIN_IGNORE_DEPRECATIONS
-   ASSERT_OR_PRINT (mongoc_collection_stats (collection, NULL, &stats, &error), error);
-   END_IGNORE_DEPRECATIONS
-
-   BSON_ASSERT (bson_iter_init_find (&iter, &stats, "ns"));
-
-   BSON_ASSERT (bson_iter_init_find (&iter, &stats, "count"));
-   BSON_ASSERT (bson_iter_as_int64 (&iter) >= 1);
-
-   bson_destroy (&stats);
-
-   ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   bson_destroy (&doc);
-}
-
-
-static void
-test_stats_read_pref (void)
-{
-   mock_server_t *server;
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   mongoc_read_prefs_t *prefs;
-   future_t *future;
-   request_t *request;
-   bson_error_t error;
-   bson_t stats;
-
-   server = mock_mongos_new (WIRE_VERSION_MIN);
-   mock_server_run (server);
-   mock_server_auto_endsessions (server);
-   client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
-   collection = mongoc_client_get_collection (client, "db", "collection");
-   prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-   mongoc_collection_set_read_prefs (collection, prefs);
-   future = future_collection_stats (collection, NULL, &stats, &error);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'db',"
-                                                 " 'collStats': 'collection',"
-                                                 " '$readPreference': {'mode': 'secondary'}}"));
-
-   reply_to_request_with_ok_and_destroy (request);
-   ASSERT_OR_PRINT (future_get_bool (future), error);
-
-   future_destroy (future);
-   bson_destroy (&stats);
-   mongoc_read_prefs_destroy (prefs);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   mock_server_destroy (server);
-}
-
-
-static void
 test_find_and_modify_write_concern (void)
 {
    mongoc_collection_t *collection;
@@ -3303,7 +2662,7 @@ test_large_return (void *ctx)
 
    BSON_APPEND_OID (&query, "_id", &oid);
 
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, &query, NULL, NULL);
    BSON_ASSERT (cursor);
    bson_destroy (&query);
 
@@ -3418,7 +2777,7 @@ _test_insert_validate (insert_fn_t inser
    collection = get_test_collection (client, "test_insert_validate");
 
    BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'': 1}"), NULL, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key");
+   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty string");
 
    BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'_id': {'$a': 1}}"), tmp_bson ("{'validate': false}"), &error));
    ASSERT_CMPUINT32 (error.domain, ==, (uint32_t) MONGOC_ERROR_SERVER);
@@ -3434,7 +2793,7 @@ _test_insert_validate (insert_fn_t inser
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
-                          "invalid document for insert: keys cannot contain \".\": \"a.a\"");
+                          "invalid document for insert: Disallowed '.' in element key: \"a.a\"");
 
    /* {validate: true} is still prohibited */
    BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': true}"), &error));
@@ -3451,49 +2810,6 @@ _test_insert_validate (insert_fn_t inser
 }
 
 static void
-test_insert_bulk_validate (void)
-{
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   bson_error_t error;
-   const bson_t *docs_client_invalid[] = {tmp_bson ("{'a': 1}"), tmp_bson ("{'': 2}")};
-   const bson_t *docs_server_invalid[] = {tmp_bson ("{'a': 1}"), tmp_bson ("{'_id': {'$a': 2}}")};
-
-   BEGIN_IGNORE_DEPRECATIONS
-   client = test_framework_new_default_client ();
-   mongoc_client_set_error_api (client, 2);
-   collection = get_test_collection (client, "test_insert_validate");
-
-   /* Invalid documents, validation. */
-   BSON_ASSERT (!mongoc_collection_insert_bulk (
-      collection, MONGOC_INSERT_NONE, docs_client_invalid, 2, NULL /* write concern */, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document");
-
-   /* Invalid documents, no validation. */
-   BSON_ASSERT (!mongoc_collection_insert_bulk (collection,
-                                                (mongoc_insert_flags_t) MONGOC_INSERT_NO_VALIDATE,
-                                                docs_server_invalid,
-                                                2,
-                                                NULL /* write concern */,
-                                                &error));
-   ASSERT_CMPUINT32 (error.domain, ==, (uint32_t) MONGOC_ERROR_SERVER);
-
-   /* Valid document, validation. */
-   ASSERT_OR_PRINT (mongoc_collection_insert_bulk (collection,
-                                                   MONGOC_INSERT_NONE,
-                                                   docs_client_invalid,
-                                                   1 /* don't include invalid second doc. */,
-                                                   NULL /* write concern */,
-                                                   &error),
-                    error);
-
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   END_IGNORE_DEPRECATIONS
-}
-
-
-static void
 test_insert_one_validate (void)
 {
    _test_insert_validate (insert_one);
@@ -3525,25 +2841,7 @@ test_find_limit (void)
    client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
    collection = mongoc_client_get_collection (client, "test", "test");
 
-   /* test mongoc_collection_find and mongoc_collection_find_with_opts */
-   cursor = mongoc_collection_find (
-      collection, MONGOC_QUERY_NONE, 0 /* skip */, 2 /* limit */, 0 /* batch_size */, tmp_bson ("{}"), NULL, NULL);
-
-   future = future_cursor_next (cursor, &doc);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'find': 'test',"
-                                                 " 'filter': {},"
-                                                 " 'limit': {'$numberLong': '2'}}"));
-
-   reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}");
-   BSON_ASSERT (future_get_bool (future));
-
-   future_destroy (future);
-   request_destroy (request);
-   mongoc_cursor_destroy (cursor);
-
+   /* test mongoc_collection_find_with_opts */
    cursor = mongoc_collection_find_with_opts (
       collection, tmp_bson ("{}"), tmp_bson ("{'limit': {'$numberLong': '2'}}"), NULL);
 
@@ -3585,25 +2883,7 @@ test_find_batch_size (void)
    client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
    collection = mongoc_client_get_collection (client, "test", "test");
 
-   /* test mongoc_collection_find and mongoc_collection_find_with_opts */
-   cursor = mongoc_collection_find (
-      collection, MONGOC_QUERY_NONE, 0 /* skip */, 0 /* limit */, 2 /* batch_size */, tmp_bson ("{}"), NULL, NULL);
-
-   future = future_cursor_next (cursor, &doc);
-   request = mock_server_receives_msg (server,
-                                       MONGOC_MSG_NONE,
-                                       tmp_bson ("{'$db': 'test',"
-                                                 " 'find': 'test',"
-                                                 " 'filter': {},"
-                                                 " 'batchSize': {'$numberLong': '2'}}"));
-
-   reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}");
-   BSON_ASSERT (future_get_bool (future));
-
-   future_destroy (future);
-   request_destroy (request);
-   mongoc_cursor_destroy (cursor);
-
+   /* test mongoc_collection_find_with_opts */
    cursor = mongoc_collection_find_with_opts (
       collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': {'$numberLong': '2'}}"), NULL);
 
@@ -3628,47 +2908,12 @@ test_find_batch_size (void)
 
 
 static void
-test_command_fq (void *context)
-{
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   const bson_t *doc = NULL;
-   bson_iter_t iter;
-   bson_t *cmd;
-   bool r;
-
-   BSON_UNUSED (context);
-
-   client = test_framework_new_default_client ();
-   ASSERT (client);
-
-   cmd = tmp_bson ("{ 'dbstats': 1}");
-
-   cursor = mongoc_client_command (client, "sometest.$cmd", MONGOC_QUERY_SECONDARY_OK, 0, -1, 0, cmd, NULL, NULL);
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (r);
-
-   if (bson_iter_init_find (&iter, doc, "db") && BSON_ITER_HOLDS_UTF8 (&iter)) {
-      ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), "sometest");
-   } else {
-      test_error ("dbstats didn't return 'db' key?");
-   }
-
-
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (!r);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
-}
-
-static void
 test_get_index_info (void)
 {
    mongoc_collection_t *collection;
    mongoc_client_t *client;
-   mongoc_index_opt_t opt1;
-   mongoc_index_opt_t opt2;
+   mongoc_index_model_t *im1;
+   mongoc_index_model_t *im2;
    bson_error_t error = {0};
    mongoc_cursor_t *cursor;
    const bson_t *indexinfo;
@@ -3737,18 +2982,18 @@ test_get_index_info (void)
    BSON_APPEND_INT32 (&indexkey1, "raspberry", 1);
    idx1_name = mongoc_collection_keys_to_index_string (&indexkey1);
    ASSERT (strcmp (idx1_name, "raspberry_1") == 0);
-   mongoc_index_opt_init (&opt1);
-   opt1.background = true;
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &indexkey1, &opt1, &error), error);
+   im1 = mongoc_index_model_new (&indexkey1, tmp_bson ("{'background': true}"));
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im1, 1, NULL, NULL, &error), error);
+   mongoc_index_model_destroy (im1);
    bson_destroy (&indexkey1);
 
    bson_init (&indexkey2);
    BSON_APPEND_INT32 (&indexkey2, "snozzberry", 1);
    idx2_name = mongoc_collection_keys_to_index_string (&indexkey2);
    ASSERT (strcmp (idx2_name, "snozzberry_1") == 0);
-   mongoc_index_opt_init (&opt2);
-   opt2.unique = true;
-   ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &indexkey2, &opt2, &error), error);
+   im2 = mongoc_index_model_new (&indexkey2, tmp_bson ("{'unique': true}"));
+   ASSERT_OR_PRINT (mongoc_collection_create_indexes_with_opts (collection, &im2, 1, NULL, NULL, &error), error);
+   mongoc_index_model_destroy (im2);
    bson_destroy (&indexkey2);
 
    /*
@@ -3903,15 +3148,8 @@ test_find_read_concern (void)
    client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
    collection = mongoc_client_get_collection (client, "test", "test");
 
-   /* No read_concern set - test find and find_with_opts */
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_SECONDARY_OK,
-                                    0 /* skip */,
-                                    0 /* limit */,
-                                    0 /* batch_size */,
-                                    tmp_bson ("{}"),
-                                    NULL,
-                                    NULL);
+   /* No read_concern set */
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
 
    future = future_cursor_next (cursor, &doc);
    request =
@@ -3931,14 +3169,11 @@ test_find_read_concern (void)
    rc = mongoc_read_concern_new ();
    mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL);
    mongoc_collection_set_read_concern (collection, rc);
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_SECONDARY_OK,
-                                    0 /* skip */,
-                                    0 /* limit */,
-                                    0 /* batch_size */,
-                                    tmp_bson ("{}"),
-                                    NULL,
-                                    NULL);
+   cursor = mongoc_collection_find_with_opts (collection,
+
+                                              tmp_bson ("{}"),
+                                              NULL,
+                                              NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server,
@@ -3963,14 +3198,7 @@ test_find_read_concern (void)
    rc = mongoc_read_concern_new ();
    mongoc_read_concern_set_level (rc, "random");
    mongoc_collection_set_read_concern (collection, rc);
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_SECONDARY_OK,
-                                    0 /* skip */,
-                                    0 /* limit */,
-                                    0 /* batch_size */,
-                                    tmp_bson ("{}"),
-                                    NULL,
-                                    NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server,
@@ -3994,14 +3222,7 @@ test_find_read_concern (void)
    /* empty readConcernLevel doesn't send anything */
    rc = mongoc_read_concern_new ();
    mongoc_collection_set_read_concern (collection, rc);
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_SECONDARY_OK,
-                                    0 /* skip */,
-                                    0 /* limit */,
-                                    0 /* batch_size */,
-                                    tmp_bson ("{}"),
-                                    NULL,
-                                    NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server,
@@ -4026,14 +3247,7 @@ test_find_read_concern (void)
    rc = mongoc_read_concern_new ();
    mongoc_read_concern_set_level (rc, NULL);
    mongoc_collection_set_read_concern (collection, rc);
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_SECONDARY_OK,
-                                    0 /* skip */,
-                                    0 /* limit */,
-                                    0 /* batch_size */,
-                                    tmp_bson ("{}"),
-                                    NULL,
-                                    NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server,
@@ -4340,9 +3554,7 @@ test_index_with_collation (void)
    mongoc_collection_t *collection;
    request_t *request;
    bson_error_t error;
-   bson_t *collation;
    bson_t keys;
-   mongoc_index_opt_t opt;
    bson_t reply;
    future_t *future;
 
@@ -4353,11 +3565,11 @@ test_index_with_collation (void)
 
    bson_init (&keys);
    bson_append_int32 (&keys, "hello", -1, 1);
-   mongoc_index_opt_init (&opt);
-   collation = BCON_NEW ("locale", BCON_UTF8 ("en"), "strength", BCON_INT32 (2));
-   opt.collation = collation;
 
-   future = future_collection_create_index_with_opts (collection, &keys, &opt, NULL, &reply, &error);
+   mongoc_index_model_t *im =
+      mongoc_index_model_new (&keys, tmp_bson (BSON_STR ({"collation" : {"locale" : "en", "strength" : 2}})));
+
+   future = future_collection_create_indexes_with_opts (collection, &im, 1, NULL, &reply, &error);
 
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
@@ -4371,8 +3583,8 @@ test_index_with_collation (void)
    reply_to_request_with_ok_and_destroy (request);
    ASSERT (future_get_bool (future));
 
+   mongoc_index_model_destroy (im);
    bson_destroy (&reply);
-   bson_destroy (collation);
    bson_destroy (&keys);
    future_destroy (future);
    mongoc_collection_destroy (collection);
@@ -4408,12 +3620,14 @@ test_create_index_fail (void *context)
    bool r;
    bson_t reply;
    bson_error_t error;
+   mongoc_index_model_t *im;
 
    BSON_UNUSED (context);
 
    client = test_framework_client_new ("mongodb://example.doesntexist/?connectTimeoutMS=10", NULL);
    collection = mongoc_client_get_collection (client, "test", "test");
-   r = mongoc_collection_create_index_with_opts (collection, tmp_bson ("{'a': 1}"), NULL, NULL, &reply, &error);
+   im = mongoc_index_model_new (tmp_bson ("{'a': 1}"), NULL);
+   r = mongoc_collection_create_indexes_with_opts (collection, &im, 1, NULL, &reply, &error);
 
    ASSERT (!r);
    ASSERT_ERROR_CONTAINS (
@@ -4422,6 +3636,7 @@ test_create_index_fail (void *context)
    /* reply was initialized */
    ASSERT (bson_empty (&reply));
 
+   mongoc_index_model_destroy (im);
    bson_destroy (&reply);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);
@@ -4919,7 +4134,7 @@ _test_update_validate (update_fn_t updat
    /* bson_validate_with_error will yield a different error message than the
     * standard key check in _mongoc_validate_replace */
    if (update_fn == mongoc_collection_replace_one) {
-      msg = "invalid argument for replace: keys cannot begin with \"$\": \"$set\"";
+      msg = "invalid argument for replace: Disallowed '$' in element key: \"$set\"";
    }
 
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg);
@@ -5369,10 +4584,8 @@ test_remove_multi (void)
       mongoc_collection_remove (collection, MONGOC_REMOVE_NONE, tmp_bson ("{'_id': {'$gte': 8}}"), NULL, &error),
       error);
 
-   /* mongoc_collection_delete is an alias of mongoc_collection_remove, although
-    * its flag type differs slightly */
    ASSERT_OR_PRINT (
-      mongoc_collection_delete (collection, MONGOC_DELETE_NONE, tmp_bson ("{'_id': {'$lt': 2}}"), NULL, &error), error);
+      mongoc_collection_remove (collection, MONGOC_REMOVE_NONE, tmp_bson ("{'_id': {'$lt': 2}}"), NULL, &error), error);
 
    _test_docs_in_coll_matches (collection, tmp_bson ("{'x': 1234}"), NULL, 6);
 
@@ -5687,111 +4900,6 @@ test_insert_one_reports_id (void)
 
 #undef ASSERT_INDEX_EXISTS
 
-static void
-test_get_last_error (void)
-{
-   mongoc_client_t *client = test_framework_new_default_client ();
-   mongoc_collection_t *coll = get_test_collection (client, "test_get_last_error");
-   bson_error_t error;
-   bool ok;
-
-   // Test mongoc_collection_update:
-   {
-      mongoc_collection_drop (coll, NULL);
-
-      // Clear error:
-      ASSERT_OR_PRINT (mongoc_collection_command_simple (coll, tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error);
-      ASSERT (!mongoc_collection_get_last_error (coll));
-
-      // Insert a document to remove:
-      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), NULL, NULL, &error), error);
-
-      // Update:
-      ok = mongoc_collection_update (
-         coll, MONGOC_UPDATE_NONE, tmp_bson ("{}"), tmp_bson ("{'$set': {'foo': 'bar'}}"), NULL, &error);
-      ASSERT_OR_PRINT (ok, error);
-      const bson_t *gle = mongoc_collection_get_last_error (coll);
-      ASSERT_MATCH (
-         gle,
-         BSON_STR (
-            {"nInserted" : 0, "nMatched" : 1, "nModified" : 1, "nRemoved" : 0, "nUpserted" : 0, "writeErrors" : []}));
-   }
-
-   // Test mongoc_collection_remove:
-   {
-      mongoc_collection_drop (coll, NULL);
-
-      // Clear error:
-      ASSERT_OR_PRINT (mongoc_collection_command_simple (coll, tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error);
-      ASSERT (!mongoc_collection_get_last_error (coll));
-
-      // Insert a document to remove:
-      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), NULL, NULL, &error), error);
-
-      ok = mongoc_collection_remove (coll, MONGOC_REMOVE_NONE, tmp_bson ("{}"), NULL, &error);
-      ASSERT_OR_PRINT (ok, error);
-      const bson_t *gle = mongoc_collection_get_last_error (coll);
-      ASSERT_MATCH (
-         gle,
-         BSON_STR (
-            {"nInserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 1, "nUpserted" : 0, "writeErrors" : []}));
-   }
-
-   // Test mongoc_collection_delete:
-   {
-      mongoc_collection_drop (coll, NULL);
-
-      // Clear error:
-      ASSERT_OR_PRINT (mongoc_collection_command_simple (coll, tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error);
-      ASSERT (!mongoc_collection_get_last_error (coll));
-
-      // Insert a document to delete:
-      ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), NULL, NULL, &error), error);
-
-      ok = mongoc_collection_delete (coll, MONGOC_DELETE_NONE, tmp_bson ("{}"), NULL, &error);
-      ASSERT_OR_PRINT (ok, error);
-      const bson_t *gle = mongoc_collection_get_last_error (coll);
-      ASSERT_MATCH (
-         gle,
-         BSON_STR (
-            {"nInserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 1, "nUpserted" : 0, "writeErrors" : []}));
-   }
-
-   // Test mongoc_collection_insert_bulk:
-   {
-      mongoc_collection_drop (coll, NULL);
-
-      // Clear error:
-      ASSERT_OR_PRINT (mongoc_collection_command_simple (coll, tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error);
-      ASSERT (!mongoc_collection_get_last_error (coll));
-
-      bson_t *docs[] = {tmp_bson ("{'_id': 1}")};
-      ok = mongoc_collection_insert_bulk (coll, MONGOC_INSERT_NONE, (const bson_t **) docs, 1u, NULL, &error);
-      ASSERT_OR_PRINT (ok, error);
-      const bson_t *gle = mongoc_collection_get_last_error (coll);
-      ASSERT_MATCH (
-         gle,
-         BSON_STR (
-            {"nInserted" : 1, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "nUpserted" : 0, "writeErrors" : []}));
-   }
-
-   // Test mongoc_collection_insert:
-   {
-      mongoc_collection_drop (coll, NULL);
-
-      // Clear error:
-      ASSERT_OR_PRINT (mongoc_collection_command_simple (coll, tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error);
-      ASSERT (!mongoc_collection_get_last_error (coll));
-
-      ok = mongoc_collection_insert (coll, MONGOC_INSERT_NONE, tmp_bson ("{'_id': 1}"), NULL, &error);
-      ASSERT_OR_PRINT (ok, error);
-      const bson_t *gle = mongoc_collection_get_last_error (coll);
-      ASSERT_MATCH (gle, BSON_STR ({"insertedCount" : 1, "insertedId" : 1}));
-   }
-
-   mongoc_collection_destroy (coll);
-   mongoc_client_destroy (client);
-}
 
 void
 test_collection_install (TestSuite *suite)
@@ -5803,14 +4911,12 @@ test_collection_install (TestSuite *suit
    TestSuite_AddFull (
       suite, "/Collection/read_prefs_is_valid", test_read_prefs_is_valid, NULL, NULL, test_framework_skip_if_mongos);
    TestSuite_AddLive (suite, "/Collection/insert_many", test_insert_many);
-   TestSuite_AddLive (suite, "/Collection/insert_bulk_empty", test_insert_bulk_empty);
    TestSuite_AddLive (suite, "/Collection/copy", test_copy);
    TestSuite_AddLive (suite, "/Collection/insert", test_insert);
    TestSuite_AddLive (suite, "/Collection/insert/null_string", test_insert_null);
    TestSuite_AddFull (
       suite, "/Collection/insert/oversize", test_insert_oversize, NULL, NULL, test_framework_skip_if_slow_or_live);
    TestSuite_AddMockServerTest (suite, "/Collection/insert/keys", test_insert_command_keys);
-   TestSuite_AddLive (suite, "/Collection/save", test_save);
    TestSuite_AddLive (suite, "/Collection/insert/w0", test_insert_w0);
    TestSuite_AddLive (suite, "/Collection/update/w0", test_update_w0);
    TestSuite_AddLive (suite, "/Collection/remove/w0", test_remove_w0);
@@ -5839,17 +4945,6 @@ test_collection_install (TestSuite *suit
    TestSuite_AddLive (suite, "/Collection/remove/multi", test_remove_multi);
    TestSuite_AddFull (
       suite, "/Collection/remove/oversize", test_remove_oversize, NULL, NULL, test_framework_skip_if_slow_or_live);
-   TestSuite_AddLive (suite, "/Collection/count", test_count);
-   TestSuite_AddMockServerTest (suite, "/Collection/count_with_opts", test_count_with_opts);
-   TestSuite_AddMockServerTest (suite, "/Collection/count/read_pref", test_count_read_pref);
-   TestSuite_AddMockServerTest (suite, "/Collection/count/read_concern", test_count_read_concern);
-   TestSuite_AddMockServerTest (suite, "/Collection/count/collation", test_count_with_collation);
-   TestSuite_AddFull (suite,
-                      "/Collection/count/read_concern_live",
-                      test_count_read_concern_live,
-                      NULL,
-                      NULL,
-                      mongod_supports_majority_read_concern);
    TestSuite_AddLive (suite, "/Collection/drop", test_drop);
    TestSuite_AddLive (suite, "/Collection/aggregate", test_aggregate);
    TestSuite_AddMockServerTest (suite, "/Collection/aggregate/inherit/collection", test_aggregate_inherit_collection);
@@ -5873,13 +4968,7 @@ test_collection_install (TestSuite *suit
                       NULL,
                       NULL,
                       test_framework_skip_if_auth);
-   TestSuite_AddFull (suite, "/Collection/validate", test_validate, NULL, NULL, test_framework_skip_if_slow_or_live);
    TestSuite_AddLive (suite, "/Collection/rename", test_rename);
-   // The collStats command is deprecated in MongoDB 6.0 (maxWireVersion=17) and
-   // may be removed in a future major release.
-   TestSuite_AddFull (
-      suite, "/Collection/stats", test_stats, NULL, NULL, test_framework_skip_if_max_wire_version_more_than_17);
-   TestSuite_AddMockServerTest (suite, "/Collection/stats/read_pref", test_stats_read_pref);
    TestSuite_AddMockServerTest (suite, "/Collection/find_read_concern", test_find_read_concern);
    TestSuite_AddFull (
       suite, "/Collection/getmore_read_concern_live", test_getmore_read_concern_live, NULL, NULL, TestSuite_CheckLive);
@@ -5892,8 +4981,6 @@ test_collection_install (TestSuite *suit
    TestSuite_AddLive (suite, "/Collection/insert_many_validate", test_insert_many_validate);
    TestSuite_AddMockServerTest (suite, "/Collection/limit", test_find_limit);
    TestSuite_AddMockServerTest (suite, "/Collection/batch_size", test_find_batch_size);
-   TestSuite_AddFull (
-      suite, "/Collection/command_fully_qualified", test_command_fq, NULL, NULL, test_framework_skip_if_mongos);
    TestSuite_AddLive (suite, "/Collection/get_index_info", test_get_index_info);
    TestSuite_AddMockServerTest (suite, "/Collection/find_indexes/error", test_find_indexes_err);
    TestSuite_AddLive (suite, "/Collection/insert/duplicate_key", test_insert_duplicate_key);
@@ -5914,7 +5001,6 @@ test_collection_install (TestSuite *suit
    TestSuite_AddLive (suite, "/Collection/count_documents_live", test_count_documents_live);
    TestSuite_AddMockServerTest (suite, "/Collection/estimated_document_count", test_estimated_document_count);
    TestSuite_AddLive (suite, "/Collection/estimated_document_count_live", test_estimated_document_count_live);
-   TestSuite_AddLive (suite, "/Collection/insert_bulk_validate", test_insert_bulk_validate);
    TestSuite_AddMockServerTest (suite, "/Collection/aggregate_with_batch_size", test_aggregate_with_batch_size);
    TestSuite_AddFull (suite,
                       "/Collection/fam/no_error_on_retry",
@@ -5952,5 +5038,4 @@ test_collection_install (TestSuite *suit
                       // requires failpoint
                       test_framework_skip_if_no_failpoint);
    TestSuite_AddLive (suite, "/Collection/insert_one_reports_id", test_insert_one_reports_id);
-   TestSuite_AddLive (suite, "/Collection/get_last_error", test_get_last_error);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-command-logging-and-monitoring.c 2.0.2-1/src/libmongoc/tests/test-mongoc-command-logging-and-monitoring.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-command-logging-and-monitoring.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-command-logging-and-monitoring.c	2025-06-19 15:42:22.000000000 +0000
@@ -4,6 +4,7 @@
 #include "test-conveniences.h"
 #include <mongoc/mongoc-array-private.h>
 #include "TestSuite.h"
+#include <mlib/loop.h>
 
 static void
 stored_log_handler (const mongoc_structured_log_entry_t *entry, void *user_data)
@@ -291,8 +292,8 @@ prose_test_3 (void)
       if (test_length > max_expected_length) {
          expect_missing = true;
       } else {
-         for (int missing = 0; missing < sizeof expect_missing_lengths / sizeof expect_missing_lengths[0]; missing++) {
-            if (expect_missing_lengths[missing] == test_length) {
+         mlib_foreach_arr (const int, len, expect_missing_lengths) {
+            if (*len == test_length) {
                expect_missing = true;
                break;
             }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-command-monitoring.c 2.0.2-1/src/libmongoc/tests/test-mongoc-command-monitoring.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-command-monitoring.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-command-monitoring.c	2025-06-19 15:42:22.000000000 +0000
@@ -291,7 +291,8 @@ test_reset_callbacks (void)
    /* reset callbacks */
    mongoc_client_set_apm_callbacks (client, NULL, NULL);
    /* destroys cmd_reply */
-   cursor = mongoc_cursor_new_from_command_reply (client, &cmd_reply, sd->id);
+   cursor = mongoc_cursor_new_from_command_reply_with_opts (
+      client, &cmd_reply, tmp_bson ("{'serverId': %" PRIu32 "}", sd->id));
    ASSERT (mongoc_cursor_next (cursor, &b));
    ASSERT_CMPINT (incremented, ==, 1); /* same value as before */
 
@@ -648,7 +649,7 @@ _test_query_operation_id (bool pooled)
    }
 
    collection = mongoc_client_get_collection (client, "db", "collection");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_request (server);
@@ -821,49 +822,6 @@ set_cmd_test_callbacks (mongoc_client_t
 
 
 static void
-test_client_cmd (void)
-{
-   cmd_test_t test;
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   const bson_t *reply;
-
-   cmd_test_init (&test);
-   client = test_framework_new_default_client ();
-   set_cmd_test_callbacks (client, (void *) &test);
-   cursor =
-      mongoc_client_command (client, "admin", MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL);
-
-   ASSERT (mongoc_cursor_next (cursor, &reply));
-   ASSERT_CMPSTR (test.cmd_name, "ping");
-   ASSERT_MATCH (&test.cmd, "{'ping': 1}");
-   ASSERT_CMPSTR (test.db, "admin");
-   ASSERT_CMPINT (1, ==, test.started_calls);
-   ASSERT_CMPINT (1, ==, test.succeeded_calls);
-   ASSERT_CMPINT (0, ==, test.failed_calls);
-
-   cmd_test_cleanup (&test);
-   mongoc_cursor_destroy (cursor);
-
-   cmd_test_init (&test);
-   cursor =
-      mongoc_client_command (client, "admin", MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'foo': 1}"), NULL, NULL);
-
-   ASSERT (!mongoc_cursor_next (cursor, &reply));
-   ASSERT_CMPSTR (test.cmd_name, "foo");
-   ASSERT_MATCH (&test.cmd, "{'foo': 1}");
-   ASSERT_CMPSTR (test.db, "admin");
-   ASSERT_CMPINT (1, ==, test.started_calls);
-   ASSERT_CMPINT (0, ==, test.succeeded_calls);
-   ASSERT_CMPINT (1, ==, test.failed_calls);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
-   cmd_test_cleanup (&test);
-}
-
-
-static void
 test_client_cmd_simple (void)
 {
    cmd_test_t test;
@@ -955,38 +913,6 @@ test_client_cmd_op_ids (void)
 }
 
 
-static void
-test_killcursors_deprecated (void *unused)
-{
-   cmd_test_t test;
-   mongoc_client_t *client;
-   bool r;
-   bson_error_t error;
-
-   BSON_UNUSED (unused);
-
-   cmd_test_init (&test);
-   client = test_framework_new_default_client ();
-
-   /* connect */
-   r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error);
-
-   ASSERT_OR_PRINT (r, error);
-   set_cmd_test_callbacks (client, (void *) &test);
-
-   /* deprecated function without "db" or "collection", skips APM. This sends
-    * OP_KILL_CURSORS. */
-   mongoc_client_kill_cursor (client, 123);
-
-   ASSERT_CMPINT (0, ==, test.started_calls);
-   ASSERT_CMPINT (0, ==, test.succeeded_calls);
-   ASSERT_CMPINT (0, ==, test.failed_calls);
-
-   mongoc_client_destroy (client);
-   cmd_test_cleanup (&test);
-}
-
-
 typedef struct {
    int failed_calls;
    bson_t reply;
@@ -1053,7 +979,7 @@ test_command_failed_reply_mock (void)
    ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test));
 
    collection = mongoc_client_get_collection (client, "db", "collection");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_request (server);
@@ -1108,7 +1034,7 @@ test_command_failed_reply_hangup (void)
    ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test));
 
    collection = mongoc_client_get_collection (client, "db2", "collection");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_request (server);
@@ -1304,15 +1230,8 @@ test_command_monitoring_install (TestSui
       suite, "/command_monitoring/operation_id/query/single/cmd", test_query_operation_id_single_cmd);
    TestSuite_AddMockServerTest (
       suite, "/command_monitoring/operation_id/query/pooled/cmd", test_query_operation_id_pooled_cmd);
-   TestSuite_AddLive (suite, "/command_monitoring/client_cmd", test_client_cmd);
    TestSuite_AddLive (suite, "/command_monitoring/client_cmd_simple", test_client_cmd_simple);
    TestSuite_AddLive (suite, "/command_monitoring/client_cmd/op_ids", test_client_cmd_op_ids);
-   TestSuite_AddFull (suite,
-                      "/command_monitoring/killcursors_deprecated",
-                      test_killcursors_deprecated,
-                      NULL /* dtor */,
-                      NULL /* ctx */,
-                      test_framework_skip_if_no_legacy_opcodes);
    TestSuite_AddMockServerTest (suite, "/command_monitoring/failed_reply_mock", test_command_failed_reply_mock);
    TestSuite_AddMockServerTest (suite, "/command_monitoring/failed_reply_hangup", test_command_failed_reply_hangup);
    TestSuite_AddMockServerTest (suite, "/command_monitoring/service_id/loadbalanced", test_service_id_loadbalanced);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-connection-uri.c 2.0.2-1/src/libmongoc/tests/test-mongoc-connection-uri.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-connection-uri.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-connection-uri.c	2025-06-19 15:42:22.000000000 +0000
@@ -1,6 +1,13 @@
-#include <mongoc/mongoc.h>
+#include <mongoc/mongoc-uri.h>
+
+//
+
+#include <bson/bson.h>
+
 #include <mongoc/mongoc-util-private.h>
 
+#include <common-bson-dsl-private.h>
+
 #include "json-test.h"
 #include "test-libmongoc.h"
 #include <mongoc/mongoc-read-concern-private.h>
@@ -14,22 +21,24 @@ static void
 bson_contains_iter (const bson_t *haystack, bson_iter_t *needle)
 {
    bson_iter_t iter;
-   uint32_t bson_type;
 
    if (!bson_iter_next (needle)) {
       return;
    }
 
-   ASSERT (bson_iter_init_find_case (&iter, haystack, bson_iter_key (needle)));
+   const char *const key = bson_iter_key (needle);
+
+   ASSERT_WITH_MSG (bson_iter_init_find_case (&iter, haystack, key), "'%s' is not present", key);
+
+   const uint32_t bson_type = bson_iter_type (needle);
 
-   bson_type = bson_iter_type (needle);
    switch (bson_type) {
    case BSON_TYPE_ARRAY:
    case BSON_TYPE_DOCUMENT: {
       bson_t sub_bson;
       bson_iter_t sub_iter;
 
-      ASSERT (BSON_ITER_HOLDS_DOCUMENT (&iter));
+      ASSERT_WITH_MSG (BSON_ITER_HOLDS_DOCUMENT (&iter), "'%s' is not a document", key);
       bson_iter_bson (&iter, &sub_bson);
 
       bson_iter_recurse (needle, &sub_iter);
@@ -39,20 +48,20 @@ bson_contains_iter (const bson_t *haysta
       return;
    }
    case BSON_TYPE_BOOL:
-      ASSERT (bson_iter_as_bool (needle) == bson_iter_as_bool (&iter));
+      ASSERT_WITH_MSG (bson_iter_as_bool (needle) == bson_iter_as_bool (&iter), "'%s' is not the correct value", key);
       bson_contains_iter (haystack, needle);
       return;
    case BSON_TYPE_UTF8:
-      ASSERT (0 == strcmp (bson_iter_utf8 (needle, 0), bson_iter_utf8 (&iter, 0)));
+      ASSERT_CMPSTR (bson_iter_utf8 (needle, 0), bson_iter_utf8 (&iter, 0));
       bson_contains_iter (haystack, needle);
       return;
    case BSON_TYPE_DOUBLE:
-      ASSERT (bson_iter_double (needle) == bson_iter_double (&iter));
+      ASSERT_CMPDOUBLE (bson_iter_double (needle), ==, bson_iter_double (&iter));
       bson_contains_iter (haystack, needle);
       return;
    case BSON_TYPE_INT64:
    case BSON_TYPE_INT32:
-      ASSERT (bson_iter_as_int64 (needle) == bson_iter_as_int64 (&iter));
+      ASSERT_CMPINT64 (bson_iter_as_int64 (needle), ==, bson_iter_as_int64 (&iter));
       bson_contains_iter (haystack, needle);
       return;
    default:
@@ -62,27 +71,31 @@ bson_contains_iter (const bson_t *haysta
 }
 
 static void
-run_uri_test (const char *uri_string, bool valid, const bson_t *hosts, const bson_t *auth, const bson_t *options)
+run_uri_test (const char *uri_string,
+              bool valid,
+              const bson_t *hosts,
+              const bson_t *auth,
+              const bson_t *options,
+              const bson_t *credentials)
 {
-   mongoc_uri_t *uri;
-   bson_iter_t auth_iter;
-   const char *db;
    bson_error_t error;
 
-   uri = mongoc_uri_new_with_error (uri_string, &error);
+   mongoc_uri_t *const uri = mongoc_uri_new_with_error (uri_string, &error);
 
    /* BEGIN Exceptions to test suite */
 
    /* some spec tests assume we allow DB names like "auth.foo" */
-   if ((bson_iter_init_find (&auth_iter, auth, "db") || bson_iter_init_find (&auth_iter, auth, "source")) &&
-       BSON_ITER_HOLDS_UTF8 (&auth_iter)) {
-      db = bson_iter_utf8 (&auth_iter, NULL);
-      if (strchr (db, '.')) {
-         BSON_ASSERT (!uri);
-         ASSERT_ERROR_CONTAINS (
-            error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid database name in URI");
-         clear_captured_logs ();
-         return;
+   if (auth) {
+      bson_iter_t iter;
+      if ((bson_iter_init_find (&iter, auth, "db") || bson_iter_init_find (&iter, auth, "source")) &&
+          BSON_ITER_HOLDS_UTF8 (&iter)) {
+         if (strchr (bson_iter_utf8 (&iter, NULL), '.')) {
+            BSON_ASSERT (!uri);
+            ASSERT_ERROR_CONTAINS (
+               error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid database name in URI");
+            clear_captured_logs ();
+            return;
+         }
       }
    }
 
@@ -97,6 +110,18 @@ run_uri_test (const char *uri_string, bo
          MONGOC_WARNING ("Error parsing URI: '%s'", error.message);
          return;
       }
+
+      // CDRIVER-4128: only legacy boolean values are currently supported.
+      if (strstr (uri_string, "CANONICALIZE_HOST_NAME:none") || strstr (uri_string, "CANONICALIZE_HOST_NAME:forward")) {
+         return;
+      }
+
+      // CDRIVER-5580: commas in TOKEN_RESOURCE are interpreted as a key-value pair delimiter which produces an invalid
+      // mechanism property that is diagnosed as a client error instead of a warning.
+      if (strstr (uri_string, "TOKEN_RESOURCE:mongodb://host1%2Chost2")) {
+         MONGOC_WARNING ("percent-encoded commas in TOKEN_RESOURCE");
+         return;
+      }
    }
 
    if (uri) {
@@ -133,12 +158,11 @@ run_uri_test (const char *uri_string, bo
    if (valid) {
       ASSERT_OR_PRINT (uri, error);
    } else {
-      BSON_ASSERT (!uri);
+      ASSERT_WITH_MSG (!uri, "expected URI to be invalid: %s", uri_string);
       return;
    }
 
    if (!bson_empty0 (hosts)) {
-      const mongoc_host_list_t *hl;
       bson_iter_t iter;
       bson_iter_t host_iter;
 
@@ -154,7 +178,7 @@ run_uri_test (const char *uri_string, bo
             port = bson_iter_as_int64 (&host_iter);
          }
 
-         for (hl = mongoc_uri_get_hosts (uri); hl; hl = hl->next) {
+         for (const mongoc_host_list_t *hl = mongoc_uri_get_hosts (uri); hl; hl = hl->next) {
             if (!strcmp (host, hl->host) && port == hl->port) {
                ok = true;
                break;
@@ -162,77 +186,171 @@ run_uri_test (const char *uri_string, bo
          }
 
          if (!ok) {
-            fprintf (stderr, "Could not find '%s':%" PRId64 " in uri '%s'\n", host, port, mongoc_uri_get_string (uri));
-            BSON_ASSERT (0);
+            test_error ("Could not find '%s':%" PRId64 " in uri '%s'\n", host, port, mongoc_uri_get_string (uri));
          }
       }
    }
 
-   if (!bson_empty0 (auth)) {
-      const char *auth_source = mongoc_uri_get_auth_source (uri);
-      const char *username = mongoc_uri_get_username (uri);
-      const char *password = mongoc_uri_get_password (uri);
+   if (auth) {
       bson_iter_t iter;
 
       if (bson_iter_init_find (&iter, auth, "username") && BSON_ITER_HOLDS_UTF8 (&iter)) {
-         ASSERT_CMPSTR (username, bson_iter_utf8 (&iter, NULL));
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), bson_iter_utf8 (&iter, NULL));
       }
 
       if (bson_iter_init_find (&iter, auth, "password") && BSON_ITER_HOLDS_UTF8 (&iter)) {
-         ASSERT_CMPSTR (password, bson_iter_utf8 (&iter, NULL));
+         ASSERT_CMPSTR (mongoc_uri_get_password (uri), bson_iter_utf8 (&iter, NULL));
       }
 
       if ((bson_iter_init_find (&iter, auth, "db") || bson_iter_init_find (&iter, auth, "source")) &&
           BSON_ITER_HOLDS_UTF8 (&iter)) {
-         const char *auth_mech = mongoc_uri_get_auth_mechanism (uri);
-         if (auth_mech && 0 != strcmp (auth_mech, "MONGODB-AWS")) {
-            // Do not check expected auth source for MONGODB-AWS due to CDRIVER-5811.
-            ASSERT_CMPSTR (auth_source, bson_iter_utf8 (&iter, NULL));
-         }
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), bson_iter_utf8 (&iter, NULL));
       }
    }
 
    if (options) {
-      const mongoc_read_concern_t *rc;
-      bson_t uri_options = BSON_INITIALIZER;
-      bson_t test_options = BSON_INITIALIZER;
+      bson_t actual = BSON_INITIALIZER;
       bson_iter_t iter;
 
-      bson_concat (&uri_options, mongoc_uri_get_options (uri));
-      bson_concat (&uri_options, mongoc_uri_get_credentials (uri));
+      // "options" includes both URI options and credentials.
+      bson_concat (&actual, mongoc_uri_get_options (uri));
+      bson_concat (&actual, mongoc_uri_get_credentials (uri));
 
-      rc = mongoc_uri_get_read_concern (uri);
+      const mongoc_read_concern_t *const rc = mongoc_uri_get_read_concern (uri);
       if (!mongoc_read_concern_is_default (rc)) {
-         BSON_APPEND_UTF8 (&uri_options, "readconcernlevel", mongoc_read_concern_get_level (rc));
+         BSON_APPEND_UTF8 (&actual, "readconcernlevel", mongoc_read_concern_get_level (rc));
       }
 
+      bson_t expected = BSON_INITIALIZER;
       bson_copy_to_excluding_noinit (options,
-                                     &test_options,
-                                     "username", /* these 'auth' params may be included in 'options' */
+                                     &expected,
+
+                                     // These 'auth' params may be included in 'options'
+                                     "username",
                                      "password",
                                      "source",
-                                     "mechanism",            /* renamed to 'authmechanism' for consistency */
-                                     "mechanism_properties", /* renamed to 'authmechanismproperties' for
-                                                              * consistency */
+
+                                     // Credentials fields.
+                                     "authmechanism",
+                                     "authmechanismproperties",
+
+                                     // Rename for consistency.
+                                     "mechanism",            // -> "authmechanism"
+                                     "mechanism_properties", // -> "authmechanismproperties"
                                      NULL);
 
       if ((bson_iter_init_find (&iter, options, "mechanism") ||
            bson_iter_init_find (&iter, options, "authmechanism")) &&
           BSON_ITER_HOLDS_UTF8 (&iter)) {
-         BSON_APPEND_UTF8 (&test_options, "authmechanism", bson_iter_utf8 (&iter, NULL));
+         ASSERT (!bson_has_field (&expected, "authmechanism"));
+         ASSERT (BSON_APPEND_UTF8 (&expected, "authmechanism", bson_iter_utf8 (&iter, NULL)));
       }
 
       if ((bson_iter_init_find (&iter, options, "mechanism_properties") ||
            bson_iter_init_find (&iter, options, "authmechanismproperties")) &&
           BSON_ITER_HOLDS_DOCUMENT (&iter)) {
-         ASSERT (bson_append_iter (&test_options, "authmechanismproperties", -1, &iter));
+         ASSERT (!bson_has_field (&expected, "authmechanismproperties"));
+         ASSERT (BSON_APPEND_ITER (&expected, "authmechanismproperties", &iter));
       }
 
-      bson_iter_init (&iter, &test_options);
-      bson_contains_iter (&uri_options, &iter);
+      bson_iter_init (&iter, &expected);
+      bson_contains_iter (&actual, &iter);
 
-      bson_destroy (&test_options);
-      bson_destroy (&uri_options);
+      bson_destroy (&expected);
+      bson_destroy (&actual);
+   }
+
+   if (credentials) {
+      bson_iter_t iter;
+
+      bson_t expected = BSON_INITIALIZER;
+
+      // Rename keys for consistency across tests:
+      //  - "mechanism" -> "authmechanism"
+      //  - "mechanism_properties" -> "authmechanismproperties"
+      {
+         bson_copy_to_excluding_noinit (credentials,
+                                        &expected,
+
+                                        // Credentials fields.
+                                        "authmechanism",
+                                        "authmechanismproperties",
+
+                                        // Rename for consistency.
+                                        "mechanism",            // -> "authmechanism"
+                                        "mechanism_properties", // -> "authmechanismproperties"
+                                        NULL);
+
+         if ((bson_iter_init_find (&iter, credentials, "mechanism") ||
+              bson_iter_init_find (&iter, credentials, "authmechanism")) &&
+             BSON_ITER_HOLDS_UTF8 (&iter)) {
+            ASSERT (!bson_has_field (&expected, "authmechanism"));
+            ASSERT (BSON_APPEND_UTF8 (&expected, "authmechanism", bson_iter_utf8 (&iter, NULL)));
+         }
+
+         if ((bson_iter_init_find (&iter, credentials, "mechanism_properties") ||
+              bson_iter_init_find (&iter, credentials, "authmechanismproperties")) &&
+             BSON_ITER_HOLDS_DOCUMENT (&iter)) {
+            ASSERT (!bson_has_field (&expected, "authmechanismproperties"));
+            ASSERT (BSON_APPEND_ITER (&expected, "authmechanismproperties", &iter));
+         }
+      }
+
+      bsonVisitEach (
+         expected,
+         case (when (iKeyWithType ("username", utf8),
+                     do ({ ASSERT_CMPSTR (mongoc_uri_get_username (uri), bsonAs (cstr)); })),
+               when (iKeyWithType ("password", utf8),
+                     do ({ ASSERT_CMPSTR (mongoc_uri_get_password (uri), bsonAs (cstr)); })),
+               when (iKeyWithType ("source", utf8),
+                     do ({ ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), bsonAs (cstr)); })),
+               when (iKeyWithType ("authmechanism", utf8),
+                     do ({ ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), bsonAs (cstr)); })),
+               when (iKeyWithType ("authmechanismproperties", doc), do ({
+                        bson_t expected_props = BSON_INITIALIZER;
+                        ASSERT_OR_PRINT (_mongoc_iter_document_as_bson (&bsonVisitIter, &expected_props, &error),
+                                         error);
+
+                        // CDRIVER-4128: CANONICALIZE_HOST_NAME is UTF-8 even when "false" or "true".
+                        {
+                           bson_t updated = BSON_INITIALIZER;
+                           bson_copy_to_excluding_noinit (&expected_props, &updated, "CANONICALIZE_HOST_NAME", NULL);
+                           if (bson_iter_init_find_case (&iter, &expected_props, "CANONICALIZE_HOST_NAME")) {
+                              if (BSON_ITER_HOLDS_BOOL (&iter)) {
+                                 BSON_APPEND_UTF8 (
+                                    &updated, "CANONICALIZE_HOST_NAME", bson_iter_bool (&iter) ? "true" : "false");
+                              } else {
+                                 BSON_APPEND_VALUE (&updated, "CANONICALIZE_HOST_NAME", bson_iter_value (&iter));
+                              }
+                           }
+                           bson_destroy (&expected_props);
+                           expected_props = updated; // Ownership transfer.
+                        }
+
+                        bson_t actual;
+                        ASSERT_WITH_MSG (mongoc_uri_get_mechanism_properties (uri, &actual),
+                                         "expected authmechanismproperties to be provided");
+
+                        bson_iter_init (&iter, &expected_props);
+                        bson_contains_iter (&actual, &iter);
+
+                        bson_destroy (&expected_props);
+                        bson_destroy (&actual);
+                     })),
+               // Connection String spec: if a test case includes a null value for one of these keys (e.g. auth: ~,
+               // port: ~), no assertion is necessary.
+               when (iKeyWithType ("username", null), nop),
+               when (iKeyWithType ("password", null), nop),
+               when (iKeyWithType ("source", null), nop),
+               when (iKeyWithType ("authmechanism", null), nop),
+               when (iKeyWithType ("authmechanismproperties", null), nop),
+               else (do ({
+                  test_error ("unexpected credentials field '%s' with type '%s'",
+                              bson_iter_key (&bsonVisitIter),
+                              _mongoc_bson_type_to_str (bson_iter_type (&bsonVisitIter)));
+               }))));
+
+      bson_destroy (&expected);
    }
 
    if (uri) {
@@ -240,9 +358,35 @@ run_uri_test (const char *uri_string, bo
    }
 }
 
+static bson_t *
+bson_lookup_doc_null_ok (const bson_t *b, const char *key)
+{
+   bson_iter_t iter;
+
+   if (!bson_iter_init_find (&iter, b, key)) {
+      return NULL;
+   }
+
+   if (BSON_ITER_HOLDS_NULL (&iter)) {
+      return NULL;
+   }
+
+   bson_t *const ret = bson_new ();
+   {
+      bson_t doc;
+      bson_iter_bson (&iter, &doc);
+      bson_concat (ret, &doc);
+   }
+   return ret;
+}
+
 static void
 test_connection_uri_cb (void *scenario_vp)
 {
+   BSON_ASSERT_PARAM (scenario_vp);
+
+   const bson_t *const scenario = scenario_vp;
+
    static const test_skip_t skips[] = {
       {.description = "Valid connection pool options are parsed correctly",
        .reason = "libmongoc does not support maxIdleTimeMS"},
@@ -275,37 +419,24 @@ test_connection_uri_cb (void *scenario_v
       {.description = "replicaset, host and non-default port present",
        .reason = "libmongoc does not support proxies (CDRIVER-4187)"},
       {.description = "all options present", .reason = "libmongoc does not support proxies (CDRIVER-4187)"},
-      {.description = "must raise an error when the hostname canonicalization is invalid",
-       .reason = "libmongoc does not-yet support non-boolean values for CANONICALIZE_HOST_NAME (CDRIVER-4128)"},
-      {.description = "must raise an error when the authSource is empty",
-       .reason = "libmongoc does not-yet error on empty authSource (CDRIVER-3517)"},
-      {.description = "must raise an error when the authSource is empty without credentials",
-       .reason = "libmongoc does not-yet error on empty authSource (CDRIVER-3517)"},
-      {.description = "should throw an exception if username and no password (MONGODB-AWS)",
-       .reason = "libmongoc does not-yet error with username and no password for MONGODB-AWS (CDRIVER-5811)"},
       {.description = "(MONGODB-OIDC)",
        .reason = "libmongoc does not-yet implement MONGODB-OIDC (CDRIVER-4489)",
        .check_substring = true},
       {.description = "Colon in a key value pair",
        .reason = "libmongoc does not-yet implement MONGODB-OIDC (CDRIVER-4489)",
        .check_substring = true},
+      {.description = "Valid connection pool options are parsed correctly",
+       .reason = "libmongoc does not support minPoolSize (CDRIVER-2390)"},
+      {.description = "minPoolSize=0 does not error",
+       .reason = "libmongoc does not support minPoolSize (CDRIVER-2390)"},
       {.description = NULL},
    };
 
    bson_iter_t iter;
-   bson_iter_t descendent;
    bson_iter_t tests_iter;
-   bson_iter_t warning_iter;
-   bson_t hosts;
-   bson_t auth;
-   bson_t options;
-   bool valid;
-
-   BSON_ASSERT_PARAM (scenario_vp);
-   const bson_t *const scenario = scenario_vp;
 
-   BSON_ASSERT (bson_iter_init_find (&iter, scenario, "tests"));
-   BSON_ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
+   ASSERT (bson_iter_init_find (&iter, scenario, "tests"));
+   ASSERT (BSON_ITER_HOLDS_ARRAY (&iter));
    ASSERT (bson_iter_recurse (&iter, &tests_iter));
 
    while (bson_iter_next (&tests_iter)) {
@@ -324,29 +455,19 @@ test_connection_uri_cb (void *scenario_v
          fflush (stdout);
       }
 
-      /* newer spec test replaces both "auth" and "options" with "credential"
-       */
-      if (bson_has_field (&test_case, "credential")) {
-         bson_lookup_doc_null_ok (&test_case, "credential", &auth);
-         bson_lookup_doc_null_ok (&test_case, "credential", &options);
-         bson_init (&hosts);
-      } else if (bson_has_field (&test_case, "auth")) {
-         bson_lookup_doc_null_ok (&test_case, "auth", &auth);
-         bson_lookup_doc_null_ok (&test_case, "options", &options);
-         bson_lookup_doc_null_ok (&test_case, "hosts", &hosts);
-      } else {
-         /* These are expected to be initialized */
-         bson_init (&hosts);
-         bson_init (&auth);
-         bson_init (&options);
-      }
+      bson_t *const hosts = bson_lookup_doc_null_ok (&test_case, "hosts");
+      bson_t *const auth = bson_lookup_doc_null_ok (&test_case, "auth");
+      bson_t *const options = bson_lookup_doc_null_ok (&test_case, "options");
+      bson_t *const credentials = bson_lookup_doc_null_ok (&test_case, "credential");
 
-      valid = _mongoc_lookup_bool (&test_case, "valid", true);
+      const bool valid = _mongoc_lookup_bool (&test_case, "valid", true);
       capture_logs (true);
-      run_uri_test (uri_string, valid, &hosts, &auth, &options);
+      run_uri_test (uri_string, valid, hosts, auth, options, credentials);
 
+      bson_iter_t warning_iter;
       bson_iter_init (&warning_iter, &test_case);
 
+      bson_iter_t descendent;
       if (bson_iter_find_descendant (&warning_iter, "warning", &descendent) && BSON_ITER_HOLDS_BOOL (&descendent)) {
          if (bson_iter_as_bool (&descendent)) {
             ASSERT_CAPTURED_LOG ("mongoc_uri", MONGOC_LOG_LEVEL_WARNING, "");
@@ -355,9 +476,10 @@ test_connection_uri_cb (void *scenario_v
          }
       }
 
-      bson_destroy (&hosts);
-      bson_destroy (&auth);
-      bson_destroy (&options);
+      bson_destroy (hosts);
+      bson_destroy (auth);
+      bson_destroy (options);
+      bson_destroy (credentials);
    }
 }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-counters.c 2.0.2-1/src/libmongoc/tests/test-mongoc-counters.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-counters.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-counters.c	2025-06-19 15:42:22.000000000 +0000
@@ -21,7 +21,7 @@
 #include "test-libmongoc.h"
 #include "TestSuite.h"
 #include "mock_server/future-functions.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-atomic-private.h>
 
 /* test statistics counters excluding OP_INSERT, OP_UPDATE, and OP_DELETE since
@@ -778,30 +778,6 @@ test_counters_rpc_op_egress_cluster_lega
       future_destroy (ping);
    }
 
-   // Trigger: mongoc_cluster_legacy_rpc_sendv_to_server
-   mongoc_client_kill_cursor (client, 123);
-
-   {
-      request_t *const request = mock_server_receives_kill_cursors (server, 123);
-
-      ASSERT_WITH_MSG (request->opcode == MONGOC_OPCODE_KILL_CURSORS,
-                       "expected OP_KILL_CURSORS request, but received: %s",
-                       request->as_str);
-
-      // OP_KILL_CURSORS 1:
-      //  - by _mongoc_rpc_op_egress_inc
-      //  - by mongoc_cluster_legacy_rpc_sendv_to_server
-      //  - by _mongoc_client_op_killcursors
-      //  - by _mongoc_client_kill_cursor
-      //  - by mongoc_client_kill_cursor
-      expected.op_egress_killcursors += 1;
-      expected.op_egress_total += 1;
-      ASSERT_RPC_OP_EGRESS_COUNTERS_CURRENT (expected);
-
-      // OP_KILL_CURSORS does not require a response.
-      request_destroy (request);
-   }
-
    // Ensure no extra requests.
    {
       int responses = 0;
@@ -1264,7 +1240,7 @@ _test_counters_auth (bool with_op_msg, b
    // Number of messages sent by background threads depend on the number of
    // members in the replica set.
    const size_t member_count_zu = test_framework_replset_member_count ();
-   ASSERT (mcommon_in_range_unsigned (int32_t, member_count_zu));
+   ASSERT (mlib_in_range (int32_t, member_count_zu));
    const int32_t member_count = (int32_t) member_count_zu;
 
    // MongoDB Handshake Spec: Since MongoDB server 4.4, the initial handshake
@@ -1474,6 +1450,7 @@ test_counters_auth_pooled_op_msg (void *
 void
 test_counters_install (TestSuite *suite)
 {
+   BSON_UNUSED (suite);
 #ifdef MONGOC_ENABLE_SHM_COUNTERS
    TestSuite_AddFull (suite,
                       "/counters/op_msg",
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-crud.c 2.0.2-1/src/libmongoc/tests/test-mongoc-crud.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-crud.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-crud.c	2025-06-19 15:42:22.000000000 +0000
@@ -4,7 +4,8 @@
 #include "json-test-operations.h"
 #include "test-libmongoc.h"
 #include <mongoc/mongoc-bulkwrite.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/loop.h>
 
 static bool
 crud_test_operation_cb (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation)
@@ -301,7 +302,7 @@ prose_test_3 (void *ctx)
 static char *
 repeat_char (char c, int32_t count)
 {
-   ASSERT (mcommon_in_range_size_t_signed (count));
+   ASSERT (mlib_in_range (size_t, count));
    char *str = bson_malloc (count + 1);
    memset (str, c, count);
    str[count] = '\0';
@@ -546,7 +547,7 @@ prose_test_6 (void *ctx)
       // Count write errors.
       {
          const bson_t *writeErrors = mongoc_bulkwriteexception_writeerrors (ret.exc);
-         ASSERT (mcommon_in_range_uint32_t_signed (maxWriteBatchSize + 1));
+         ASSERT (mlib_in_range (uint32_t, maxWriteBatchSize + 1));
          ASSERT_CMPUINT32 (bson_count_keys (writeErrors), ==, (uint32_t) maxWriteBatchSize + 1);
       }
 
@@ -1009,7 +1010,8 @@ prose_test_11_fixture_new (void)
          bson_free (large_str);
       }
 
-      for (size_t i = 0; i < tf->numModels; i++) {
+      mlib_foreach_irange (i, tf->numModels) {
+         (void) i;
          ok = mongoc_bulkwrite_append_insertone (tf->bw, "db.coll", doc, NULL, &error);
          ASSERT_OR_PRINT (ok, error);
       }
@@ -1017,7 +1019,6 @@ prose_test_11_fixture_new (void)
       bson_destroy (doc);
    }
 
-
    if (remainderBytes >= 217) {
       // Create a document { 'a': 'b'.repeat(remainderBytes - 57) }
       bson_t *doc;
@@ -1080,7 +1081,7 @@ prose_test_11 (void *ctx)
          mongoc_bulkwritereturn_t bwr = mongoc_bulkwrite_execute (tf->bw, NULL /* opts */);
          ASSERT (bwr.res);
          ASSERT_NO_BULKWRITEEXCEPTION (bwr);
-         ASSERT (mcommon_in_range_int64_t_unsigned (tf->numModels));
+         ASSERT (mlib_in_range (int64_t, tf->numModels));
          ASSERT_CMPINT64 (mongoc_bulkwriteresult_insertedcount (bwr.res), ==, (int64_t) tf->numModels + 1);
          mongoc_bulkwriteresult_destroy (bwr.res);
          mongoc_bulkwriteexception_destroy (bwr.exc);
@@ -1092,7 +1093,7 @@ prose_test_11 (void *ctx)
       bson_t *first = _mongoc_array_index (&tf->captured, bson_t *, 0);
       {
          bson_t *ops = bson_lookup_bson (first, "ops");
-         ASSERT (mcommon_in_range_uint32_t_unsigned (tf->numModels));
+         ASSERT (mlib_in_range (uint32_t, tf->numModels));
          ASSERT_CMPUINT32 (bson_count_keys (ops), ==, (uint32_t) tf->numModels + 1);
          bson_destroy (ops);
 
@@ -1131,7 +1132,7 @@ prose_test_11 (void *ctx)
          mongoc_bulkwritereturn_t bwr = mongoc_bulkwrite_execute (tf->bw, NULL /* opts */);
          ASSERT (bwr.res);
          ASSERT_NO_BULKWRITEEXCEPTION (bwr);
-         ASSERT (mcommon_in_range_int64_t_unsigned (tf->numModels));
+         ASSERT (mlib_in_range (int64_t, tf->numModels));
          ASSERT_CMPINT64 (mongoc_bulkwriteresult_insertedcount (bwr.res), ==, (int64_t) tf->numModels + 1);
          mongoc_bulkwriteresult_destroy (bwr.res);
          mongoc_bulkwriteexception_destroy (bwr.exc);
@@ -1143,7 +1144,7 @@ prose_test_11 (void *ctx)
       bson_t *first = _mongoc_array_index (&tf->captured, bson_t *, 0);
       {
          bson_t *ops = bson_lookup_bson (first, "ops");
-         ASSERT (mcommon_in_range_uint32_t_unsigned (tf->numModels));
+         ASSERT (mlib_in_range (uint32_t, tf->numModels));
          ASSERT_CMPUINT32 (bson_count_keys (ops), ==, (uint32_t) tf->numModels);
          bson_destroy (ops);
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-cursor.c 2.0.2-1/src/libmongoc/tests/test-mongoc-cursor.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-cursor.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-cursor.c	2025-06-19 15:42:22.000000000 +0000
@@ -12,7 +12,7 @@
 #include <mongoc/mongoc-write-concern-private.h>
 #include "test-conveniences.h"
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 typedef mongoc_cursor_t *(*make_cursor_fn) (mongoc_collection_t *);
@@ -40,9 +40,6 @@ typedef struct {
    } while (0)
 
 static mongoc_cursor_t *
-_make_cmd_deprecated_cursor (mongoc_collection_t *coll);
-
-static mongoc_cursor_t *
 _make_array_cursor (mongoc_collection_t *coll);
 
 /* test that the host a cursor returns belongs to a server it connected to. */
@@ -139,7 +136,6 @@ _test_common_clone_w_concerns (void *ctx
    mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL);
    write_concern = mongoc_write_concern_new ();
    ASSERT (write_concern);
-   mongoc_write_concern_set_fsync (write_concern, true);
    mongoc_write_concern_set_journal (write_concern, true);
    mongoc_write_concern_set_wmajority (write_concern, 1000);
    cursor->write_concern = write_concern;
@@ -160,7 +156,7 @@ _test_common_clone_w_concerns (void *ctx
    ASSERT_MATCH (_mongoc_read_concern_get_bson (cloned->read_concern), "{'level': 'local'}");
    bson = _mongoc_write_concern_get_bson (cloned->write_concern);
    ASSERT (bson);
-   ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter));
+   ASSERT (!bson_iter_init_find (&iter, bson, "fsync")); // Deprecated "fsync" removed in C driver 2.0.
    ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter));
    ASSERT (bson_iter_init_find (&iter, bson, "w") && BSON_ITER_HOLDS_UTF8 (&iter));
    ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), "majority");
@@ -291,7 +287,7 @@ _test_common_opts (void *ctx)
    ASSERT_CMPINT (mongoc_cursor_get_server_id (cursor), ==, sd->id);
 
    /* listDatabases and hello prohibits limit and batchSize */
-   if (ctor != _make_array_cursor && ctor != _make_cmd_deprecated_cursor) {
+   if (ctor != _make_array_cursor) {
       mongoc_cursor_set_batch_size (cursor, 1);
       ASSERT_CMPINT (mongoc_cursor_get_batch_size (cursor), ==, 1);
       BSON_ASSERT (mongoc_cursor_set_limit (cursor, 2));
@@ -304,7 +300,7 @@ _test_common_opts (void *ctx)
    ASSERT_OR_PRINT (mongoc_cursor_next (cursor, &doc), cursor->error);
    /* options should be unchanged. */
    ASSERT_CMPINT (mongoc_cursor_get_server_id (cursor), ==, sd->id);
-   if (ctor != _make_array_cursor && ctor != _make_cmd_deprecated_cursor) {
+   if (ctor != _make_array_cursor) {
       ASSERT_CMPINT (mongoc_cursor_get_batch_size (cursor), ==, 1);
       ASSERT_CMPINT ((int) mongoc_cursor_get_limit (cursor), ==, 2);
       /* limit cannot be set again. */
@@ -412,14 +408,6 @@ _make_cmd_cursor_from_agg (mongoc_collec
 
 
 static mongoc_cursor_t *
-_make_cmd_deprecated_cursor (mongoc_collection_t *coll)
-{
-   return mongoc_collection_command (
-      coll, MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL);
-}
-
-
-static mongoc_cursor_t *
 _make_array_cursor (mongoc_collection_t *coll)
 {
    return mongoc_client_find_databases_with_opts (coll->client, NULL);
@@ -441,13 +429,6 @@ _make_array_cursor (mongoc_collection_t
    } else                                                                                    \
       ((void) 0)
 
-#define TEST_CURSOR_CMD_DEPRECATED(prefix, fn)                                                          \
-   if (1) {                                                                                             \
-      make_cursor_helper_t *const helper = bson_malloc (sizeof (*helper));                              \
-      *helper = (make_cursor_helper_t){.ctor = _make_cmd_deprecated_cursor};                            \
-      TestSuite_AddFull (suite, prefix "/cmd_deprecated", fn, &bson_free, helper, TestSuite_CheckLive); \
-   } else                                                                                               \
-      ((void) 0)
 
 #define TEST_CURSOR_ARRAY(prefix, fn)                                                          \
    if (1) {                                                                                    \
@@ -466,14 +447,13 @@ _make_array_cursor (mongoc_collection_t
       ((void) 0)
 
 
-#define TEST_FOREACH_CURSOR(prefix, fn)        \
-   if (1) {                                    \
-      TEST_CURSOR_FIND (prefix, fn);           \
-      TEST_CURSOR_CMD (prefix, fn);            \
-      TEST_CURSOR_CMD_DEPRECATED (prefix, fn); \
-      TEST_CURSOR_ARRAY (prefix, fn);          \
-      TEST_CURSOR_AGG (prefix, fn);            \
-   } else                                      \
+#define TEST_FOREACH_CURSOR(prefix, fn) \
+   if (1) {                             \
+      TEST_CURSOR_FIND (prefix, fn);    \
+      TEST_CURSOR_CMD (prefix, fn);     \
+      TEST_CURSOR_ARRAY (prefix, fn);   \
+      TEST_CURSOR_AGG (prefix, fn);     \
+   } else                               \
       (void) 0
 
 
@@ -487,11 +467,9 @@ test_common_cursor_functions_install (Te
    TEST_FOREACH_CURSOR ("/Cursor/common/advancing_past_end", _test_common_advancing_past_end);
    /* an agg/cmd cursors do not support setting server id. test others. */
    TEST_CURSOR_FIND ("/Cursor/common/hint", _test_common_server_hint);
-   TEST_CURSOR_CMD_DEPRECATED ("/Cursor/common/hint", _test_common_server_hint);
    TEST_CURSOR_ARRAY ("/Cursor/common/hint", _test_common_server_hint);
    /* find, cmd_depr, and array cursors can have all options set. */
    TEST_CURSOR_FIND ("/Cursor/common/opts", _test_common_opts);
-   TEST_CURSOR_CMD_DEPRECATED ("/Cursor/common/opts", _test_common_opts);
    TEST_CURSOR_ARRAY ("/Cursor/common/opts", _test_common_opts);
    /* a command cursor created from find_indexes_with_opts is already primed. */
    TEST_CURSOR_CMD ("/Cursor/common/opts", _test_common_opts_after_prime);
@@ -529,7 +507,7 @@ test_limit (void)
 
    /* test positive and negative limit */
    for (i = 0; i < 2; i++) {
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
+      cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
       ASSERT_CMPINT64 ((int64_t) 0, ==, mongoc_cursor_get_limit (cursor));
       ASSERT (mongoc_cursor_set_limit (cursor, limits[i]));
       ASSERT_CMPINT64 (limits[i], ==, mongoc_cursor_get_limit (cursor));
@@ -654,14 +632,7 @@ test_kill_cursor_live (void)
    server_id = mongoc_bulk_operation_execute (bulk, NULL, &error);
    ASSERT_OR_PRINT (server_id > 0, error);
 
-   cursor = mongoc_collection_find (collection,
-                                    MONGOC_QUERY_NONE,
-                                    0,
-                                    0,
-                                    2, /* batch size 2 */
-                                    b,
-                                    NULL,
-                                    NULL);
+   cursor = mongoc_collection_find_with_opts (collection, b, tmp_bson ("{'batchSize': 2}"), NULL);
 
    r = mongoc_cursor_next (cursor, &doc);
    ASSERT (r);
@@ -742,7 +713,7 @@ _test_kill_cursors (bool pooled)
    collection = mongoc_client_get_collection (client, "db", "collection");
 
    prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, prefs);
+   cursor = mongoc_collection_find_with_opts (collection, q, NULL, prefs);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_rs_receives_request (rs);
@@ -824,78 +795,6 @@ test_kill_cursors_pooled (void)
 }
 
 
-/* Test explicit mongoc_client_kill_cursor. */
-static void
-_test_client_kill_cursor (bool has_primary)
-{
-   mock_rs_t *rs;
-   mongoc_client_t *client;
-   mongoc_read_prefs_t *read_prefs;
-   bson_error_t error;
-   future_t *future;
-   request_t *request;
-
-   rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN,
-                                 has_primary, /* maybe a primary*/
-                                 1,           /* definitely a secondary */
-                                 0);          /* no arbiter */
-   mock_rs_run (rs);
-   client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL);
-   read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
-
-   /* make client open a connection - it won't open one to kill a cursor */
-   future = future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), read_prefs, NULL, &error);
-
-   request = mock_rs_receives_msg (rs,
-                                   MONGOC_MSG_NONE,
-                                   tmp_bson ("{'$db': 'admin',"
-                                             " '$readPreference': {'mode': 'secondary'},"
-                                             " 'foo': 1}"));
-
-   reply_to_request_simple (request, "{'ok': 1}");
-   ASSERT_OR_PRINT (future_get_bool (future), error);
-   request_destroy (request);
-   future_destroy (future);
-
-   future = future_client_kill_cursor (client, 123);
-   mock_rs_set_request_timeout_msec (rs, 100);
-
-   /* we don't pass namespace so client always sends legacy OP_KILLCURSORS */
-   request = mock_rs_receives_kill_cursors (rs, 123);
-
-   if (has_primary) {
-      BSON_ASSERT (request);
-
-      /* weird but true. see mongoc_client_kill_cursor's documentation */
-      BSON_ASSERT (mock_rs_request_is_to_primary (rs, request));
-
-      request_destroy (request); /* server has no reply to OP_KILLCURSORS */
-   } else {
-      /* TODO: catch and check warning */
-      BSON_ASSERT (!request);
-   }
-
-   future_wait (future); /* no return value */
-   future_destroy (future);
-   mongoc_read_prefs_destroy (read_prefs);
-   mongoc_client_destroy (client);
-   mock_rs_destroy (rs);
-}
-
-static void
-test_client_kill_cursor_with_primary (void)
-{
-   _test_client_kill_cursor (true);
-}
-
-
-static void
-test_client_kill_cursor_without_primary (void)
-{
-   _test_client_kill_cursor (false);
-}
-
-
 static int
 count_docs (mongoc_cursor_t *cursor)
 {
@@ -1156,7 +1055,7 @@ test_cursor_int64_t_maxtimems (void)
    bson_append_bool (max_await_time_ms, "awaitData", 9, true);
    bson_append_int64 (
       max_await_time_ms, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, MONGOC_CURSOR_MAX_AWAIT_TIME_MS_LEN, ms_int64);
-   ASSERT (mcommon_in_range_int32_t_unsigned (server_id));
+   ASSERT (mlib_in_range (int32_t, server_id));
    BSON_APPEND_INT32 (max_await_time_ms, "serverId", (uint32_t) server_id);
 
    cursor = mongoc_cursor_new_from_command_reply_with_opts (client,
@@ -1253,7 +1152,10 @@ test_cursor_new_invalid_filter (void)
 
    ASSERT (cursor);
    ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Invalid filter: empty key");
+   ASSERT_ERROR_CONTAINS (error,
+                          MONGOC_ERROR_CURSOR,
+                          MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                          "Invalid filter: Element key cannot be an empty string");
 
    ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc));
    ASSERT (bson_empty (error_doc));
@@ -1280,7 +1182,10 @@ test_cursor_new_invalid_opts (void)
 
    ASSERT (cursor);
    ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Invalid opts: empty key");
+   ASSERT_ERROR_CONTAINS (error,
+                          MONGOC_ERROR_CURSOR,
+                          MONGOC_ERROR_CURSOR_INVALID_CURSOR,
+                          "Invalid opts: Element key cannot be an empty string");
 
    ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc));
    ASSERT (bson_empty (error_doc));
@@ -1349,7 +1254,7 @@ test_cursor_hint_errors (void)
 
    client = test_framework_new_default_client ();
    collection = mongoc_client_get_collection (client, "db", "collection");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL);
 
    capture_logs (true);
    ASSERT (!mongoc_cursor_set_server_id (cursor, 0));
@@ -1421,7 +1326,7 @@ _test_cursor_hint (bool pooled, bool use
 
    collection = mongoc_client_get_collection (client, "test", "test");
 
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, q, NULL, NULL);
    ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_server_id (cursor));
 
    if (use_primary) {
@@ -1534,7 +1439,7 @@ test_cursor_hint_mongos (void)
 
    for (i = 0; i < sizeof (modes) / sizeof (mongoc_read_mode_t); i++) {
       prefs = mongoc_read_prefs_new (modes[i]);
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs);
+      cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), NULL, NULL);
 
       ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_server_id (cursor));
       ASSERT (mongoc_cursor_set_server_id (cursor, 1));
@@ -1585,7 +1490,7 @@ test_cursor_hint_mongos_cmd (void)
 
    for (i = 0; i < sizeof (modes) / sizeof (mongoc_read_mode_t); i++) {
       prefs = mongoc_read_prefs_new (modes[i]);
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs);
+      cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), NULL, NULL);
 
       ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_server_id (cursor));
       ASSERT (mongoc_cursor_set_server_id (cursor, 1));
@@ -1639,7 +1544,7 @@ _test_cursor_hint_no_warmup (bool pooled
    }
 
    collection = get_test_collection (client, "test_cursor_hint_no_warmup");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, q, NULL, NULL);
 
    /* no chance for topology scan, no server selection */
    ASSERT (mongoc_cursor_set_server_id (cursor, 1));
@@ -1701,23 +1606,6 @@ test_tailable_alive (void)
 
    ASSERT_OR_PRINT (r, error);
 
-   /* test mongoc_collection_find and mongoc_collection_find_with_opts */
-   cursor = mongoc_collection_find (
-      collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson (NULL), NULL, NULL);
-
-   ASSERT (mongoc_cursor_more (cursor));
-   ASSERT (mongoc_cursor_next (cursor, &doc));
-
-   /* still alive */
-   ASSERT (mongoc_cursor_more (cursor));
-
-   /* no next document, but still alive and could return more in the future
-    * see CDRIVER-1530 */
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_more (cursor));
-
-   mongoc_cursor_destroy (cursor);
-
    cursor = mongoc_collection_find_with_opts (
       collection, tmp_bson (NULL), tmp_bson ("{'tailable': true, 'awaitData': true}"), NULL);
 
@@ -1859,7 +1747,7 @@ _test_cursor_n_return_find_cmd (mongoc_c
 
 
 static void
-_test_cursor_n_return (bool find_with_opts)
+_test_cursor_n_return (void)
 {
    cursor_n_return_test tests[] = {{
                                       0,         /* skip              */
@@ -1922,36 +1810,25 @@ _test_cursor_n_return (bool find_with_op
    for (i = 0; i < sizeof (tests) / sizeof (cursor_n_return_test); i++) {
       test = &tests[i];
 
-      if (find_with_opts) {
-         bson_reinit (&opts);
+      bson_reinit (&opts);
+
+      if (test->skip) {
+         BSON_APPEND_INT64 (&opts, "skip", test->skip);
+      }
 
-         if (test->skip) {
-            BSON_APPEND_INT64 (&opts, "skip", test->skip);
-         }
-
-         if (test->limit > 0) {
-            BSON_APPEND_INT64 (&opts, "limit", test->limit);
-         } else if (test->limit < 0) {
-            BSON_APPEND_INT64 (&opts, "limit", -test->limit);
-            BSON_APPEND_BOOL (&opts, "singleBatch", true);
-         }
-
-         if (test->batch_size) {
-            BSON_APPEND_INT64 (&opts, "batchSize", test->batch_size);
-         }
+      if (test->limit > 0) {
+         BSON_APPEND_INT64 (&opts, "limit", test->limit);
+      } else if (test->limit < 0) {
+         BSON_APPEND_INT64 (&opts, "limit", -test->limit);
+         BSON_APPEND_BOOL (&opts, "singleBatch", true);
+      }
 
-         cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), &opts, NULL);
-      } else {
-         cursor = mongoc_collection_find (collection,
-                                          MONGOC_QUERY_NONE,
-                                          (uint32_t) test->skip,
-                                          (uint32_t) test->limit,
-                                          (uint32_t) test->batch_size,
-                                          tmp_bson (NULL),
-                                          NULL,
-                                          NULL);
+      if (test->batch_size) {
+         BSON_APPEND_INT64 (&opts, "batchSize", test->batch_size);
       }
 
+      cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), &opts, NULL);
+
       _test_cursor_n_return_find_cmd (cursor, server, test);
 
       mongoc_cursor_destroy (cursor);
@@ -1965,16 +1842,9 @@ _test_cursor_n_return (bool find_with_op
 
 
 static void
-test_n_return_find_cmd (void)
-{
-   _test_cursor_n_return (false);
-}
-
-
-static void
 test_n_return_find_cmd_with_opts (void)
 {
-   _test_cursor_n_return (true);
+   _test_cursor_n_return ();
 }
 
 
@@ -2129,40 +1999,6 @@ test_error_document_query (void)
    mongoc_client_destroy (client);
 }
 
-
-static void
-test_error_document_command (void)
-{
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   bson_error_t error;
-   const bson_t *doc;
-   const bson_t *error_doc;
-
-   client = test_framework_new_default_client ();
-   mongoc_client_set_error_api (client, 2);
-   cursor = mongoc_client_command (client,
-                                   "test",
-                                   MONGOC_QUERY_NONE,
-                                   0,
-                                   0,
-                                   0,
-                                   tmp_bson ("{'foo': 1}"), /* no such cmd */
-                                   NULL,
-                                   NULL);
-
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc));
-   ASSERT_CMPUINT32 (error.domain, ==, MONGOC_ERROR_SERVER);
-   ASSERT_CONTAINS (error.message, "no such");
-
-   ASSERT_CMPINT32 (bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code);
-
-   mongoc_cursor_destroy (cursor);
-   mongoc_client_destroy (client);
-}
-
-
 static void
 test_error_document_getmore (void)
 {
@@ -2212,8 +2048,7 @@ test_error_document_getmore (void)
 }
 
 /* test that an error during constructing a find cursor causes the cursor to
- * be marked as failed, so mongoc_cursor_is_alive and mongoc_cursor_more return
- * false */
+ * be marked as failed, mongoc_cursor_more returns false */
 static void
 test_find_error_is_alive (void)
 {
@@ -2224,12 +2059,9 @@ test_find_error_is_alive (void)
    const bson_t *bson;
    client = test_framework_new_default_client ();
    coll = mongoc_client_get_collection (client, "test", "test");
-   cursor = mongoc_collection_find (
-      coll, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'$query': {}, 'non_dollar': {}}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), tmp_bson ("{'$bad': 1}"), NULL);
    BSON_ASSERT (mongoc_cursor_error (cursor, &err));
-   ASSERT_ERROR_CONTAINS (
-      err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot mix $query with non-dollar field");
-   BSON_ASSERT (!mongoc_cursor_is_alive (cursor));
+   ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot use $-modifiers");
    BSON_ASSERT (!mongoc_cursor_more (cursor));
    BSON_ASSERT (!mongoc_cursor_next (cursor, &bson));
    mongoc_cursor_destroy (cursor);
@@ -2584,9 +2416,6 @@ test_cursor_install (TestSuite *suite)
                       test_kill_cursor_live);
    TestSuite_AddMockServerTest (suite, "/Cursor/kill/single", test_kill_cursors_single);
    TestSuite_AddMockServerTest (suite, "/Cursor/kill/pooled", test_kill_cursors_pooled);
-   TestSuite_AddMockServerTest (suite, "/Cursor/client_kill_cursor/with_primary", test_client_kill_cursor_with_primary);
-   TestSuite_AddMockServerTest (
-      suite, "/Cursor/client_kill_cursor/without_primary", test_client_kill_cursor_without_primary);
    TestSuite_AddLive (suite, "/Cursor/empty_collection", test_cursor_empty_collection);
    TestSuite_AddLive (suite, "/Cursor/new_from_agg", test_cursor_new_from_aggregate);
    TestSuite_AddLive (suite, "/Cursor/new_from_agg_no_initial", test_cursor_new_from_aggregate_no_initial);
@@ -2610,13 +2439,11 @@ test_cursor_install (TestSuite *suite)
    TestSuite_AddLive (suite, "/Cursor/hint/no_warmup/single", test_hint_no_warmup_single);
    TestSuite_AddLive (suite, "/Cursor/hint/no_warmup/pooled", test_hint_no_warmup_pooled);
    TestSuite_AddLive (suite, "/Cursor/tailable/alive", test_tailable_alive);
-   TestSuite_AddMockServerTest (suite, "/Cursor/n_return/find_cmd", test_n_return_find_cmd);
    TestSuite_AddMockServerTest (suite, "/Cursor/n_return/find_cmd/with_opts", test_n_return_find_cmd_with_opts);
    TestSuite_AddLive (suite, "/Cursor/empty_final_batch_live", test_empty_final_batch_live);
    TestSuite_AddMockServerTest (suite, "/Cursor/empty_final_batch", test_empty_final_batch);
    TestSuite_AddLive (suite, "/Cursor/error_document/query", test_error_document_query);
    TestSuite_AddLive (suite, "/Cursor/error_document/getmore", test_error_document_getmore);
-   TestSuite_AddLive (suite, "/Cursor/error_document/command", test_error_document_command);
    TestSuite_AddLive (suite, "/Cursor/find_error/is_alive", test_find_error_is_alive);
    TestSuite_AddLive (suite, "/Cursor/batchsize_override_int32", test_cursor_batchsize_override_int32);
    TestSuite_AddLive (suite, "/Cursor/batchsize_override_int64", test_cursor_batchsize_override_int64);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-database.c 2.0.2-1/src/libmongoc/tests/test-mongoc-database.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-database.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-database.c	2025-06-19 15:42:22.000000000 +0000
@@ -297,62 +297,7 @@ test_has_collection (void)
 
 
 static void
-test_command (void)
-{
-   mongoc_database_t *database;
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   bson_error_t error;
-   const bson_t *doc;
-   bool r;
-   bson_t cmd = BSON_INITIALIZER;
-   bson_t reply;
-
-   client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
-
-   database = mongoc_client_get_database (client, "admin");
-
-   /*
-    * Test a known working command, "ping".
-    */
-   bson_append_int32 (&cmd, "ping", 4, 1);
-
-   cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL);
-   BSON_ASSERT (cursor);
-
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (r);
-   BSON_ASSERT (doc);
-
-   r = mongoc_cursor_next (cursor, &doc);
-   BSON_ASSERT (!r);
-   BSON_ASSERT (!doc);
-
-   mongoc_cursor_destroy (cursor);
-
-
-   /*
-    * Test a non-existing command to ensure we get the failure.
-    */
-   bson_reinit (&cmd);
-   bson_append_int32 (&cmd, "a_non_existing_command", -1, 1);
-
-   r = mongoc_database_command_simple (database, &cmd, NULL, &reply, &error);
-   BSON_ASSERT (!r);
-   BSON_ASSERT (error.domain == MONGOC_ERROR_QUERY);
-   BSON_ASSERT (error.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND);
-   BSON_ASSERT (strstr (error.message, "a_non_existing_command"));
-
-   bson_destroy (&reply);
-   mongoc_database_destroy (database);
-   mongoc_client_destroy (client);
-   bson_destroy (&cmd);
-}
-
-
-static void
-_test_db_command_read_prefs (bool simple, bool pooled)
+_test_db_command_read_prefs (bool pooled)
 {
    mock_server_t *server;
    mongoc_client_pool_t *pool = NULL;
@@ -363,8 +308,6 @@ _test_db_command_read_prefs (bool simple
    future_t *future;
    bson_error_t error;
    request_t *request;
-   mongoc_cursor_t *cursor;
-   const bson_t *reply;
 
    /* mock mongos: easiest way to test that read preference is configured */
    server = mock_mongos_new (WIRE_VERSION_MIN);
@@ -383,56 +326,28 @@ _test_db_command_read_prefs (bool simple
    mongoc_database_set_read_prefs (db, secondary_pref);
    cmd = tmp_bson ("{'foo': 1}");
 
-   if (simple) {
-      /* simple, without read preference */
-      future = future_database_command_simple (db, cmd, NULL, NULL, &error);
-
-      request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
-
-      reply_to_request_simple (request, "{'ok': 1}");
-      ASSERT_OR_PRINT (future_get_bool (future), error);
-      future_destroy (future);
-      request_destroy (request);
-
-      /* with read preference */
-      future = future_database_command_simple (db, cmd, secondary_pref, NULL, &error);
-
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'foo': 1,"
-                                                    " '$readPreference': {'mode': 'secondary'}}"));
-      reply_to_request_simple (request, "{'ok': 1}");
-      ASSERT_OR_PRINT (future_get_bool (future), error);
-      future_destroy (future);
-      request_destroy (request);
-   } else {
-      /* not simple, no read preference */
-      cursor = mongoc_database_command (db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL);
-      future = future_cursor_next (cursor, &reply);
-      request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
-
-      reply_to_request_simple (request, "{'ok': 1}");
-      ASSERT (future_get_bool (future));
-      future_destroy (future);
-      request_destroy (request);
-      mongoc_cursor_destroy (cursor);
-
-      /* with read preference */
-      cursor = mongoc_database_command (db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref);
-      future = future_cursor_next (cursor, &reply);
-      request = mock_server_receives_msg (server,
-                                          MONGOC_MSG_NONE,
-                                          tmp_bson ("{'$db': 'db',"
-                                                    " 'foo': 1,"
-                                                    " '$readPreference': {'mode': 'secondary'}}"));
-
-      reply_to_request_simple (request, "{'ok': 1}");
-      ASSERT (future_get_bool (future));
-      future_destroy (future);
-      request_destroy (request);
-      mongoc_cursor_destroy (cursor);
-   }
+   /* without read preference */
+   future = future_database_command_simple (db, cmd, NULL, NULL, &error);
+
+   request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}"));
+
+   reply_to_request_simple (request, "{'ok': 1}");
+   ASSERT_OR_PRINT (future_get_bool (future), error);
+   future_destroy (future);
+   request_destroy (request);
+
+   /* with read preference */
+   future = future_database_command_simple (db, cmd, secondary_pref, NULL, &error);
+
+   request = mock_server_receives_msg (server,
+                                       MONGOC_MSG_NONE,
+                                       tmp_bson ("{'$db': 'db',"
+                                                 " 'foo': 1,"
+                                                 " '$readPreference': {'mode': 'secondary'}}"));
+   reply_to_request_simple (request, "{'ok': 1}");
+   ASSERT_OR_PRINT (future_get_bool (future), error);
+   future_destroy (future);
+   request_destroy (request);
 
    mongoc_database_destroy (db);
    mongoc_read_prefs_destroy (secondary_pref);
@@ -451,28 +366,14 @@ _test_db_command_read_prefs (bool simple
 static void
 test_db_command_simple_read_prefs_single (void)
 {
-   _test_db_command_read_prefs (true, false);
+   _test_db_command_read_prefs (false);
 }
 
 
 static void
 test_db_command_simple_read_prefs_pooled (void)
 {
-   _test_db_command_read_prefs (true, true);
-}
-
-
-static void
-test_db_command_read_prefs_single (void)
-{
-   _test_db_command_read_prefs (false, false);
-}
-
-
-static void
-test_db_command_read_prefs_pooled (void)
-{
-   _test_db_command_read_prefs (false, true);
+   _test_db_command_read_prefs (true);
 }
 
 
@@ -617,7 +518,6 @@ test_get_collection_info (void)
    bson_iter_t col_iter;
    bson_t capped_options = BSON_INITIALIZER;
    bson_t noopts_options = BSON_INITIALIZER;
-   bson_t name_filter = BSON_INITIALIZER;
    const bson_t *doc;
    int num_infos = 0;
 
@@ -650,19 +550,12 @@ test_get_collection_info (void)
    ASSERT_OR_PRINT (collection, error);
    mongoc_collection_destroy (collection);
 
-   /* first we filter on collection name. */
-   BSON_APPEND_UTF8 (&name_filter, "name", noopts_name);
-
    /* We only test with filters since get_collection_names will
     * test w/o filters for us. */
 
    /* Filter on an exact match of name */
-   BEGIN_IGNORE_DEPRECATIONS
-   cursor = mongoc_database_find_collections (database, &name_filter, &error);
-   END_IGNORE_DEPRECATIONS
+   cursor = mongoc_database_find_collections_with_opts (database, tmp_bson ("{'filter': {'name': '%s'}}", noopts_name));
    BSON_ASSERT (cursor);
-   BSON_ASSERT (!error.domain);
-   BSON_ASSERT (!error.code);
 
    while (mongoc_cursor_next (cursor, &doc)) {
       if (bson_iter_init (&col_iter, doc) && bson_iter_find (&col_iter, "name") && BSON_ITER_HOLDS_UTF8 (&col_iter) &&
@@ -674,6 +567,8 @@ test_get_collection_info (void)
       }
    }
 
+   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
+
    BSON_ASSERT (1 == num_infos);
 
    mongoc_cursor_destroy (cursor);
@@ -687,64 +582,11 @@ test_get_collection_info (void)
 
    bson_destroy (&capped_options);
    bson_destroy (&noopts_options);
-   bson_destroy (&name_filter);
 
    mongoc_database_destroy (database);
    mongoc_client_destroy (client);
 }
 
-static void
-test_get_collection_info_regex (void)
-{
-   mongoc_database_t *database;
-   mongoc_collection_t *collection;
-   mongoc_client_t *client;
-   mongoc_cursor_t *cursor;
-   bson_error_t error = {0};
-   bson_iter_t col_iter;
-   bson_t name_filter = BSON_INITIALIZER;
-   const bson_t *doc;
-   char *dbname;
-
-   client = test_framework_new_default_client ();
-   BSON_ASSERT (client);
-
-   dbname = gen_collection_name ("test_get_collection_info_regex");
-   database = mongoc_client_get_database (client, dbname);
-   mongoc_database_drop_with_opts (database, NULL, NULL);
-
-   collection = mongoc_database_create_collection (database, "abbbc", NULL, &error);
-   ASSERT_OR_PRINT (collection, error);
-   mongoc_collection_destroy (collection);
-
-   collection = mongoc_database_create_collection (database, "foo", NULL, &error);
-   ASSERT_OR_PRINT (collection, error);
-
-   BSON_APPEND_REGEX (&name_filter, "name", "ab+c", NULL);
-
-   BEGIN_IGNORE_DEPRECATIONS
-   cursor = mongoc_database_find_collections (database, &name_filter, &error);
-   END_IGNORE_DEPRECATIONS
-
-   BSON_ASSERT (cursor);
-   BSON_ASSERT (!error.domain);
-   BSON_ASSERT (!error.code);
-
-   BSON_ASSERT (mongoc_cursor_next (cursor, &doc));
-   BSON_ASSERT (bson_iter_init_find (&col_iter, doc, "name"));
-   BSON_ASSERT (0 == strcmp (bson_iter_utf8 (&col_iter, NULL), "abbbc"));
-
-   /* only one match */
-   BSON_ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
-   mongoc_cursor_destroy (cursor);
-
-   bson_destroy (&name_filter);
-   mongoc_collection_destroy (collection);
-   bson_free (dbname);
-   mongoc_database_destroy (database);
-   mongoc_client_destroy (client);
-}
 
 static void
 test_get_collection_info_with_opts_regex (void)
@@ -1078,17 +920,13 @@ test_database_install (TestSuite *suite)
       suite, "/Database/create_with_write_concern", test_create_with_write_concern, NULL, NULL, TestSuite_CheckLive);
    TestSuite_AddLive (suite, "/Database/copy", test_copy);
    TestSuite_AddLive (suite, "/Database/has_collection", test_has_collection);
-   TestSuite_AddLive (suite, "/Database/command", test_command);
    TestSuite_AddMockServerTest (
       suite, "/Database/command/read_prefs/simple/single", test_db_command_simple_read_prefs_single);
    TestSuite_AddMockServerTest (
       suite, "/Database/command/read_prefs/simple/pooled", test_db_command_simple_read_prefs_pooled);
-   TestSuite_AddMockServerTest (suite, "/Database/command/read_prefs/single", test_db_command_read_prefs_single);
-   TestSuite_AddMockServerTest (suite, "/Database/command/read_prefs/pooled", test_db_command_read_prefs_pooled);
    TestSuite_AddLive (suite, "/Database/drop", test_drop);
    TestSuite_AddLive (suite, "/Database/create_collection", test_create_collection);
    TestSuite_AddLive (suite, "/Database/get_collection_info", test_get_collection_info);
-   TestSuite_AddLive (suite, "/Database/get_collection_info_regex", test_get_collection_info_regex);
    TestSuite_AddLive (suite, "/Database/get_collection_info_with_opts_regex", test_get_collection_info_with_opts_regex);
    TestSuite_AddMockServerTest (suite, "/Database/get_collection/getmore_cmd", test_get_collection_info_getmore_cmd);
    TestSuite_AddLive (suite, "/Database/get_collection", test_get_collection);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-dns.c 2.0.2-1/src/libmongoc/tests/test-mongoc-dns.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-dns.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-dns.c	2025-06-19 15:42:22.000000000 +0000
@@ -13,7 +13,7 @@
 
 #include "json-test.h"
 #include "test-libmongoc.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 static void
 _assert_options_match (const bson_t *test, mongoc_uri_t *uri)
@@ -203,7 +203,7 @@ _host_list_matches (const bson_t *test,
       ctx->hosts = NULL;
       bson_mutex_unlock (&ctx->mutex);
 
-      ret = mcommon_cmp_equal_su (expected, actual);
+      ret = mlib_cmp (expected, ==, actual);
    }
 
    return ret;
@@ -908,7 +908,7 @@ _mock_rr_resolver_prose_test_10 (const c
 
    if (rr_type == MONGOC_RR_SRV) {
       const size_t count = _mongoc_host_list_length (rr_data->hosts);
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, count));
+      BSON_ASSERT (mlib_in_range (uint32_t, count));
 
       rr_data->hosts = MAKE_HOSTS ("localhost.test.build.10gen.cc:27017",
                                    "localhost.test.build.10gen.cc:27019",
@@ -1010,7 +1010,7 @@ _mock_rr_resolver_prose_test_11 (const c
 
    if (rr_type == MONGOC_RR_SRV) {
       const size_t count = _mongoc_host_list_length (rr_data->hosts);
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, count));
+      BSON_ASSERT (mlib_in_range (uint32_t, count));
 
       rr_data->hosts = MAKE_HOSTS ("localhost.test.build.10gen.cc:27019", "localhost.test.build.10gen.cc:27020");
       rr_data->count = (uint32_t) count;
@@ -1109,7 +1109,7 @@ _mock_rr_resolver_prose_test_12 (const c
 
    if (rr_type == MONGOC_RR_SRV) {
       const size_t count = _mongoc_host_list_length (rr_data->hosts);
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, count));
+      BSON_ASSERT (mlib_in_range (uint32_t, count));
 
       rr_data->hosts = MAKE_HOSTS ("localhost.test.build.10gen.cc:27017",
                                    "localhost.test.build.10gen.cc:27019",
@@ -1260,7 +1260,7 @@ _mock_rr_resolver_with_override (const c
    if (rr_type == MONGOC_RR_SRV) {
       bson_mutex_lock (&rr_override.lock);
       const size_t count = _mongoc_host_list_length (rr_override.hosts);
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, count));
+      BSON_ASSERT (mlib_in_range (uint32_t, count));
       rr_data->hosts = _mongoc_host_list_copy_all (rr_override.hosts);
       rr_data->count = (uint32_t) count;
       rr_data->txt_record_opts = NULL;
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-error.c 2.0.2-1/src/libmongoc/tests/test-mongoc-error.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-error.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-error.c	2025-06-19 15:42:22.000000000 +0000
@@ -7,6 +7,7 @@
 #include "mock_server/future-functions.h"
 #include "mock_server/mock-server.h"
 #include <mongoc/mongoc-error-private.h>
+#include <mlib/loop.h>
 
 #include <inttypes.h>
 
@@ -18,15 +19,12 @@
 static void
 test_set_error_api_single (void)
 {
-   mongoc_client_t *client;
-   int32_t unsupported_versions[] = {-1, 0, 3};
-   int i;
-
    capture_logs (true);
-   client = test_framework_new_default_client ();
+   mongoc_client_t *const client = test_framework_new_default_client ();
 
-   for (i = 0; i < sizeof (unsupported_versions) / sizeof (int32_t); i++) {
-      ASSERT (!mongoc_client_set_error_api (client, unsupported_versions[i]));
+   int32_t unsupported_versions[] = {-1, 0, 3};
+   mlib_foreach_arr (int32_t, ver, unsupported_versions) {
+      ASSERT (!mongoc_client_set_error_api (client, *ver));
       ASSERT_CAPTURED_LOG ("mongoc_client_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Unsupported Error API Version");
    }
 
@@ -37,20 +35,16 @@ test_set_error_api_single (void)
 static void
 test_set_error_api_pooled (void)
 {
-   mongoc_client_pool_t *pool;
-   mongoc_client_t *client;
-   int32_t unsupported_versions[] = {-1, 0, 3};
-   int i;
-
    capture_logs (true);
-   pool = test_framework_new_default_client_pool ();
+   mongoc_client_pool_t *const pool = test_framework_new_default_client_pool ();
 
-   for (i = 0; i < sizeof (unsupported_versions) / sizeof (int32_t); i++) {
-      ASSERT (!mongoc_client_pool_set_error_api (pool, unsupported_versions[i]));
+   int32_t unsupported_versions[] = {-1, 0, 3};
+   mlib_foreach_arr (int32_t, ver, unsupported_versions) {
+      ASSERT (!mongoc_client_pool_set_error_api (pool, *ver));
       ASSERT_CAPTURED_LOG ("mongoc_client_pool_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Unsupported Error API Version");
    }
 
-   client = mongoc_client_pool_pop (pool);
+   mongoc_client_t *const client = mongoc_client_pool_pop (pool);
    ASSERT (!mongoc_client_set_error_api (client, 1));
    ASSERT_CAPTURED_LOG (
       "mongoc_client_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Cannot set Error API Version on a pooled client");
@@ -140,28 +134,26 @@ test_state_change_helper (uint32_t domai
                                                      MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS};
    mongoc_server_err_t shutdown_codes[] = {MONGOC_SERVER_ERR_INTERRUPTEDATSHUTDOWN,
                                            MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS};
-   int i;
-
    MONGOC_DEBUG ("Checking domain = %" PRIu32, domain);
 
    memset (&error, 0, sizeof (bson_error_t));
    error.domain = domain;
 
-   for (i = 0; i < sizeof (not_primary_codes) / sizeof (mongoc_server_err_t); i++) {
-      error.code = not_primary_codes[i];
+   mlib_foreach_arr (mongoc_server_err_t, err, not_primary_codes) {
+      error.code = *err;
       BSON_ASSERT (expect_error == _mongoc_error_is_not_primary (&error));
       BSON_ASSERT (!_mongoc_error_is_recovering (&error));
       BSON_ASSERT (!_mongoc_error_is_shutdown (&error));
       BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error));
    }
-   for (i = 0; i < sizeof (node_is_recovering_codes) / sizeof (mongoc_server_err_t); i++) {
-      error.code = node_is_recovering_codes[i];
+   mlib_foreach_arr (mongoc_server_err_t, err, node_is_recovering_codes) {
+      error.code = *err;
       BSON_ASSERT (!_mongoc_error_is_not_primary (&error));
       BSON_ASSERT (expect_error == _mongoc_error_is_recovering (&error));
       BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error));
    }
-   for (i = 0; i < sizeof (shutdown_codes) / sizeof (mongoc_server_err_t); i++) {
-      error.code = shutdown_codes[i];
+   mlib_foreach_arr (mongoc_server_err_t, err, shutdown_codes) {
+      error.code = *err;
       BSON_ASSERT (!_mongoc_error_is_not_primary (&error));
       /* Shutdown errors are a subset of recovering errors. */
       BSON_ASSERT (expect_error == _mongoc_error_is_recovering (&error));
@@ -217,6 +209,68 @@ test_state_change (void)
    test_state_change_helper (MONGOC_ERROR_QUERY, false);
 }
 
+static void
+test_mongoc_error_basic (void)
+{
+   bson_error_t error;
+
+   _mongoc_set_error (&error, 123, 456, "%s:%d", "localhost", 27017);
+   ASSERT_CMPSTR (error.message, "localhost:27017");
+   ASSERT_CMPUINT32 (error.domain, ==, 123u);
+   ASSERT_CMPUINT32 (error.code, ==, 456u);
+   ASSERT_CMPUINT (error.reserved, ==, 2u); // MONGOC_ERROR_CATEGORY
+}
+
+static void
+test_mongoc_error_with_category (void)
+{
+   bson_error_t error;
+
+   _mongoc_set_error_with_category (&error, 99u, 123, 456, "%s:%d", "localhost", 27017);
+   ASSERT_CMPSTR (error.message, "localhost:27017");
+   ASSERT_CMPUINT32 (error.domain, ==, 123u);
+   ASSERT_CMPUINT32 (error.code, ==, 456u);
+   ASSERT_CMPUINT (error.reserved, ==, 99u);
+}
+
+#ifdef _WIN32
+static void
+test_mongoc_winerr_to_string (void)
+{
+   // Test WIN32 success.
+   {
+      char *got = mongoc_winerr_to_string ((DWORD) NO_ERROR);
+      const char *expect = "(0x00000000) The operation completed successfully.";
+      ASSERT_CMPSTR (expect, got);
+      bson_free (got);
+   }
+
+   // Test WIN32 error.
+   {
+      char *got = mongoc_winerr_to_string ((DWORD) ERROR_FILE_NOT_FOUND);
+      const char *expect = "(0x00000002) The system cannot find the file specified.";
+      ASSERT_CMPSTR (expect, got);
+      bson_free (got);
+   }
+
+   // Test SECURITY_STATUS error.
+   {
+      char *got = mongoc_winerr_to_string ((DWORD) SEC_E_CERT_EXPIRED);
+      const char *expect = "(0x80090328) The received certificate has expired.";
+      ASSERT_CMPSTR (expect, got);
+      bson_free (got);
+   }
+
+   // Test DNS_STATUS error.
+   {
+      char *got = mongoc_winerr_to_string ((DWORD) DNS_ERROR_RCODE_SERVER_FAILURE);
+      const char *expect = "(0x0000232A) DNS server failure.";
+      ASSERT_CMPSTR (expect, got);
+      bson_free (got);
+   }
+}
+#endif // _WIN32
+
 void
 test_error_install (TestSuite *suite)
 {
@@ -227,4 +281,9 @@ test_error_install (TestSuite *suite)
    TestSuite_AddMockServerTest (suite, "/Error/command/v2", test_command_error_v2);
    TestSuite_Add (suite, "/Error/has_label", test_has_label);
    TestSuite_Add (suite, "/Error/state_change", test_state_change);
+   TestSuite_Add (suite, "/Error/basic", test_mongoc_error_basic);
+   TestSuite_Add (suite, "/Error/category", test_mongoc_error_with_category);
+#ifdef _WIN32
+   TestSuite_Add (suite, "/Error/windows_error_to_string", test_mongoc_winerr_to_string);
+#endif
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-exhaust.c 2.0.2-1/src/libmongoc/tests/test-mongoc-exhaust.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-exhaust.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-exhaust.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,9 +16,6 @@
 #include <common-oid-private.h>
 
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "exhaust-test"
-
 /* Server support for exhaust cursors depends on server topology and version:
  * Server Version      Server Behavior
  * ------------------  -----------------------------------
@@ -164,17 +161,18 @@ test_exhaust_cursor (bool pooled)
          bptr[i] = &b[i];
       }
 
-      BEGIN_IGNORE_DEPRECATIONS
-      ASSERT_OR_PRINT (
-         mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) bptr, 10, wr, &error), error);
-      END_IGNORE_DEPRECATIONS
+      bson_t opts = BSON_INITIALIZER;
+      ASSERT (mongoc_write_concern_append (wr, &opts));
+      ASSERT_OR_PRINT (mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, &opts, NULL, &error),
+                       error);
+      bson_destroy (&opts);
    }
 
    /* create a couple of cursors */
    {
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL);
+      cursor = mongoc_collection_find_with_opts (collection, &q, tmp_bson ("{'exhaust': true, 'batchSize': 5}"), NULL);
 
-      cursor2 = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL);
+      cursor2 = mongoc_collection_find_with_opts (collection, &q, NULL, NULL);
    }
 
    /* Read from the exhaust cursor, ensure that we're in exhaust where we
@@ -206,7 +204,7 @@ test_exhaust_cursor (bool pooled)
     * (putting the client into exhaust), breaks a mid-stream read from a
     * regular cursor */
    {
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL);
+      cursor = mongoc_collection_find_with_opts (collection, &q, tmp_bson ("{'exhaust': true, 'batchSize': 5}"), NULL);
 
       r = mongoc_cursor_next (cursor2, &doc);
       if (!r) {
@@ -250,9 +248,10 @@ test_exhaust_cursor (bool pooled)
 
    /* make sure writes fail as well */
    {
-      BEGIN_IGNORE_DEPRECATIONS
-      r = mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) bptr, 10, wr, &error);
-      END_IGNORE_DEPRECATIONS
+      bson_t opts = BSON_INITIALIZER;
+      ASSERT (mongoc_write_concern_append (wr, &opts));
+      r = mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, &opts, NULL, &error);
+      bson_destroy (&opts);
 
       BSON_ASSERT (!r);
       ASSERT_CMPUINT32 (error.domain, ==, MONGOC_ERROR_CLIENT);
@@ -267,7 +266,7 @@ test_exhaust_cursor (bool pooled)
     * 4. make sure we can read the cursor we made during the exhaust
     */
    {
-      cursor2 = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL);
+      cursor2 = mongoc_collection_find_with_opts (collection, &q, NULL, NULL);
 
       server_id = cursor->server_id;
       stream = (mongoc_stream_t *) mongoc_set_get (client->cluster.nodes, server_id);
@@ -433,7 +432,8 @@ test_exhaust_cursor_multi_batch (void *c
    server_id = mongoc_bulk_operation_execute (bulk, NULL, &error);
    ASSERT_OR_PRINT (server_id, error);
 
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 10, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (
+      collection, tmp_bson ("{}"), tmp_bson ("{'exhaust': true, 'batchSize': 10}"), NULL);
 
    i = 0;
    while (mongoc_cursor_next (cursor, &cursor_doc)) {
@@ -465,7 +465,7 @@ test_cursor_server_hint_with_exhaust (vo
                                                                NULL /* read_prefs */);
 
    // Set a bogus server ID.
-   mongoc_cursor_set_hint (cursor, 123);
+   mongoc_cursor_set_server_id (cursor, 123);
 
    // Iterate the cursor.
    const bson_t *result;
@@ -492,8 +492,8 @@ test_cursor_set_max_await_time_ms (void)
    client = test_framework_new_default_client ();
    collection = get_test_collection (client, "test_cursor_set_max_await_time_ms");
 
-   cursor = mongoc_collection_find (
-      collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (
+      collection, tmp_bson ("{}"), tmp_bson ("{'tailable': true, 'awaitData': true}"), NULL);
 
    ASSERT_CMPINT (0, ==, mongoc_cursor_get_max_await_time_ms (cursor));
    mongoc_cursor_set_max_await_time_ms (cursor, 123);
@@ -581,7 +581,7 @@ _mock_test_exhaust (bool pooled, exhaust
    }
 
    collection = mongoc_client_get_collection (client, "db", "test");
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson ("{}"), NULL, NULL);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'exhaust': true}"), NULL);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_query (
@@ -693,7 +693,7 @@ test_exhaust_in_child (void)
 
    /* insert some documents, more than one reply's worth. */
    to_insert = BCON_NEW ("x", BCON_INT32 (1));
-   bulk = mongoc_collection_create_bulk_operation (coll, false, NULL /* wc */);
+   bulk = mongoc_collection_create_bulk_operation_with_opts (coll, NULL);
    for (i = 0; i < 1001; i++) {
       ret = mongoc_bulk_operation_insert_with_opts (bulk, to_insert, NULL /* opts */, &error);
       ASSERT_OR_PRINT (ret, error);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs-bucket.c 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs-bucket.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs-bucket.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs-bucket.c	2025-06-19 15:42:22.000000000 +0000
@@ -71,14 +71,14 @@ _get_index_count (mongoc_collection_t *c
    int n;
    const bson_t *info;
 
-   cursor = mongoc_collection_find_indexes (collection, &error);
-   ASSERT_OR_PRINT (0 == error.code, error);
+   cursor = mongoc_collection_find_indexes_with_opts (collection, NULL);
 
    n = 0;
 
    while (mongoc_cursor_next (cursor, &info)) {
       n++;
    }
+   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error);
 
    mongoc_cursor_destroy (cursor);
 
@@ -632,7 +632,7 @@ gridfs_spec_download_operation (mongoc_d
 
    r = hex_to_bytes (str, &hex_len, &hex_bytes);
    if (r) {
-      ASSERT (ret == hex_len);
+      ASSERT (mlib_cmp (ret, ==, hex_len));
       ASSERT (memcmp (buf, hex_bytes, hex_len) == 0);
       bson_free (hex_bytes);
    } else {
@@ -709,7 +709,7 @@ gridfs_spec_upload_operation (mongoc_dat
    ASSERT (stream);
 
    bytes_written = mongoc_stream_write (stream, hex_bytes, hex_len, 0);
-   ASSERT (bytes_written == hex_len);
+   ASSERT (mlib_cmp (bytes_written, ==, hex_len));
    bson_free (hex_bytes);
 
    mongoc_stream_close (stream);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs-file-page.c 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs-file-page.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs-file-page.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs-file-page.c	2025-06-19 15:42:22.000000000 +0000
@@ -109,7 +109,7 @@ test_read (void)
    ASSERT (page->offset == 3);
 
    r = _mongoc_gridfs_file_page_read (page, buf, 50);
-   ASSERT (r == len - 3);
+   ASSERT (mlib_cmp (r, ==, len - 3));
    ASSERT (memcmp (fox + 3, buf, len - 3) == 0);
 
    _mongoc_gridfs_file_page_destroy (page);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs.c 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-gridfs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-gridfs.c	2025-06-19 15:42:22.000000000 +0000
@@ -13,7 +13,7 @@
 #include "mock_server/future.h"
 #include "mock_server/future-functions.h"
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 
 static mongoc_gridfs_t *
@@ -53,8 +53,7 @@ _check_index (mongoc_collection_t *colle
    bson_t index_key;
    int n;
 
-   cursor = mongoc_collection_find_indexes (collection, &error);
-   ASSERT_OR_PRINT (0 == error.code, error);
+   cursor = mongoc_collection_find_indexes_with_opts (collection, NULL);
 
    n = 0;
 
@@ -276,7 +275,7 @@ test_list (void)
    mongoc_client_t *client;
    bson_error_t error;
    mongoc_gridfs_file_list_t *list;
-   bson_t query, child;
+   bson_t query, opts, child;
    char buf[100];
    int i = 0;
 
@@ -288,14 +287,14 @@ test_list (void)
    prep_files (gridfs);
 
    bson_init (&query);
-   bson_append_document_begin (&query, "$orderby", -1, &child);
+   bson_init (&opts);
+   bson_append_document_begin (&opts, "sort", -1, &child);
    bson_append_int32 (&child, "filename", -1, 1);
-   bson_append_document_end (&query, &child);
-   bson_append_document_begin (&query, "$query", -1, &child);
-   bson_append_document_end (&query, &child);
+   bson_append_document_end (&opts, &child);
 
-   list = mongoc_gridfs_find (gridfs, &query);
+   list = mongoc_gridfs_find_with_opts (gridfs, &query, NULL);
 
+   bson_destroy (&opts);
    bson_destroy (&query);
 
    i = 0;
@@ -311,7 +310,7 @@ test_list (void)
 
    bson_init (&query);
    bson_append_utf8 (&query, "filename", -1, "file.1", -1);
-   ASSERT_OR_PRINT (file = mongoc_gridfs_find_one (gridfs, &query, &error), error);
+   ASSERT_OR_PRINT (file = mongoc_gridfs_find_one_with_opts (gridfs, &query, NULL, &error), error);
    bson_destroy (&query);
 
    ASSERT_CMPINT (strcmp (mongoc_gridfs_file_get_filename (file), "file.1"), ==, 0);
@@ -495,7 +494,7 @@ test_properties (void)
 
    ASSERT (mongoc_collection_insert_one (mongoc_gridfs_get_files (gridfs), doc_in, NULL, NULL, NULL));
 
-   list = mongoc_gridfs_find (gridfs, &query);
+   list = mongoc_gridfs_find_with_opts (gridfs, &query, NULL);
    file = mongoc_gridfs_file_list_next (list);
    file_id = mongoc_gridfs_file_get_id (file);
    ASSERT (file_id);
@@ -665,7 +664,7 @@ test_read (void)
 
    BSON_ASSERT (errno == previous_errno);
    BSON_ASSERT (r == 0);
-   BSON_ASSERT (mongoc_gridfs_file_tell (file) == file->length + 20);
+   BSON_ASSERT (mlib_cmp (mongoc_gridfs_file_tell (file), ==, file->length + 20));
 
    mongoc_gridfs_file_destroy (file);
 
@@ -757,11 +756,11 @@ _test_write (bool at_boundary)
 
    /* Test writing beyond the end of the file */
    BSON_ASSERT (mongoc_gridfs_file_seek (file, seek_len, SEEK_END) == 0);
-   BSON_ASSERT (mongoc_gridfs_file_tell (file) == file->length + seek_len);
+   BSON_ASSERT (mlib_cmp (mongoc_gridfs_file_tell (file), ==, file->length + seek_len));
 
    r = mongoc_gridfs_file_writev (file, iov, 2, 0);
    BSON_ASSERT (r == len);
-   BSON_ASSERT (mongoc_gridfs_file_tell (file) == 2 * len + seek_len);
+   BSON_ASSERT (mlib_cmp (mongoc_gridfs_file_tell (file), ==, 2 * len + seek_len));
    BSON_ASSERT (file->length == 2 * len + seek_len);
    BSON_ASSERT (mongoc_gridfs_file_save (file));
    _check_chunk_count (gridfs, 2 * len + seek_len, file->chunk_size);
@@ -842,14 +841,14 @@ test_write_past_end (void)
    ASSERT (file);
 
    r = mongoc_gridfs_file_writev (file, iov, 1, 0);
-   ASSERT (mcommon_in_range_signed (size_t, r));
+   ASSERT (mlib_in_range (size_t, r));
    ASSERT_CMPSIZE_T ((size_t) r, ==, len);
 
    ASSERT_CMPINT (mongoc_gridfs_file_seek (file, (int64_t) delta, SEEK_SET), ==, 0);
    ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file), ==, delta);
 
    r = mongoc_gridfs_file_writev (file, iov, 1, 0);
-   ASSERT (mcommon_in_range_signed (size_t, r));
+   ASSERT (mlib_in_range (size_t, r));
    ASSERT_CMPSIZE_T ((size_t) r, ==, len);
    mongoc_gridfs_file_save (file);
 
@@ -857,17 +856,17 @@ test_write_past_end (void)
       mongoc_collection_count_documents (mongoc_gridfs_get_chunks (gridfs), tmp_bson (NULL), NULL, NULL, NULL, &error);
 
    ASSERT_OR_PRINT (cnt != -1, error);
-   ASSERT (mcommon_cmp_equal_us (expected_chunks, cnt));
+   ASSERT (mlib_cmp (expected_chunks, ==, cnt));
 
    mongoc_gridfs_file_destroy (file);
-   file = mongoc_gridfs_find_one (gridfs, tmp_bson (NULL), &error);
+   file = mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson (NULL), NULL, &error);
    ASSERT_OR_PRINT (file, error);
 
-   BSON_ASSERT (mcommon_in_range_unsigned (size_t, delta + len));
+   BSON_ASSERT (mlib_in_range (size_t, delta + len));
    const size_t total_bytes = (size_t) (delta + len);
 
    r = mongoc_gridfs_file_readv (file, &riov, 1, total_bytes, 0);
-   ASSERT (mcommon_in_range_signed (size_t, r));
+   ASSERT (mlib_in_range (size_t, r));
    ASSERT_CMPSIZE_T ((size_t) r, ==, total_bytes);
 
    mongoc_gridfs_file_destroy (file);
@@ -963,7 +962,7 @@ test_stream (void)
 
    stream = mongoc_stream_gridfs_new (file);
 
-   ASSERT (mcommon_in_range_signed (size_t, file->length));
+   ASSERT (mlib_in_range (size_t, file->length));
    const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) file->length, 0);
    ASSERT_CMPINT64 ((int64_t) r, ==, file->length);
 
@@ -1022,7 +1021,7 @@ test_long_seek (void *ctx)
    /* new file handle */
    mongoc_gridfs_file_save (file);
    mongoc_gridfs_file_destroy (file);
-   file = mongoc_gridfs_find_one (gridfs, tmp_bson ("{'filename': 'filename'}"), &error);
+   file = mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson ("{'filename': 'filename'}"), NULL, &error);
 
    ASSERT_OR_PRINT (file, error);
 
@@ -1307,7 +1306,7 @@ test_set_id (void)
    /* if we find a file with new id, then file_set_id worked */
    ASSERT_OR_PRINT (mongoc_gridfs_file_set_id (file, &id, &error), error);
    ASSERT (mongoc_gridfs_file_save (file));
-   result = mongoc_gridfs_find_one (gridfs, query, &error);
+   result = mongoc_gridfs_find_one_with_opts (gridfs, query, NULL, &error);
    ASSERT_OR_PRINT (result, error);
 
    mongoc_gridfs_file_destroy (result);
@@ -1353,7 +1352,7 @@ test_inherit_client_config (void)
    gridfs = _get_gridfs (server, client, MONGOC_QUERY_NONE);
 
    /* test read prefs and read concern */
-   future = future_gridfs_find_one (gridfs, tmp_bson ("{}"), &error);
+   future = future_gridfs_find_one_with_opts (gridfs, tmp_bson ("{}"), NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
@@ -1402,17 +1401,18 @@ test_find_one_empty (void)
 {
    mongoc_gridfs_t *gridfs;
    mongoc_client_t *client;
-   bson_error_t error = {1, 2, "hello"};
+   bson_error_t error = {1, 2, "hello", 0};
 
    client = test_framework_new_default_client ();
    gridfs = get_test_gridfs (client, "list", &error);
    ASSERT_OR_PRINT (gridfs, error);
-   ASSERT (!mongoc_gridfs_find_one (gridfs, tmp_bson ("{'x': 'doesntexist'}"), &error));
+   ASSERT (!mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson ("{'x': 'doesntexist'}"), NULL, &error));
 
    /* ensure "error" is cleared if we successfully find no file */
-   ASSERT_CMPINT (error.domain, ==, 0);
-   ASSERT_CMPINT (error.code, ==, 0);
+   ASSERT_CMPUINT32 (error.domain, ==, 0);
+   ASSERT_CMPUINT32 (error.code, ==, 0);
    ASSERT_CMPSTR (error.message, "");
+   ASSERT_CMPUINT (error.reserved, ==, 0);
 
    mongoc_gridfs_destroy (gridfs);
    mongoc_client_destroy (client);
@@ -1518,7 +1518,7 @@ test_reading_multiple_chunks (void)
             ssize_t got =
                mongoc_gridfs_file_readv (file, &iov, 1 /* iovcnt */, 1 /* min_bytes */, 0 /* timeout_msec */);
             ASSERT_CMPSSIZE_T (got, >=, 0);
-            ASSERT (mcommon_in_range_int_signed (got));
+            ASSERT (mlib_in_range (int, got));
             mcommon_string_append_printf (&str, "%.*s", (int) got, (char *) buf);
             ASSERT_CMPSSIZE_T (got, ==, 4);
          }
@@ -1528,7 +1528,7 @@ test_reading_multiple_chunks (void)
             ssize_t got =
                mongoc_gridfs_file_readv (file, &iov, 1 /* iovcnt */, 1 /* min_bytes */, 0 /* timeout_msec */);
             ASSERT_CMPSSIZE_T (got, >=, 0);
-            ASSERT (mcommon_in_range_int_signed (got));
+            ASSERT (mlib_in_range (int, got));
             mcommon_string_append_printf (&str, "%.*s", (int) got, (char *) buf);
             ASSERT_CMPSSIZE_T (got, ==, 3);
          }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-gssapi.c 2.0.2-1/src/libmongoc/tests/test-mongoc-gssapi.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-gssapi.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-gssapi.c	2025-06-19 15:42:22.000000000 +0000
@@ -79,7 +79,7 @@ static BSON_THREAD_FUN (gssapi_kerberos_
       }
       bson_destroy (cmd);
       collection = mongoc_client_get_collection (client, "kerberos", "test");
-      cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL);
+      cursor = mongoc_collection_find_with_opts (collection, &query, NULL, NULL);
 
       if (!mongoc_cursor_next (cursor, &doc) && mongoc_cursor_error (cursor, &error)) {
          fflush (stdout);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-handshake.c 2.0.2-1/src/libmongoc/tests/test-mongoc-handshake.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-handshake.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-handshake.c	2025-06-19 15:42:22.000000000 +0000
@@ -1189,18 +1189,12 @@ test_handshake_platform_config (void)
    BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_HAVE_SASL_CLIENT_DONE));
 #endif
 
-#ifdef MONGOC_NO_AUTOMATIC_GLOBALS
-   BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS));
-#endif
+   BSON_ASSERT (!_get_bit (config_str, MONGOC_MD_FLAG_NO_AUTOMATIC_GLOBALS_UNUSED)); // Flag was removed.
 
 #ifdef MONGOC_EXPERIMENTAL_FEATURES
    BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_EXPERIMENTAL_FEATURES));
 #endif
 
-#ifdef MONGOC_ENABLE_SSL_LIBRESSL
-   BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SSL_LIBRESSL));
-#endif
-
 #ifdef MONGOC_ENABLE_SASL_CYRUS
    BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SASL_CYRUS));
 #endif
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-hedged-reads.c 2.0.2-1/src/libmongoc/tests/test-mongoc-hedged-reads.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-hedged-reads.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-hedged-reads.c	2025-06-19 15:42:22.000000000 +0000
@@ -24,9 +24,6 @@
 #include "test-libmongoc.h"
 #include "test-conveniences.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "client-test-hedged-reads"
-
 
 static void
 test_mongos_hedged_reads_read_pref (void)
@@ -52,7 +49,7 @@ test_mongos_hedged_reads_read_pref (void
     * readPreference. */
    mongoc_collection_set_read_prefs (collection, prefs);
 
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, prefs, NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
@@ -71,7 +68,7 @@ test_mongos_hedged_reads_read_pref (void
    mongoc_read_prefs_set_hedge (prefs, &hedge_doc);
    mongoc_collection_set_read_prefs (collection, prefs);
 
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, prefs, NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-long-namespace.c 2.0.2-1/src/libmongoc/tests/test-mongoc-long-namespace.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-long-namespace.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-long-namespace.c	2025-06-19 15:42:22.000000000 +0000
@@ -262,81 +262,6 @@ change_stream (test_fixture_t *test_fixt
 }
 
 
-/* Test mongoc_client_command, which constructed a namespace with
- * MONGOC_NAMESPACE_MAX */
-static void
-client_command (test_fixture_t *test_fixture)
-{
-   const bson_t *found;
-   mongoc_cursor_t *cursor;
-   bool ret;
-   bson_error_t error;
-
-   cursor = mongoc_client_command (test_fixture->client,
-                                   test_fixture->ns_db,
-                                   MONGOC_QUERY_NONE,
-                                   0 /* skip */,
-                                   0 /* limit */,
-                                   0 /* batch size */,
-                                   tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll),
-                                   NULL /* fields */,
-                                   NULL /* read prefs */);
-   ret = mongoc_cursor_next (cursor, &found);
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error);
-   ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll);
-   mongoc_cursor_destroy (cursor);
-}
-
-/* Test mongoc_database_command, which constructed a namespace with
- * MONGOC_NAMESPACE_MAX. */
-static void
-database_command (test_fixture_t *test_fixture)
-{
-   const bson_t *found;
-   mongoc_cursor_t *cursor;
-   bool ret;
-   bson_error_t error;
-
-   cursor =
-      mongoc_database_command (test_fixture->db,
-                               MONGOC_QUERY_NONE,
-                               0 /* skip */,
-                               0 /* limit */,
-                               0 /* batch size */,
-                               tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll),
-                               NULL /* fields */,
-                               NULL /* read prefs */);
-   ret = mongoc_cursor_next (cursor, &found);
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error);
-   ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll);
-   mongoc_cursor_destroy (cursor);
-}
-
-/* Test mongoc_collection_command, which constructed a namespace with
- * MONGOC_NAMESPACE_MAX. */
-static void
-collection_command (test_fixture_t *test_fixture)
-{
-   const bson_t *found;
-   mongoc_cursor_t *cursor;
-   bool ret;
-   bson_error_t error;
-
-   cursor =
-      mongoc_collection_command (test_fixture->coll,
-                                 MONGOC_QUERY_NONE,
-                                 0 /* skip */,
-                                 0 /* limit */,
-                                 0 /* batch size */,
-                                 tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll),
-                                 NULL /* fields */,
-                                 NULL /* read prefs */);
-   ret = mongoc_cursor_next (cursor, &found);
-   ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error);
-   ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll);
-   mongoc_cursor_destroy (cursor);
-}
-
 /* Check whether a collection exists. */
 static void
 _check_existence (mongoc_client_t *client, char *ns_db, char *ns_coll, bool should_exist)
@@ -531,14 +456,6 @@ test_long_namespace_install (TestSuite *
 {
    /* MongoDB 4.4 (wire version 9) introduced support for long namespaces in
     * SERVER-32959 */
-   add_long_namespace_test (
-      "/long_namespace/client_command", client_command, test_framework_skip_if_max_wire_version_less_than_9);
-
-   add_long_namespace_test (
-      "/long_namespace/database_command", database_command, test_framework_skip_if_max_wire_version_less_than_9);
-
-   add_long_namespace_test (
-      "/long_namespace/collection_command", collection_command, test_framework_skip_if_max_wire_version_less_than_9);
 
    add_long_namespace_test ("/long_namespace/crud", crud, test_framework_skip_if_max_wire_version_less_than_9);
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-matcher.c 2.0.2-1/src/libmongoc/tests/test-mongoc-matcher.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-matcher.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-matcher.c	1970-01-01 00:00:00.000000000 +0000
@@ -1,531 +0,0 @@
-
-#include <bson/bcon.h>
-#include <mongoc/mongoc.h>
-#include <mongoc/mongoc-matcher-private.h>
-#include <mongoc/mongoc-util-private.h>
-#include <common-macros-private.h> // BEGIN_IGNORE_DEPRECATIONS
-
-#include "TestSuite.h"
-
-BEGIN_IGNORE_DEPRECATIONS
-
-static void
-test_mongoc_matcher_basic (void)
-{
-   bson_t matcher_query;
-   bson_t *query;
-   bson_t *to_match;
-   bson_t *should_fail;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-
-   bson_init (&matcher_query);
-
-   query = BCON_NEW ("city",
-                     "New York",
-                     "state",
-                     "New York",
-                     "favorite color",
-                     "blue",
-                     "name",
-                     "{",
-                     "$not",
-                     "invalid",
-                     "}",
-                     /*      "zip", "{", "$in", "[", BCON_INT32(11201), */
-                     /*      BCON_INT32(90210), "]", "}", */
-                     "$or",
-                     "[",
-                     "{",
-                     "age",
-                     "{",
-                     "$lt",
-                     BCON_INT32 (18),
-                     "}",
-                     "}",
-                     "{",
-                     "age",
-                     "{",
-                     "$gt",
-                     BCON_INT32 (45),
-                     "}",
-                     "}",
-                     "]");
-
-   matcher = mongoc_matcher_new (query, &error);
-
-   BSON_ASSERT (matcher);
-
-   _mongoc_matcher_op_to_bson (matcher->optree, &matcher_query);
-
-#if 0
-   {
-      char *out = bson_as_canonical_extended_json(&matcher_query, NULL);
-      fprintf(stderr, "bson: %s\n", out);
-      bson_free(out);
-   }
-#endif
-
-   to_match = BCON_NEW ("city",
-                        "New York",
-                        "state",
-                        "New York",
-                        "favorite color",
-                        "blue",
-                        "zip",
-                        BCON_INT32 (11201),
-                        "age",
-                        BCON_INT32 (65));
-
-   BSON_ASSERT (mongoc_matcher_match (matcher, to_match));
-
-   should_fail = BCON_NEW ("city",
-                           "New York",
-                           "state",
-                           "New York",
-                           "favorite color",
-                           "blue",
-                           "zip",
-                           BCON_INT32 (99999),
-                           "age",
-                           BCON_INT32 (30));
-
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-
-   bson_destroy (query);
-   bson_destroy (to_match);
-   bson_destroy (should_fail);
-   bson_destroy (&matcher_query);
-
-   mongoc_matcher_destroy (matcher);
-}
-
-static void
-test_mongoc_matcher_array (void)
-{
-   bson_t *query;
-   bson_t *to_match;
-   bson_t *should_fail;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-
-   query = BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), "]");
-   matcher = mongoc_matcher_new (query, &error);
-   BSON_ASSERT (matcher);
-
-   /* query matches itself */
-   BSON_ASSERT (mongoc_matcher_match (matcher, query));
-
-   to_match = BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), "]", "b", "whatever");
-   BSON_ASSERT (mongoc_matcher_match (matcher, to_match));
-
-   /* query {a: [1, 2]} doesn't match {a: 1} */
-   should_fail = BCON_NEW ("a", BCON_INT32 (1));
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-   bson_destroy (should_fail);
-
-   /* query {a: [1, 2]} doesn't match {a: [2, 1]} */
-   should_fail = BCON_NEW ("a", "[", BCON_INT32 (2), BCON_INT32 (1), "]");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-   bson_destroy (should_fail);
-
-   /* query {a: [1, 2]} doesn't match {a: [1, 2, 3]} */
-   should_fail = BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-   bson_destroy (should_fail);
-
-   /* query {a: [1, 2]} doesn't match {a: [1]} */
-   should_fail = BCON_NEW ("a", "[", BCON_INT32 (1), "]");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-
-   bson_destroy (to_match);
-   mongoc_matcher_destroy (matcher);
-   bson_destroy (query);
-
-   /* empty array */
-   query = BCON_NEW ("a", "[", "]");
-
-   /* {a: []} matches itself */
-   matcher = mongoc_matcher_new (query, &error);
-   BSON_ASSERT (matcher);
-
-   /* query {a: []} matches {a: [], b: "whatever"} */
-   to_match = BCON_NEW ("a", "[", "]", "b", "whatever");
-   BSON_ASSERT (mongoc_matcher_match (matcher, query));
-   BSON_ASSERT (mongoc_matcher_match (matcher, to_match));
-
-   /* query {a: []} doesn't match {a: [1]} */
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-   bson_destroy (should_fail);
-
-   /* query {a: []} doesn't match empty document */
-   should_fail = bson_new ();
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-
-   bson_destroy (should_fail);
-
-   /* query {a: []} doesn't match {a: null} */
-   should_fail = BCON_NEW ("a", BCON_NULL);
-   BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail));
-
-   bson_destroy (should_fail);
-   bson_destroy (query);
-   bson_destroy (to_match);
-   mongoc_matcher_destroy (matcher);
-}
-
-
-typedef struct compare_check {
-   const char *op;
-   int32_t doc;
-   int32_t query;
-   bool expected;
-} compare_check;
-
-
-static void
-test_mongoc_matcher_compare (void)
-{
-   mongoc_matcher_t *matcher;
-   compare_check checks[] = {{"$gt", 2, 2, false},
-                             {"$gte", 2, 2, true},
-                             {"$lt", 2, 2, false},
-                             {"$lte", 2, 2, true},
-                             {"$ne", 2, 2, false},
-                             {NULL}};
-   bson_t *doc;
-   bson_t *q;
-   int i;
-
-   for (i = 0; checks[i].op; i++) {
-      doc = BCON_NEW ("a", BCON_INT32 (checks[i].doc));
-      q = BCON_NEW ("a", "{", checks[i].op, BCON_INT32 (checks[i].query), "}");
-      matcher = mongoc_matcher_new (q, NULL);
-      BSON_ASSERT (matcher);
-      BSON_ASSERT (mongoc_matcher_match (matcher, doc) == checks[i].expected);
-      bson_destroy (q);
-      bson_destroy (doc);
-      mongoc_matcher_destroy (matcher);
-   }
-}
-
-
-typedef struct {
-   const char *spec;
-   const char *doc;
-   bool match;
-} logic_op_test_t;
-
-
-static void
-test_mongoc_matcher_logic_ops (void)
-{
-   logic_op_test_t tests[] = {
-      {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1}", true},
-      {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"b\": 2}", true},
-      {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 3}", false},
-      {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": 3}", true},
-      {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": -2}", true},
-      {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": 0}", false},
-      {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1, \"b\": 2}", true},
-      {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1, \"b\": 1}", false},
-      {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1}", false},
-      {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"b\": 2}", false},
-      {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": 0}", true},
-      {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": -2}", false},
-      {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": 1}", false},
-   };
-
-   int n_tests = sizeof tests / sizeof (logic_op_test_t);
-   int i;
-   logic_op_test_t test;
-   bson_t *spec;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-   bson_t *doc;
-   bool r;
-
-   for (i = 0; i < n_tests; i++) {
-      test = tests[i];
-      spec = bson_new_from_json ((uint8_t *) test.spec, -1, &error);
-      if (!spec) {
-         test_error ("couldn't parse JSON query:\n\n%s\n\n%s", test.spec, error.message);
-      }
-
-      matcher = mongoc_matcher_new (spec, &error);
-      BSON_ASSERT (matcher);
-
-      doc = bson_new_from_json ((uint8_t *) test.doc, -1, &error);
-      if (!doc) {
-         test_error ("couldn't parse JSON document:\n\n%s\n\n%s", test.doc, error.message);
-      }
-
-      r = mongoc_matcher_match (matcher, doc);
-      if (test.match != r) {
-         test_error ("query:\n\n%s\n\nshould %shave matched:\n\n%s", test.match ? "" : "not ", test.spec, test.doc);
-      }
-
-      mongoc_matcher_destroy (matcher);
-      bson_destroy (doc);
-      bson_destroy (spec);
-   }
-}
-
-
-static void
-test_mongoc_matcher_bad_spec (void)
-{
-   bson_t *spec;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-
-   spec = BCON_NEW ("name", "{", "$abc", "invalid", "}");
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (!matcher);
-   BSON_ASSERT (error.domain == MONGOC_ERROR_MATCHER);
-   BSON_ASSERT (error.code == MONGOC_ERROR_MATCHER_INVALID);
-   bson_destroy (spec);
-
-   spec = BCON_NEW ("name", "{", "$or", "", "}");
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (!matcher);
-   BSON_ASSERT (error.domain == MONGOC_ERROR_MATCHER);
-   BSON_ASSERT (error.code == MONGOC_ERROR_MATCHER_INVALID);
-   bson_destroy (spec);
-}
-
-
-static void
-test_mongoc_matcher_eq_utf8 (void)
-{
-   bson_t *doc;
-   bson_t *spec;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-   bool r;
-
-   spec = BCON_NEW ("hello", "world");
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, spec);
-   BSON_ASSERT (r);
-   bson_destroy (spec);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", "world");
-   doc = BCON_NEW ("hello", BCON_NULL);
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (!r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", "world");
-   doc = BCON_NEW ("hello", BCON_UNDEFINED);
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (!r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-}
-
-
-static void
-test_mongoc_matcher_eq_int32 (void)
-{
-   bson_t *spec;
-   bson_t *doc;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-   bool r;
-
-   spec = BCON_NEW ("hello", BCON_INT32 (1234));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, spec);
-   BSON_ASSERT (r);
-   bson_destroy (spec);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", BCON_INT32 (1234));
-   doc = BCON_NEW ("hello", BCON_INT64 (1234));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", BCON_INT32 (1234));
-   doc = BCON_NEW ("hello", BCON_INT64 (4321));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (!r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-}
-
-
-static void
-test_mongoc_matcher_eq_int64 (void)
-{
-   bson_t *spec;
-   bson_t *doc;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-   bool r;
-
-   spec = BCON_NEW ("hello", BCON_INT64 (1234));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, spec);
-   BSON_ASSERT (r);
-   bson_destroy (spec);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", BCON_INT64 (1234));
-   doc = BCON_NEW ("hello", BCON_INT64 (1234));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-
-   spec = BCON_NEW ("hello", BCON_INT64 (1234));
-   doc = BCON_NEW ("hello", BCON_INT32 (4321));
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   r = mongoc_matcher_match (matcher, doc);
-   BSON_ASSERT (!r);
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-}
-
-
-static void
-test_mongoc_matcher_eq_doc (void)
-{
-   bson_t *spec;
-   bson_t *doc;
-   bson_error_t error;
-   mongoc_matcher_t *matcher;
-
-   /* {doc: {a: 1}} matches itself */
-   spec = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "}");
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   BSON_ASSERT (mongoc_matcher_match (matcher, spec));
-
-   /* {doc: {a: 1}} matches {doc: {a: 1}, foo: "whatever"} */
-   doc = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "}", "foo", BCON_UTF8 ("whatever"));
-   BSON_ASSERT (mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1}} doesn't match {doc: 1} */
-   doc = BCON_NEW ("doc", BCON_INT32 (1));
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1}} doesn't match {doc: {}} */
-   doc = BCON_NEW ("doc", "{", "}");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1}} doesn't match {doc: {a: 2}} */
-   doc = BCON_NEW ("doc", "{", "a", BCON_INT32 (2), "}");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1}} doesn't match {doc: {b: 1}} */
-   doc = BCON_NEW ("doc", "{", "b", BCON_INT32 (1), "}");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1}} doesn't match {doc: {a: 1, b: 1}} */
-   doc = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "b", BCON_INT32 (1), "}");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (doc);
-
-   /* {doc: {a: 1, b:1}} matches itself */
-   bson_destroy (spec);
-   mongoc_matcher_destroy (matcher);
-   spec = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "b", BCON_INT32 (1), "}");
-   matcher = mongoc_matcher_new (spec, &error);
-   BSON_ASSERT (matcher);
-   BSON_ASSERT (mongoc_matcher_match (matcher, spec));
-
-   /* {doc: {a: 1, b:1}} doesn't match {doc: {a: 1}} */
-   doc = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "}");
-   BSON_ASSERT (!mongoc_matcher_match (matcher, doc));
-   bson_destroy (spec);
-   bson_destroy (doc);
-   mongoc_matcher_destroy (matcher);
-}
-
-
-static void
-test_mongoc_matcher_in_basic (void)
-{
-   mongoc_matcher_t *matcher;
-   bson_error_t error;
-   bool r;
-   bson_t *spec;
-   bson_t doc = BSON_INITIALIZER;
-
-   spec = BCON_NEW ("key", "{", "$in", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]", "}");
-
-   matcher = mongoc_matcher_new (spec, &error);
-   r = mongoc_matcher_match (matcher, &doc);
-   ASSERT (!r);
-
-   bson_reinit (&doc);
-   bson_append_int32 (&doc, "key", 3, 1);
-   r = mongoc_matcher_match (matcher, &doc);
-   ASSERT (r);
-
-   bson_reinit (&doc);
-   bson_append_int32 (&doc, "key", 3, 2);
-   r = mongoc_matcher_match (matcher, &doc);
-   ASSERT (r);
-
-   bson_reinit (&doc);
-   bson_append_int32 (&doc, "key", 3, 3);
-   r = mongoc_matcher_match (matcher, &doc);
-   ASSERT (r);
-
-   bson_reinit (&doc);
-   bson_append_int32 (&doc, "key", 3, 4);
-   r = mongoc_matcher_match (matcher, &doc);
-   ASSERT (!r);
-
-   bson_destroy (&doc);
-   bson_destroy (spec);
-   mongoc_matcher_destroy (matcher);
-}
-
-END_IGNORE_DEPRECATIONS
-
-void
-test_matcher_install (TestSuite *suite)
-{
-   TestSuite_Add (suite, "/Matcher/basic", test_mongoc_matcher_basic);
-   TestSuite_Add (suite, "/Matcher/array", test_mongoc_matcher_array);
-   TestSuite_Add (suite, "/Matcher/compare", test_mongoc_matcher_compare);
-   TestSuite_Add (suite, "/Matcher/logic", test_mongoc_matcher_logic_ops);
-   TestSuite_Add (suite, "/Matcher/bad_spec", test_mongoc_matcher_bad_spec);
-   TestSuite_Add (suite, "/Matcher/eq/utf8", test_mongoc_matcher_eq_utf8);
-   TestSuite_Add (suite, "/Matcher/eq/int32", test_mongoc_matcher_eq_int32);
-   TestSuite_Add (suite, "/Matcher/eq/int64", test_mongoc_matcher_eq_int64);
-   TestSuite_Add (suite, "/Matcher/eq/doc", test_mongoc_matcher_eq_doc);
-   TestSuite_Add (suite, "/Matcher/in/basic", test_mongoc_matcher_in_basic);
-}
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-max-staleness.c 2.0.2-1/src/libmongoc/tests/test-mongoc-max-staleness.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-max-staleness.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-max-staleness.c	2025-06-19 15:42:22.000000000 +0000
@@ -10,9 +10,6 @@
 #include "mock_server/mock-server.h"
 #include "mock_server/future-functions.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "client-test-max-staleness"
-
 
 static int64_t
 get_max_staleness (const mongoc_client_t *client)
@@ -120,7 +117,7 @@ test_mongos_max_staleness_read_pref (voi
    /* count command with mode "secondary", no MONGOC_URI_MAXSTALENESSSECONDS. */
    prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
    mongoc_collection_set_read_prefs (collection, prefs);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, NULL, NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
@@ -140,7 +137,7 @@ test_mongos_max_staleness_read_pref (voi
    mongoc_collection_set_read_prefs (collection, prefs);
 
    mongoc_collection_set_read_prefs (collection, prefs);
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, NULL, NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
@@ -160,7 +157,7 @@ test_mongos_max_staleness_read_pref (voi
    mongoc_read_prefs_set_max_staleness_seconds (prefs, MONGOC_NO_MAX_STALENESS);
    mongoc_collection_set_read_prefs (collection, prefs);
 
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, NULL, NULL, &error);
    request = mock_server_receives_msg (
       server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', '$readPreference': {'mode': 'secondaryPreferred'}}"));
 
@@ -175,7 +172,7 @@ test_mongos_max_staleness_read_pref (voi
    mongoc_read_prefs_set_max_staleness_seconds (prefs, 1);
    mongoc_collection_set_read_prefs (collection, prefs);
 
-   future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
+   future = future_collection_estimated_document_count (collection, NULL, NULL, NULL, &error);
    request = mock_server_receives_msg (server,
                                        MONGOC_MSG_NONE,
                                        tmp_bson ("{'$db': 'db',"
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-opts.c 2.0.2-1/src/libmongoc/tests/test-mongoc-opts.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-opts.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-opts.c	2025-06-19 15:42:22.000000000 +0000
@@ -425,15 +425,6 @@ collection_watch (func_ctx_t *ctx, bson_
 
 
 static future_t *
-count (func_ctx_t *ctx, bson_t *cmd)
-{
-   BSON_APPEND_UTF8 (cmd, "count", "collection");
-   return future_collection_count_with_opts (
-      ctx->collection, MONGOC_QUERY_NONE, NULL, 0, 0, ctx->opts, ctx->prefs, &ctx->error);
-}
-
-
-static future_t *
 count_documents (func_ctx_t *ctx, bson_t *cmd)
 {
    BSON_APPEND_UTF8 (cmd, "aggregate", "collection");
@@ -441,13 +432,28 @@ count_documents (func_ctx_t *ctx, bson_t
       ctx->collection, tmp_bson ("{}"), ctx->opts, ctx->prefs, NULL, &ctx->error);
 }
 
+static void
+destroy_index_models (void *data)
+{
+   mongoc_index_model_t **ptr = (mongoc_index_model_t **) data;
+   while (NULL != *ptr) {
+      mongoc_index_model_destroy (*ptr);
+      ptr++;
+   }
+}
 
 static future_t *
 create_index (func_ctx_t *ctx, bson_t *cmd)
 {
    BSON_APPEND_UTF8 (cmd, "createIndexes", "collection");
-   return future_collection_create_index_with_opts (
-      ctx->collection, tmp_bson ("{}"), NULL, ctx->opts, NULL, &ctx->error);
+   mongoc_index_model_t *im = mongoc_index_model_new (tmp_bson ("{'foo': 'bar'}"), NULL);
+   // Allocate a list of `mongoc_index_model_t` to extend the lifetime until the future resolves.
+   mongoc_index_model_t **ims = bson_malloc0 (sizeof (mongoc_index_model_t *) * 2);
+   ims[0] = im;
+   ims[1] = NULL; // NULL-terimate.
+   ctx->data = ims;
+   ctx->destructor = destroy_index_models; // Destroy `mongoc_index_model_t` after future returns.
+   return future_collection_create_indexes_with_opts (ctx->collection, ims, 1, ctx->opts, NULL, &ctx->error);
 }
 
 
@@ -840,11 +846,9 @@ static opt_inheritance_test_t gInheritan
    OPT_TEST (COLL, collection_read_write_cmd, WRITE_CONCERN),
    OPT_TEST (COLL, collection_watch, READ_CONCERN),
    OPT_TEST (COLL, collection_write_cmd, WRITE_CONCERN),
-   OPT_TEST (COLL, count, READ_CONCERN),
-   OPT_TEST (COLL, count, READ_PREFS),
    OPT_TEST (COLL, count_documents, READ_CONCERN),
    OPT_TEST (COLL, count_documents, READ_PREFS),
-   OPT_TEST (COLL, create_index, WRITE_CONCERN),
+   // OPT_TEST (COLL, create_index, WRITE_CONCERN), Known issue: CDRIVER-5945
    OPT_TEST (COLL, drop_index, WRITE_CONCERN),
    OPT_TEST (COLL, estimated_document_count, READ_CONCERN),
    OPT_TEST (COLL, estimated_document_count, READ_PREFS),
@@ -891,6 +895,8 @@ install_inheritance_tests (TestSuite *su
 
       bson_free (name);
    }
+
+   BSON_UNUSED (create_index); // Silence unused warning. Remove when resolving CDRIVER-5945.
 }
 
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-read-concern.c 2.0.2-1/src/libmongoc/tests/test-mongoc-read-concern.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-read-concern.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-read-concern.c	2025-06-19 15:42:22.000000000 +0000
@@ -164,18 +164,6 @@ _test_read_concern_wire_version (bool ex
 
    future_destroy (future);
 
-   /*
-    * count
-    */
-   future =
-      future_collection_count_with_opts (collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, &opts, NULL, &error);
-   request =
-      mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}"));
-   reply_to_request_simple (request, "{'ok': 1, 'n': 1}");
-   request_destroy (request);
-   ASSERT_CMPINT64 (future_get_int64_t (future), ==, (int64_t) 1);
-
-   future_destroy (future);
    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-read-prefs.c 2.0.2-1/src/libmongoc/tests/test-mongoc-read-prefs.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-read-prefs.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-read-prefs.c	2025-06-19 15:42:22.000000000 +0000
@@ -34,7 +34,7 @@ _test_op_msg (const mongoc_uri_t *uri,
    client = test_framework_client_new_from_uri (uri, NULL);
    collection = mongoc_client_get_collection (client, "test", "test");
 
-   cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 1, 0, tmp_bson (query_or_cmd), NULL, read_prefs);
+   cursor = mongoc_collection_find_with_opts (collection, tmp_bson (query_or_cmd), NULL, read_prefs);
 
    future = future_cursor_next (cursor, &doc);
    request = mock_server_receives_msg (server, 0, tmp_bson (expected_find));
@@ -58,49 +58,6 @@ _test_op_msg (const mongoc_uri_t *uri,
 
 
 static void
-_test_command (const mongoc_uri_t *uri,
-               mock_server_t *server,
-               const char *command,
-               mongoc_read_prefs_t *read_prefs,
-               const char *expected_cmd)
-{
-   mongoc_client_t *client;
-   mongoc_collection_t *collection;
-   mongoc_cursor_t *cursor;
-   const bson_t *doc;
-   bson_t b = BSON_INITIALIZER;
-   future_t *future;
-   request_t *request;
-
-   client = test_framework_client_new_from_uri (uri, NULL);
-   collection = mongoc_client_get_collection (client, "test", "test");
-   mongoc_collection_set_read_prefs (collection, read_prefs);
-
-   cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 1, 0, tmp_bson (command), NULL, read_prefs);
-
-   future = future_cursor_next (cursor, &doc);
-
-   request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_cmd));
-
-   reply_to_request (request,
-                     MONGOC_REPLY_NONE, /* flags */
-                     0,                 /* cursorId */
-                     0,                 /* startingFrom */
-                     1,                 /* numberReturned */
-                     "{'ok': 1}");
-
-   /* mongoc_cursor_next returned true */
-   BSON_ASSERT (future_get_bool (future));
-
-   request_destroy (request);
-   future_destroy (future);
-   mongoc_cursor_destroy (cursor);
-   mongoc_collection_destroy (collection);
-   mongoc_client_destroy (client);
-   bson_destroy (&b);
-}
-
-static void
 _test_command_simple (const mongoc_uri_t *uri,
                       mock_server_t *server,
                       const char *command,
@@ -242,8 +199,6 @@ _test_read_prefs_op_msg (read_pref_test_
    uri = _get_uri (server, test_type);
 
    if (_can_be_command (query_or_cmd)) {
-      _test_command (uri, server, query_or_cmd, read_prefs, expected_cmd);
-
       _test_command_simple (uri, server, query_or_cmd, read_prefs, expected_cmd);
    }
 
@@ -448,13 +403,6 @@ test_read_prefs_mongos_secondary (void)
                             "{'find': 'test', 'filter':  {'a': 1},"
                             " '$readPreference': {'mode': 'secondary'}}");
 
-   _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS,
-                            read_prefs,
-                            "{'$query': {'a': 1}}",
-                            "{'$query': {'a': 1}, '$readPreference': {'mode': 'secondary'}}",
-                            "{'find': 'test', 'filter':  {'a': 1},"
-                            " '$readPreference': {'mode': 'secondary'}}");
-
    mongoc_read_prefs_destroy (read_prefs);
 }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-retryable-reads.c 2.0.2-1/src/libmongoc/tests/test-mongoc-retryable-reads.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-retryable-reads.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-retryable-reads.c	2025-06-19 15:42:22.000000000 +0000
@@ -79,9 +79,7 @@ test_cmd_helpers (void *ctx)
    bson_t reply;
    bson_error_t error;
    bson_iter_t iter;
-   mongoc_cursor_t *cursor;
    mongoc_database_t *database;
-   const bson_t *doc;
 
    BSON_UNUSED (ctx);
 
@@ -172,30 +170,6 @@ test_cmd_helpers (void *ctx)
    ASSERT (!mongoc_client_command_simple_with_server_id (client, "test", cmd, NULL, server_id, NULL, &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command");
 
-
-   /* deprecated command helpers (which goes through cursor logic) function must
-    * not retry. */
-   _set_failpoint (client);
-   cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL);
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command");
-   mongoc_cursor_destroy (cursor);
-
-   _set_failpoint (client);
-   cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL);
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command");
-   mongoc_cursor_destroy (cursor);
-
-   _set_failpoint (client);
-   cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL);
-   ASSERT (!mongoc_cursor_next (cursor, &doc));
-   ASSERT (mongoc_cursor_error (cursor, &error));
-   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command");
-   mongoc_cursor_destroy (cursor);
-
    ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);
 
    deactivate_fail_points (client, server_id);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-sdam-monitoring.c 2.0.2-1/src/libmongoc/tests/test-mongoc-sdam-monitoring.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-sdam-monitoring.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-sdam-monitoring.c	2025-06-19 15:42:22.000000000 +0000
@@ -9,7 +9,7 @@
 #include "mock_server/future.h"
 #include "mock_server/future-functions.h"
 #include "json-test-monitoring.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #ifdef BSON_HAVE_STRINGS_H
 #include <strings.h>
@@ -135,7 +135,7 @@ td_to_bson (const mongoc_topology_descri
    mongoc_set_t const *servers_set = mc_tpld_servers_const (td);
 
    for (size_t i = 0; i < servers_set->items_len; i++) {
-      BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, i));
+      BSON_ASSERT (mlib_in_range (uint32_t, i));
       bson_uint32_to_string ((uint32_t) i, &key, str, sizeof str);
       sd_to_bson (mongoc_set_get_item_const (servers_set, i), &server);
       BSON_APPEND_DOCUMENT (&servers, key, &server);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-sdam.c 2.0.2-1/src/libmongoc/tests/test-mongoc-sdam.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-sdam.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-sdam.c	2025-06-19 15:42:22.000000000 +0000
@@ -533,7 +533,7 @@ test_topology_discovery (void *ctx)
    mongoc_client_t *client;
    mongoc_read_prefs_t *prefs;
    mongoc_server_description_t *sd_secondary;
-   mongoc_host_list_t *hl_secondary;
+   const mongoc_host_list_t *hl_secondary;
    mongoc_collection_t *collection;
    bson_t doc = BSON_INITIALIZER;
    bson_t reply;
@@ -597,7 +597,7 @@ test_direct_connection (void *ctx)
    mongoc_client_t *client;
    mongoc_read_prefs_t *prefs;
    mongoc_server_description_t *sd_secondary;
-   mongoc_host_list_t *hl_secondary;
+   const mongoc_host_list_t *hl_secondary;
    mongoc_collection_t *collection;
    bson_t doc = BSON_INITIALIZER;
    bson_t reply;
@@ -662,7 +662,7 @@ test_existing_behavior (void *ctx)
    mongoc_client_t *client;
    mongoc_read_prefs_t *prefs;
    mongoc_server_description_t *sd_secondary;
-   mongoc_host_list_t *hl_secondary;
+   const mongoc_host_list_t *hl_secondary;
    mongoc_collection_t *collection;
    bson_t doc = BSON_INITIALIZER;
    bson_t reply;
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-socket.c 2.0.2-1/src/libmongoc/tests/test-mongoc-socket.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-socket.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-socket.c	2025-06-19 15:42:22.000000000 +0000
@@ -6,13 +6,10 @@
 #include <mongoc/mongoc-thread-private.h>
 #include <mongoc/mongoc-errno-private.h>
 #include "TestSuite.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 #include "test-libmongoc.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "socket-test"
-
 #define TIMEOUT 10000
 #define WAIT 1000
 
@@ -232,10 +229,10 @@ static BSON_THREAD_FUN (sendv_test_serve
 
    /* Start reading everything off the socket to unblock the client */
    do {
-      ASSERT (mcommon_in_range_signed (size_t, amount));
+      ASSERT (mlib_in_range (size_t, amount));
       const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT);
       if (r > 0) {
-         ASSERT (mcommon_in_range_signed (int, r));
+         ASSERT (mlib_in_range (int, r));
          amount -= (int) r;
       }
    } while (amount > 0);
@@ -252,10 +249,10 @@ static BSON_THREAD_FUN (sendv_test_serve
    bson_mutex_unlock (&data->cond_mutex);
 
    do {
-      ASSERT (mcommon_in_range_signed (size_t, amount));
+      ASSERT (mlib_in_range (size_t, amount));
       const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT);
       if (r > 0) {
-         ASSERT (mcommon_in_range_signed (int, r));
+         ASSERT (mlib_in_range (int, r));
          amount -= (int) r;
       }
    } while (amount > 0);
@@ -311,11 +308,11 @@ static BSON_THREAD_FUN (sendv_test_clien
       const ssize_t r = mongoc_stream_writev (stream, &iov, 1, WAIT);
 
       if (r > 0) {
-         BSON_ASSERT (mcommon_in_range_signed (int, r));
+         BSON_ASSERT (mlib_in_range (int, r));
          amount += (int) r;
       }
 
-      if (mcommon_cmp_not_equal_su (r, gFourMB)) {
+      if (mlib_cmp (r, !=, gFourMB)) {
          if (!done) {
             bson_mutex_lock (&data->cond_mutex);
             data->amount = amount;
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-stream-tls-error.c 2.0.2-1/src/libmongoc/tests/test-mongoc-stream-tls-error.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-stream-tls-error.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-stream-tls-error.c	2025-06-19 15:42:22.000000000 +0000
@@ -14,8 +14,7 @@
 
 #define TIMEOUT 10000 /* milliseconds */
 
-#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL) && \
-   !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
 /** run as a child thread by test_mongoc_tls_hangup
  *
  * It:
@@ -331,7 +330,7 @@ test_mongoc_tls_handshake_stall (void)
 }
 
 #endif /* !MONGOC_ENABLE_SSL_SECURE_TRANSPORT */
-#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL && !MONGOC_ENABLE_SSL_LIBRESSL */
+#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL */
 
 /* TLS stream should be NULL and base stream should still be valid, and error
  * messages should be consistent across TLS libs. Until CDRIVER-2844, just
@@ -369,7 +368,7 @@ test_mongoc_tls_load_files (void)
 void
 test_stream_tls_error_install (TestSuite *suite)
 {
-#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL)
+#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
 #if !defined(__APPLE__)
    TestSuite_Add (suite, "/TLS/hangup", test_mongoc_tls_hangup);
 #endif
@@ -378,6 +377,6 @@ test_stream_tls_error_install (TestSuite
 #if !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
    TestSuite_Add (suite, "/TLS/handshake_stall", test_mongoc_tls_handshake_stall);
 #endif
-#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL && !MONGOC_ENABLE_SSL_LIBRESSL */
+#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL */
    TestSuite_Add (suite, "/TLS/load_files", test_mongoc_tls_load_files);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-stream-tls.c 2.0.2-1/src/libmongoc/tests/test-mongoc-stream-tls.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-stream-tls.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-stream-tls.c	2025-06-19 15:42:22.000000000 +0000
@@ -10,7 +10,7 @@
 #include "test-libmongoc.h"
 #include "test-conveniences.h"
 
-#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL)
+#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
 
 static void
 test_mongoc_tls_no_certs (void)
@@ -387,7 +387,7 @@ test_mongoc_tls_trust_dir (void)
 }
 #endif
 
-#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL && !MONGOC_ENABLE_SSL_LIBRESSL */
+#endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL */
 
 void
 test_mongoc_tls_insecure_nowarning (void)
@@ -413,7 +413,7 @@ test_mongoc_tls_insecure_nowarning (void
 void
 test_stream_tls_install (TestSuite *suite)
 {
-#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL)
+#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
 
    /* Disable /TLS/commonName on macOS due to CDRIVER-4256. */
 #if !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-stream.c 2.0.2-1/src/libmongoc/tests/test-mongoc-stream.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-stream.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-stream.c	2025-06-19 15:42:22.000000000 +0000
@@ -26,7 +26,7 @@ test_buffered_basic (void)
    iov.iov_len = sizeof buf;
    iov.iov_base = buf;
    r = mongoc_stream_readv (buffered, &iov, 1, iov.iov_len, -1);
-   if (r != iov.iov_len) {
+   if (mlib_cmp (r, !=, iov.iov_len)) {
       char msg[100];
 
       bson_snprintf (msg, 100, "Expected %lld got %llu", (long long) r, (unsigned long long) iov.iov_len);
@@ -57,7 +57,7 @@ test_buffered_oversized (void)
    iov.iov_len = sizeof buf;
    iov.iov_base = buf;
    r = mongoc_stream_readv (buffered, &iov, 1, iov.iov_len, -1);
-   if (r != iov.iov_len) {
+   if (mlib_cmp (r, !=, iov.iov_len)) {
       char msg[100];
 
       bson_snprintf (msg, 100, "Expected %lld got %llu", (long long) r, (unsigned long long) iov.iov_len);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-streamable-hello.c 2.0.2-1/src/libmongoc/tests/test-mongoc-streamable-hello.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-streamable-hello.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-streamable-hello.c	2025-06-19 15:42:22.000000000 +0000
@@ -11,9 +11,6 @@
 #include <mongoc/mongoc-topology-private.h>
 #include <mongoc/mongoc-topology-description-private.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "streamable-hello"
-
 #define TV1 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }"
 #define TV2 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }"
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-description.c 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-description.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-description.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-description.c	2025-06-19 15:42:22.000000000 +0000
@@ -8,9 +8,6 @@
 #include "test-libmongoc.h"
 #include "test-conveniences.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "topology-test"
-
 static void
 _test_has_readable_writable_server (bool pooled)
 {
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-reconcile.c 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-reconcile.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-reconcile.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-reconcile.c	2025-06-19 15:42:22.000000000 +0000
@@ -13,9 +13,6 @@
 #include "test-libmongoc.h"
 #include <common-atomic-private.h>
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "topology-reconcile-test"
-
 
 static mongoc_topology_scanner_node_t *
 get_node (mongoc_topology_t *topology, const char *host_and_port)
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-scanner.c 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-scanner.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-topology-scanner.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-topology-scanner.c	2025-06-19 15:42:22.000000000 +0000
@@ -16,9 +16,6 @@
 #include "test-conveniences.h"
 #include "test-libmongoc.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "topology-scanner-test"
-
 #define TIMEOUT 20000 /* milliseconds */
 #define NSERVERS 10
 
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-topology.c 2.0.2-1/src/libmongoc/tests/test-mongoc-topology.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-topology.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-topology.c	2025-06-19 15:42:22.000000000 +0000
@@ -201,7 +201,7 @@ static void
 assert_topology_state (mongoc_topology_t *topology, mongoc_topology_scanner_state_t state)
 {
    ASSERT (topology);
-   ASSERT (topology->scanner_state == state);
+   ASSERT (mlib_cmp (topology->scanner_state, ==, state));
 }
 
 static void
@@ -2427,7 +2427,7 @@ initiator_fail (const mongoc_uri_t *uri,
    bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "failing in initiator");
    printf ("failing in initiator\n");
 
-   return false;
+   return NULL;
 }
 
 // Test failure in `mongoc_topology_scanner_node_setup` during retry of scanning
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-transactions.c 2.0.2-1/src/libmongoc/tests/test-mongoc-transactions.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-transactions.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-transactions.c	2025-06-19 15:42:22.000000000 +0000
@@ -488,9 +488,9 @@ _test_transient_txn_err (bool hangup)
    TEST_CMD_ERR (mongoc_client_read_write_command_with_opts (client, "db", b, NULL, &opts, &reply, NULL));
    TEST_CMD_ERR (0 < mongoc_collection_count_documents (collection, b, &opts, NULL, &reply, NULL));
 
-   BEGIN_IGNORE_DEPRECATIONS
-   TEST_CMD_ERR (mongoc_collection_create_index_with_opts (collection, b, NULL, &opts, &reply, NULL));
-   END_IGNORE_DEPRECATIONS
+   mongoc_index_model_t *im = mongoc_index_model_new (b, NULL);
+   TEST_CMD_ERR (mongoc_collection_create_indexes_with_opts (collection, &im, 1, &opts, &reply, NULL));
+   mongoc_index_model_destroy (im);
 
    fam = mongoc_find_and_modify_opts_new ();
    mongoc_find_and_modify_opts_append (fam, &opts);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-uri.c 2.0.2-1/src/libmongoc/tests/test-mongoc-uri.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-uri.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-uri.c	2025-06-19 15:42:22.000000000 +0000
@@ -11,21 +11,17 @@
 #include "test-libmongoc.h"
 #include "test-conveniences.h"
 #include <common-string-private.h>
+#include <mlib/loop.h>
 
 static void
 test_mongoc_uri_new (void)
 {
    const mongoc_host_list_t *hosts;
    const bson_t *options;
-   const bson_t *credentials;
    const bson_t *read_prefs_tags;
    const mongoc_read_prefs_t *read_prefs;
-   bson_t properties;
    mongoc_uri_t *uri;
    bson_iter_t iter;
-   bson_iter_t child;
-
-   capture_logs (true);
 
    /* bad uris */
    ASSERT (!mongoc_uri_new ("mongodb://"));
@@ -73,21 +69,21 @@ test_mongoc_uri_new (void)
    ASSERT (!mongoc_uri_new ("mongodb+srv://local1/?directConnection=true"));
 
    uri = mongoc_uri_new ("mongodb://[::1]:27888,[::2]:27999/?ipv6=true&" MONGOC_URI_SAFE "=true");
-   BSON_ASSERT (uri);
+   ASSERT (uri);
    hosts = mongoc_uri_get_hosts (uri);
-   BSON_ASSERT (hosts);
+   ASSERT (hosts);
    ASSERT_CMPSTR (hosts->host, "::1");
-   BSON_ASSERT (hosts->port == 27888);
+   ASSERT_CMPUINT16 (hosts->port, ==, 27888);
    ASSERT_CMPSTR (hosts->host_and_port, "[::1]:27888");
    mongoc_uri_destroy (uri);
 
    /* should recognize IPv6 "scope" like "::1%lo0", with % escaped  */
    uri = mongoc_uri_new ("mongodb://[::1%25lo0]");
-   BSON_ASSERT (uri);
+   ASSERT (uri);
    hosts = mongoc_uri_get_hosts (uri);
-   BSON_ASSERT (hosts);
+   ASSERT (hosts);
    ASSERT_CMPSTR (hosts->host, "::1%lo0");
-   BSON_ASSERT (hosts->port == 27017);
+   ASSERT_CMPUINT16 (hosts->port, ==, 27017);
    ASSERT_CMPSTR (hosts->host_and_port, "[::1%lo0]:27017");
    mongoc_uri_destroy (uri);
 
@@ -97,9 +93,9 @@ test_mongoc_uri_new (void)
 
    /* should normalize to lowercase */
    uri = mongoc_uri_new ("mongodb://cRaZyHoStNaMe");
-   BSON_ASSERT (uri);
+   ASSERT (uri);
    hosts = mongoc_uri_get_hosts (uri);
-   BSON_ASSERT (hosts);
+   ASSERT (hosts);
    ASSERT_CMPSTR (hosts->host, "crazyhostname");
    mongoc_uri_destroy (uri);
 
@@ -113,13 +109,12 @@ test_mongoc_uri_new (void)
    ASSERT (hosts);
    ASSERT (!hosts->next);
    ASSERT_CMPSTR (hosts->host, "localhost");
-   ASSERT_CMPINT (hosts->port, ==, 27017);
+   ASSERT_CMPUINT16 (hosts->port, ==, 27017);
    ASSERT_CMPSTR (hosts->host_and_port, "localhost:27017");
    ASSERT_CMPSTR (mongoc_uri_get_database (uri), "test");
    options = mongoc_uri_get_options (uri);
    ASSERT (options);
-   ASSERT (bson_iter_init_find (&iter, options, "replicaset"));
-   ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), "foo");
+   ASSERT_EQUAL_BSON (tmp_bson ("{'replicaset': 'foo'}"), options);
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://local1,local2:999,local3/?replicaset=foo");
@@ -130,11 +125,11 @@ test_mongoc_uri_new (void)
    ASSERT (hosts->next->next);
    ASSERT (!hosts->next->next->next);
    ASSERT_CMPSTR (hosts->host, "local1");
-   ASSERT_CMPINT (hosts->port, ==, 27017);
+   ASSERT_CMPUINT16 (hosts->port, ==, 27017);
    ASSERT_CMPSTR (hosts->next->host, "local2");
-   ASSERT_CMPINT (hosts->next->port, ==, 999);
+   ASSERT_CMPUINT16 (hosts->next->port, ==, 999);
    ASSERT_CMPSTR (hosts->next->next->host, "local3");
-   ASSERT_CMPINT (hosts->next->next->port, ==, 27017);
+   ASSERT_CMPUINT16 (hosts->next->next->port, ==, 27017);
    options = mongoc_uri_get_options (uri);
    ASSERT (options);
    ASSERT (bson_iter_init_find (&iter, options, "replicaset"));
@@ -150,33 +145,13 @@ test_mongoc_uri_new (void)
    ASSERT (read_prefs);
    read_prefs_tags = mongoc_read_prefs_get_tags (read_prefs);
    ASSERT (read_prefs_tags);
-   ASSERT_CMPINT (bson_count_keys (read_prefs_tags), ==, 2);
-   ASSERT (bson_iter_init_find (&iter, read_prefs_tags, "0"));
-   ASSERT (BSON_ITER_HOLDS_DOCUMENT (&iter));
-   ASSERT (bson_iter_recurse (&iter, &child));
-   ASSERT (bson_iter_next (&child));
-   ASSERT_CMPSTR (bson_iter_key (&child), "dc");
-   ASSERT_CMPSTR (bson_iter_utf8 (&child, NULL), "ny");
-   ASSERT (!bson_iter_next (&child));
-   ASSERT (bson_iter_next (&iter));
-   ASSERT (BSON_ITER_HOLDS_DOCUMENT (&iter));
-   ASSERT (bson_iter_recurse (&iter, &child));
-   ASSERT (!bson_iter_next (&child));
-   ASSERT (!bson_iter_next (&iter));
+   ASSERT_EQUAL_BSON (tmp_bson ("[{'dc': 'ny'}, {}]"), read_prefs_tags);
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SAFE "=false&" MONGOC_URI_JOURNAL "=false");
    options = mongoc_uri_get_options (uri);
    ASSERT (options);
-   ASSERT_CMPINT (bson_count_keys (options), ==, 2);
-   ASSERT (bson_iter_init (&iter, options));
-   ASSERT (bson_iter_find_case (&iter, "" MONGOC_URI_SAFE ""));
-   ASSERT (BSON_ITER_HOLDS_BOOL (&iter));
-   ASSERT (!bson_iter_bool (&iter));
-   ASSERT (bson_iter_find_case (&iter, MONGOC_URI_JOURNAL));
-   ASSERT (BSON_ITER_HOLDS_BOOL (&iter));
-   ASSERT (!bson_iter_bool (&iter));
-   ASSERT (!bson_iter_next (&iter));
+   ASSERT_EQUAL_BSON (tmp_bson ("{'%s': false, '%s': false}", MONGOC_URI_SAFE, MONGOC_URI_JOURNAL), options);
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://%2Ftmp%2Fmongodb-27017.sock/?" MONGOC_URI_TLS "=false");
@@ -257,11 +232,19 @@ test_mongoc_uri_new (void)
    mongoc_uri_destroy (uri);
 
    /* should recognize a question mark in the userpass instead of mistaking it for the beginning of options */
-   uri = mongoc_uri_new ("mongodb://us?r:pa?s@localhost?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA1");
+   uri = mongoc_uri_new ("mongodb://us?r:pa?s@localhost?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA-1");
    ASSERT (uri);
    ASSERT_CMPSTR (mongoc_uri_get_username (uri), "us?r");
    ASSERT_CMPSTR (mongoc_uri_get_password (uri), "pa?s");
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA1");
+   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA-1");
+   mongoc_uri_destroy (uri);
+
+   /* should recognize many reserved characters in the userpass for backward compatibility */
+   uri = mongoc_uri_new ("mongodb://user?#[]:pass?#[]@localhost?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA-1");
+   ASSERT (uri);
+   ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user?#[]");
+   ASSERT_CMPSTR (mongoc_uri_get_password (uri), "pass?#[]");
+   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA-1");
    mongoc_uri_destroy (uri);
 
    /* should fail on invalid escaped characters */
@@ -269,167 +252,1004 @@ test_mongoc_uri_new (void)
    uri = mongoc_uri_new ("mongodb://u%ser:pwd@localhost:27017");
    ASSERT (!uri);
    ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence");
+   capture_logs (false);
 
+   capture_logs (true);
    uri = mongoc_uri_new ("mongodb://user:p%wd@localhost:27017");
    ASSERT (!uri);
    ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence");
+   capture_logs (false);
 
+   capture_logs (true);
    uri = mongoc_uri_new ("mongodb://user:pwd@local% host:27017");
    ASSERT (!uri);
    ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence");
+   capture_logs (false);
 
    uri = mongoc_uri_new ("mongodb://christian%40realm@localhost:27017/?replicaset=%20");
    ASSERT (uri);
    options = mongoc_uri_get_options (uri);
    ASSERT (options);
-   ASSERT (bson_iter_init_find (&iter, options, "replicaset"));
-   ASSERT (BSON_ITER_HOLDS_UTF8 (&iter));
-   ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), " ");
+   ASSERT_EQUAL_BSON (tmp_bson ("{'replicaset': ' '}"), options);
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://christian%40realm@[::6]:27017/?replicaset=%20");
    ASSERT (uri);
    options = mongoc_uri_get_options (uri);
    ASSERT (options);
-   ASSERT (bson_iter_init_find (&iter, options, "replicaset"));
-   ASSERT (BSON_ITER_HOLDS_UTF8 (&iter));
-   ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), " ");
+   ASSERT_EQUAL_BSON (tmp_bson ("{'replicaset': ' '}"), options);
    mongoc_uri_destroy (uri);
 
-   /* GSSAPI-specific options */
-
-   /* should recognize the GSSAPI mechanism, and use $external as source */
-   uri = mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/"
-                         "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI");
+   // Should warn on unsupported `minPoolSize`. `minPoolSize` was removed in CDRIVER-2390.
+   capture_logs (true);
+   uri = mongoc_uri_new ("mongodb://host/?minPoolSize=1");
    ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "GSSAPI");
-   /*ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");*/
+   ASSERT_CAPTURED_LOG (
+      "setting URI option minPoolSize=1", MONGOC_LOG_LEVEL_WARNING, "Unsupported URI option \"minpoolsize\"");
    mongoc_uri_destroy (uri);
+   capture_logs (false);
+}
 
-   /* use $external as source when db is specified */
-   uri = mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/foo"
-                         "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
-   mongoc_uri_destroy (uri);
+static void
+_auth_mechanism_username_required (const char *mechanism)
+{
+   // None.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("'%s' authentication mechanism requires a username", mechanism));
+      mongoc_uri_destroy (uri);
+   }
 
-   /* should not accept " MONGOC_URI_AUTHSOURCE " other than $external */
-   ASSERT (!mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/"
-                            "foo?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHSOURCE "=bar"));
+   // Empty.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("'%s' authentication mechanism requires a username", mechanism));
+   }
+}
 
-   /* should accept MONGOC_URI_AUTHMECHANISMPROPERTIES */
-   uri = mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/"
-                         "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES
-                         "=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:"
-                         "true");
-   ASSERT (uri);
-   credentials = mongoc_uri_get_credentials (uri);
-   ASSERT (credentials);
-   ASSERT (mongoc_uri_get_mechanism_properties (uri, &properties));
-   BSON_ASSERT (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") && BSON_ITER_HOLDS_UTF8 (&iter) &&
-                (0 == strcmp (bson_iter_utf8 (&iter, NULL), "other")));
-   BSON_ASSERT (bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") &&
-                BSON_ITER_HOLDS_UTF8 (&iter) && (0 == strcmp (bson_iter_utf8 (&iter, NULL), "true")));
-   mongoc_uri_destroy (uri);
+static void
+_auth_mechanism_password_prohibited (const char *mechanism, const char *user_prefix, const char *uri_suffix)
+{
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_ASSERT_PARAM (user_prefix);
 
-   /* reverse order of arguments to ensure parsing still succeeds */
-   uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISMPROPERTIES
-                         "=SERVICE_NAME:other&" MONGOC_URI_AUTHMECHANISM "=GSSAPI");
-   ASSERT (uri);
-   mongoc_uri_destroy (uri);
+   // None.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%s@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s%s", user_prefix, mechanism, uri_suffix),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), user_prefix);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), NULL);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
 
-   /* X509 */
+   // Empty.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%s:@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s%s", user_prefix, mechanism, uri_suffix),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("'%s' authentication mechanism does not accept a password", mechanism));
+      mongoc_uri_destroy (uri);
+   }
 
-   /* should recognize this mechanism, and use $external as the source */
-   uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509");
-   /*ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");*/
-   mongoc_uri_destroy (uri);
+   // Normal.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%s:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s%s", user_prefix, mechanism, uri_suffix),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("'%s' authentication mechanism does not accept a password", mechanism));
+      clear_captured_logs ();
+      mongoc_uri_destroy (uri);
+   }
+}
 
-   /* use $external as source when db is specified */
-   uri = mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
-                         "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo"
-                         "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
-   mongoc_uri_destroy (uri);
+static void
+_auth_mechanism_password_required (const char *mechanism)
+{
+   BSON_ASSERT_PARAM (mechanism);
 
-   /* should not accept " MONGOC_URI_AUTHSOURCE " other than $external */
-   ASSERT (!mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
-                            "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo"
-                            "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509&" MONGOC_URI_AUTHSOURCE "=bar"));
+   // None.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("'%s' authentication mechanism requires a password", mechanism));
+   }
 
-   /* should recognize the encoded username */
-   uri = mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
-                         "%2CST%3DmyState%2CC%3DmyCountry@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_username (uri), "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry");
-   mongoc_uri_destroy (uri);
+   // Empty.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), "");
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
 
-   /* PLAIN */
+   // Normal.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), "pass");
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
+}
 
-   /* should recognize this mechanism */
-   uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=PLAIN");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "PLAIN");
-   mongoc_uri_destroy (uri);
+static void
+_auth_mechanism_password_allowed (const char *mechanism)
+{
+   BSON_ASSERT_PARAM (mechanism);
 
-   /* SCRAM-SHA1 */
+   // None.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), NULL);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
 
-   /* should recognize this mechanism */
-   uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA1");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA1");
-   mongoc_uri_destroy (uri);
+   // Empty.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), "");
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
+
+   // Normal.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+      ASSERT_CMPSTR (mongoc_uri_get_password (uri), "pass");
+      ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), mechanism);
+      mongoc_uri_destroy (uri);
+   }
 }
 
 
 static void
-test_mongoc_uri_authmechanismproperties (void)
+_auth_mechanism_properties_allowed (const char *mechanism, const char *userpass_prefix, const char *default_properties)
 {
-   mongoc_uri_t *uri;
-   bson_t props;
-   const bson_t *options;
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_ASSERT_PARAM (userpass_prefix);
+   BSON_OPTIONAL_PARAM (default_properties);
+
+   // None.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%slocalhost/?" MONGOC_URI_AUTHMECHANISM "=%s", userpass_prefix, mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+
+      bson_t props;
+      if (default_properties) {
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_MATCH (&props, "{%s}", default_properties ? default_properties : "");
+         bson_destroy (&props);
+      } else {
+         ASSERT_WITH_MSG (!mongoc_uri_get_mechanism_properties (uri, &props), "expected failure");
+      }
+
+      mongoc_uri_destroy (uri);
+   }
+
+   // Empty.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (tmp_str ("mongodb://%slocalhost/?" MONGOC_URI_AUTHMECHANISM
+                                                                    "=%s&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=",
+                                                                    userpass_prefix,
+                                                                    mechanism),
+                                                           &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+
+      bson_t props;
+      ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+      ASSERT_MATCH (&props, "{%s}", default_properties ? default_properties : "");
+
+      bson_destroy (&props);
+      mongoc_uri_destroy (uri);
+   }
+
+   // Invalid properties.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri =
+         mongoc_uri_new_with_error (tmp_str ("mongodb://%slocalhost/?" MONGOC_URI_AUTHMECHANISM
+                                             "=%s&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=invalid:value",
+                                             userpass_prefix,
+                                             mechanism),
+                                    &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_COMMAND,
+                             MONGOC_ERROR_COMMAND_INVALID_ARG,
+                             tmp_str ("Unsupported '%s' authentication mechanism property: 'invalid'", mechanism));
+   }
+}
 
+static void
+_auth_mechanism_source_default_db_or_admin (const char *mechanism)
+{
+   BSON_ASSERT_PARAM (mechanism);
+
+   // None (default).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "admin");
+      mongoc_uri_destroy (uri);
+   }
+
+   // Database name.
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:pass@localhost/db?" MONGOC_URI_AUTHMECHANISM "=%s", mechanism), &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "db");
+      mongoc_uri_destroy (uri);
+   }
+
+   // `authSource` (highest precedence).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://user:pass@localhost/db?" MONGOC_URI_AUTHMECHANISM "=%s&" MONGOC_URI_AUTHSOURCE "=source",
+                  mechanism),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source");
+      mongoc_uri_destroy (uri);
+   }
+}
+
+static void
+_auth_mechanism_source_external_only (const char *mechanism, const char *userpass_prefix, const char *uri_suffix)
+{
+   BSON_ASSERT_PARAM (mechanism);
+   BSON_ASSERT_PARAM (userpass_prefix);
+   BSON_ASSERT_PARAM (uri_suffix);
+
+   // None (default).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%slocalhost/?" MONGOC_URI_AUTHMECHANISM "=%s%s", userpass_prefix, mechanism, uri_suffix),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
+      mongoc_uri_destroy (uri);
+   }
+
+   // Database name (no effect).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+         tmp_str ("mongodb://%slocalhost/db?" MONGOC_URI_AUTHMECHANISM "=%s%s", userpass_prefix, mechanism, uri_suffix),
+         &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
+      mongoc_uri_destroy (uri);
+   }
+
+   // `authSource` (highest precedence, incorrect).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (tmp_str ("mongodb://%slocalhost/db?" MONGOC_URI_AUTHMECHANISM
+                                                                    "=%s&" MONGOC_URI_AUTHSOURCE "=source%s",
+                                                                    userpass_prefix,
+                                                                    mechanism,
+                                                                    uri_suffix),
+                                                           &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT (!uri);
+      ASSERT_ERROR_CONTAINS (
+         error,
+         MONGOC_ERROR_COMMAND,
+         MONGOC_ERROR_COMMAND_INVALID_ARG,
+         tmp_str ("'%s' authentication mechanism requires \"$external\" authSource, but \"source\" was specified",
+                  mechanism));
+      mongoc_uri_destroy (uri);
+   }
+
+   // `authSource` (highest precedence, correct).
+   {
+      bson_error_t error;
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error (tmp_str ("mongodb://%slocalhost/db?" MONGOC_URI_AUTHMECHANISM
+                                                                    "=%s&" MONGOC_URI_AUTHSOURCE "=$external%s",
+                                                                    userpass_prefix,
+                                                                    mechanism,
+                                                                    uri_suffix),
+                                                           &error);
+      ASSERT_OR_PRINT (uri, error);
+      ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      mongoc_uri_destroy (uri);
+   }
+}
+
+static void
+test_mongoc_uri_auth_mechanism_mongodb_x509 (void)
+{
+   // Authentication spec: username: SHOULD NOT be provided for MongoDB 3.4+.
+   // CDRIVER-1959: allow for backward compatibility until the spec states "MUST NOT" instead of "SHOULD NOT" and
+   // spec tests are updated accordingly to permit warnings or errors.
+   {
+      // None.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), NULL);
+         mongoc_uri_destroy (uri);
+      }
+
+      // Empty.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error"); // CDRIVER-1959
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "'MONGODB-X509' authentication mechanism requires a non-empty username");
+      }
+
+      // Normal.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error"); // CDRIVER-1959
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // Authentication spec: password: MUST NOT be specified.
+   _auth_mechanism_password_prohibited ("MONGODB-X509", "user", "");
+
+   // Authentication spec: source: MUST be "$external". Defaults to "$external".
+   _auth_mechanism_source_external_only ("MONGODB-X509", "", "");
+}
+
+static void
+test_mongoc_uri_auth_mechanism_gssapi (void)
+{
+   // Authentication spec: username: MUST be specified and non-zero length.
+   _auth_mechanism_username_required ("GSSAPI");
+
+   // Authentication spec: password: MAY be specified.
+   _auth_mechanism_password_allowed ("GSSAPI");
+
+   // mechanism_properties are allowed.
+   {
+      _auth_mechanism_properties_allowed ("GSSAPI", "user:pass@", "'SERVICE_NAME': 'mongodb'");
+
+      // SERVICE_NAME: Drivers MUST allow the user to specify a different service name. The default is "mongodb".
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=SERVICE_NAME:name",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_EQUAL_BSON (tmp_bson ("{'SERVICE_NAME': 'name'}"), &props);
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+
+      // SERVICE_NAME: naming of mechanism properties MUST be case-insensitive.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=service_name:name",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_EQUAL_BSON (tmp_bson ("{'service_name': 'name'}"), &props);
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+
+      // CANONICALIZE_HOST_NAME: Drivers MAY allow the user to request canonicalization of the hostname.
+      {
+         // CDRIVER-4128: only legacy boolean values are currently supported.
+         {
+            static const char *const values[] = {"false", "true", NULL};
+
+            for (const char *const *value_ptr = values; *value_ptr; ++value_ptr) {
+               const char *const value = *value_ptr;
+
+               bson_error_t error;
+               mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+                  tmp_str ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                           "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=CANONICALIZE_HOST_NAME:%s",
+                           value),
+                  &error);
+               ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+               ASSERT_OR_PRINT (uri, error);
+
+               bson_t props;
+               ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+               ASSERT_MATCH (&props, "{'CANONICALIZE_HOST_NAME': '%s'}", value);
+
+               bson_destroy (&props);
+               mongoc_uri_destroy (uri);
+            }
+         }
+
+         {
+            // CDRIVER-4128: only legacy boolean values are currently supported.
+            static const char *const values[] = {"none", "forward", "forwardAndReverse", NULL};
+
+            for (const char *const *value_ptr = values; *value_ptr; ++value_ptr) {
+               const char *const value = *value_ptr;
+               bson_error_t error;
+               mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+                  tmp_str ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                           "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=CANONICALIZE_HOST_NAME:%s",
+                           value),
+                  &error);
+               ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+               ASSERT (!uri);
+               ASSERT_ERROR_CONTAINS (error,
+                                      MONGOC_ERROR_COMMAND,
+                                      MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                      "'GSSAPI' authentication mechanism requires CANONICALIZE_HOST_NAME is either "
+                                      "\"true\" or \"false\"");
+
+               mongoc_uri_destroy (uri);
+            }
+         }
+      }
+
+      // SERVICE_REALM: Drivers MAY allow the user to specify a different realm for the service.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=SERVICE_REALM:realm",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_MATCH (&props, "{'SERVICE_NAME': 'mongodb', 'SERVICE_REALM': 'realm'}");
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+
+      // SERVICE_HOST: Drivers MAY allow the user to specify a different host for the service.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=SERVICE_HOST:host",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_MATCH (&props, "{'SERVICE_NAME': 'mongodb', 'SERVICE_HOST': 'host'}");
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // Authentication spec: source: MUST be "$external". Defaults to "$external".
+   _auth_mechanism_source_external_only ("GSSAPI", "user@", "");
+}
+
+static void
+test_mongoc_uri_auth_mechanism_plain (void)
+{
+   // Authentication spec: username: MUST be specified and non-zero length.
+   _auth_mechanism_username_required ("PLAIN");
+
+   // Authentication spec: password: MUST be specified.
+   _auth_mechanism_password_required ("PLAIN");
+
+   // Authentication spec: source: MUST be specified. Defaults to the database name if supplied on the connection
+   // string or "$external".
+   {
+      // None (default).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=PLAIN", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external");
+         mongoc_uri_destroy (uri);
+      }
+
+      // Database name.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/db?" MONGOC_URI_AUTHMECHANISM "=PLAIN", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "db");
+         mongoc_uri_destroy (uri);
+      }
+
+      // `authSource` (highest precedence).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+            "mongodb://user:pass@localhost/db?" MONGOC_URI_AUTHMECHANISM "=PLAIN&" MONGOC_URI_AUTHSOURCE "=source",
+            &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source");
+         mongoc_uri_destroy (uri);
+      }
+   }
+}
+
+static void
+test_mongoc_uri_auth_mechanism_scram_sha_1 (void)
+{
+   const char *const mechanism = "SCRAM-SHA-1";
+
+   // Authentication spec: username: MUST be specified and non-zero length.
+   _auth_mechanism_username_required (mechanism);
+
+   // Authentication spec: password: MUST be specified.
+   _auth_mechanism_password_required (mechanism);
+
+   // Authentication spec: source: MUST be specified. Defaults to the database name if supplied on the connection
+   // string or "admin".
+   _auth_mechanism_source_default_db_or_admin (mechanism);
+}
+
+static void
+test_mongoc_uri_auth_mechanism_scram_sha_256 (void)
+{
+   const char *const mechanism = "SCRAM-SHA-256";
+
+   // Authentication spec: username: MUST be specified and non-zero length.
+   _auth_mechanism_username_required (mechanism);
+
+   // Authentication spec: password: MUST be specified.
+   _auth_mechanism_password_required (mechanism);
+
+   // Authentication spec: source: MUST be specified. Defaults to the database name if supplied on the connection
+   // string or "admin".
+   _auth_mechanism_source_default_db_or_admin (mechanism);
+}
+
+static void
+test_mongoc_uri_auth_mechanism_mongodb_aws (void)
+{
+   // Authentication spec: username: MAY be specified.
+   // Authentication spec: if a username is provided without a password (or vice-versa) or if only a session token is
+   // provided Drivers MUST raise an error.
+   {
+      // None.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), NULL);
+         mongoc_uri_destroy (uri);
+      }
+
+      // Empty.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://:@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "'MONGODB-AWS' authentication mechanism requires a non-empty username");
+      }
+
+      // Normal.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), "user");
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // Authentication spec: password: MAY be specified.
+   // Authentication spec: if a username is provided without a password (or vice-versa) or if only a session token is
+   // provided Drivers MUST raise an error.
+   {
+      // None.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (
+            error,
+            MONGOC_ERROR_COMMAND,
+            MONGOC_ERROR_COMMAND_INVALID_ARG,
+            "'MONGODB-AWS' authentication mechanism does not accept a username or a password without the other");
+         mongoc_uri_destroy (uri);
+      }
+
+      // Empty.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         mongoc_uri_destroy (uri);
+      }
+
+      // Normal.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+            "mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-AWS", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // mechanism_properties are allowed.
+   {
+      _auth_mechanism_properties_allowed ("MONGODB-AWS", "", NULL);
+
+      // AWS_SESSION_TOKEN: Drivers MUST allow the user to specify an AWS session token for authentication with
+      // temporary credentials.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=MONGODB-AWS&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=AWS_SESSION_TOKEN:token",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_EQUAL_BSON (tmp_bson ("{'AWS_SESSION_TOKEN': 'token'}"), &props);
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+
+      // AWS_SESSION_TOKEN: naming of mechanism properties MUST be case-insensitive.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM
+                                       "=MONGODB-AWS&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=aws_session_token:token",
+                                       &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+
+         bson_t props;
+         ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+         ASSERT_EQUAL_BSON (tmp_bson ("{'aws_session_token': 'token'}"), &props);
+
+         bson_destroy (&props);
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // Authentication spec: source: MUST be "$external". Defaults to "$external".
+   _auth_mechanism_source_external_only ("MONGODB-AWS", "", "");
+}
+
+static void
+test_mongoc_uri_auth_mechanisms (void)
+{
    capture_logs (true);
 
-   uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA1"
-                         "&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=a:one,b:two");
-   ASSERT (uri);
-   ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA1");
-   ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
-   ASSERT_MATCH (&props, "{'a': 'one', 'b': 'two'}");
+   // No username or mechanism means no authentication, even if auth fields are present.
+   {
+      // Authentication spec: the presence of a database name in the URI connection string MUST NOT be interpreted as a
+      // user configuring authentication credentials.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://localhost/db", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "db"); // Default.
+         mongoc_uri_destroy (uri);
+      }
 
-   /* prohibited */
-   ASSERT (!mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_AUTHMECHANISM, "SCRAM-SHA1"));
+      // Authentication spec: the presence of the authSource option in the URI connection string without other
+      // credential data such as Userinfo or authentication parameters in connection options MUST NOT be interpreted as
+      // a request for authentication.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHSOURCE "=source", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source");
+         mongoc_uri_destroy (uri);
+      }
 
-   ASSERT (!mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_AUTHMECHANISM, 1));
-   ASSERT_CAPTURED_LOG ("setting authmechanism=1",
-                        MONGOC_LOG_LEVEL_WARNING,
-                        "Unsupported value for \"authmechanism\": 1,"
-                        " \"authmechanism\" is not an int32 option");
+      // For backward compatibility, `mongoc_uri_get_auth_source` always returns "admin" when no `authMechanism`,
+      // database name, or `authSource` is specified (consistent with default authentication method selecting
+      // SCRAM-SHA-1 or SCRAM-SHA-256).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://localhost/", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "admin");
+         mongoc_uri_destroy (uri);
+      }
 
-   ASSERT (!mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_AUTHMECHANISMPROPERTIES, "a:three"));
+      // For backward compatibility, `mongoc_uri_get_auth_source` uses the database name when no `authMechanism` or
+      // `authSource` is specified (consistent with default authentication method selecting SCRAM-SHA-1 or
+      // SCRAM-SHA-256).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://user:pass@localhost/db", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "db");
+         mongoc_uri_destroy (uri);
+      }
 
-   ASSERT (mongoc_uri_set_mechanism_properties (uri, tmp_bson ("{'a': 'four'}")));
+      // For backward compatibility, `mongoc_uri_get_auth_source` uses `authSource` when specified (consistent with
+      // default authentication method selecting SCRAM-SHA-1 or SCRAM-SHA-256).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://user:pass@localhost/db?" MONGOC_URI_AUTHSOURCE "=source", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source");
+         mongoc_uri_destroy (uri);
+      }
 
-   ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
-   ASSERT_MATCH (&props, "{'a': 'four', 'b': {'$exists': false}}");
+      // `authMechanismProperties` should not be validated without an `authMechanism`.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISMPROPERTIES "=x:1", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_WITH_MSG (!mongoc_uri_get_auth_mechanism (uri),
+                          "expected no authMechanism, got %s",
+                          mongoc_uri_get_auth_mechanism (uri));
+         mongoc_uri_destroy (uri);
+      }
+   }
 
-   mongoc_uri_destroy (uri);
+   // Warn for invalid or unsupported `authMechanism` values.
+   {
+      // Empty.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "Unsupported value for authMechanism '': must be one of ['MONGODB-OIDC', "
+                                "'SCRAM-SHA-1', 'SCRAM-SHA-256', 'PLAIN', 'MONGODB-X509', 'GSSAPI', 'MONGODB-AWS']");
+         mongoc_uri_destroy (uri);
+      }
 
-   /* deprecated gssapiServiceName option */
-   uri = mongoc_uri_new ("mongodb://christian%40realm.cc@localhost:27017/"
-                         "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_GSSAPISERVICENAME "=blah");
-   ASSERT (uri);
-   options = mongoc_uri_get_options (uri);
-   ASSERT (options);
-   BSON_ASSERT (0 == strcmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI"));
-   BSON_ASSERT (0 == strcmp (mongoc_uri_get_username (uri), "christian@realm.cc"));
-   ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
-   ASSERT_MATCH (&props, "{'SERVICE_NAME': 'blah'}");
-   mongoc_uri_destroy (uri);
+      // Case-insensitivity.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error (
+            "mongodb://user:pass@localhost/?" MONGOC_URI_AUTHMECHANISM "=scram-sha-1", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "scram-sha-1");
+         mongoc_uri_destroy (uri);
+      }
+
+      // No substring comparison.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=SCRAM", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "Unsupported value for authMechanism 'SCRAM': must be one of ['MONGODB-OIDC', "
+                                "'SCRAM-SHA-1', 'SCRAM-SHA-256', 'PLAIN', 'MONGODB-X509', 'GSSAPI', 'MONGODB-AWS']");
+         mongoc_uri_destroy (uri);
+      }
+
+      // Unsupported.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-CR", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "Unsupported value for authMechanism 'MONGODB-CR': must be one of ['MONGODB-OIDC', "
+                                "'SCRAM-SHA-1', 'SCRAM-SHA-256', 'PLAIN', 'MONGODB-X509', 'GSSAPI', 'MONGODB-AWS']");
+         mongoc_uri_destroy (uri);
+      }
+   }
+
+   // Default Authentication Mechanism
+   {
+      // Authentication spec: the presence of a credential delimiter (i.e. @) in the URI connection string is evidence
+      // that the user has unambiguously specified user information and MUST be interpreted as a user configuring
+      // authentication credentials (even if the username and/or password are empty strings).
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://username@localhost/", &error);
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), "username");
+
+         // For backward compatibility, do not forbid missing or empty password even if default authentication method
+         // can only resolve to SCRAM-SHA-1 or SCRAM-SHA-256, both of which require a non-empty password.
+         ASSERT_CMPSTR (mongoc_uri_get_password (uri), NULL);
+
+         mongoc_uri_destroy (uri);
+      }
+
+      // Presence of `:` is interpreted as specifying a password, even if empty.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://username:@localhost/", &error);
+         ASSERT_OR_PRINT (uri, error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT_CMPSTR (mongoc_uri_get_username (uri), "username");
+
+         // For backward compatibility, do not forbid missing or empty password even if default authentication method
+         // can only resolve to SCRAM-SHA-1 or SCRAM-SHA-256, both of which require a non-empty password.
+         ASSERT_CMPSTR (mongoc_uri_get_password (uri), "");
+
+         mongoc_uri_destroy (uri);
+      }
+
+      // Satisfy Connection String spec test: "must raise an error when the authSource is empty".
+      // This applies even before determining whether or not authentication is required.
+      {
+         bson_error_t error;
+         mongoc_uri_t *const uri =
+            mongoc_uri_new_with_error ("mongodb://localhost/?" MONGOC_URI_AUTHSOURCE "=", &error);
+         ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+         ASSERT (!uri);
+         ASSERT_ERROR_CONTAINS (error,
+                                MONGOC_ERROR_COMMAND,
+                                MONGOC_ERROR_COMMAND_INVALID_ARG,
+                                "authSource may not be specified as an empty string");
+      }
+   }
+
+   test_mongoc_uri_auth_mechanism_mongodb_x509 ();
+   test_mongoc_uri_auth_mechanism_gssapi ();
+   test_mongoc_uri_auth_mechanism_plain ();
+   test_mongoc_uri_auth_mechanism_scram_sha_1 ();
+   test_mongoc_uri_auth_mechanism_scram_sha_256 ();
+   test_mongoc_uri_auth_mechanism_mongodb_aws ();
+
+   capture_logs (false);
 }
 
 
@@ -471,11 +1291,15 @@ test_mongoc_uri_functions (void)
    ASSERT_CMPSTR (mongoc_uri_get_auth_source (client->uri), "longer authsource that should work");
    mongoc_client_destroy (client);
 
-
+   capture_logs (true);
    uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=3"
                          "&" MONGOC_URI_JOURNAL "=true"
                          "&" MONGOC_URI_WTIMEOUTMS "=42"
                          "&" MONGOC_URI_CANONICALIZEHOSTNAME "=false");
+   ASSERT_CAPTURED_LOG ("mongoc_uri_new",
+                        MONGOC_LOG_LEVEL_WARNING,
+                        MONGOC_URI_CANONICALIZEHOSTNAME " is deprecated, use " MONGOC_URI_AUTHMECHANISMPROPERTIES
+                                                        " with CANONICALIZE_HOST_NAME instead");
 
    ASSERT_CMPINT (mongoc_uri_get_option_as_int32 (uri, "serverselectiontimeoutms", 18), ==, 3);
    ASSERT (mongoc_uri_set_option_as_int32 (uri, "serverselectiontimeoutms", 18));
@@ -519,7 +1343,6 @@ test_mongoc_uri_functions (void)
    mongoc_uri_destroy (uri);
 
    ASSERT (mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_JOURNAL, false));
-   ASSERT (!mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_CANONICALIZEHOSTNAME, true));
    /* tls isn't set, return out fallback */
    ASSERT (mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_TLS, true));
    mongoc_client_destroy (client);
@@ -534,19 +1357,19 @@ test_mongoc_uri_functions (void)
 
    uri =
       mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SOCKETTIMEOUTMS "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=200");
-   ASSERT_CMPINT (1, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0));
-   ASSERT_CMPINT (200, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0));
+   ASSERT_CMPINT32 (1, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0));
+   ASSERT_CMPINT32 (200, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0));
 
    mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 2);
-   ASSERT_CMPINT (2, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0));
+   ASSERT_CMPINT32 (2, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0));
 
    mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 202);
-   ASSERT_CMPINT (202, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0));
+   ASSERT_CMPINT32 (202, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0));
 
 
    client = test_framework_client_new_from_uri (uri, NULL);
-   ASSERT_CMPINT (2, ==, client->cluster.sockettimeoutms);
-   ASSERT_CMPINT (202, ==, client->cluster.socketcheckintervalms);
+   ASSERT_CMPINT32 (2, ==, client->cluster.sockettimeoutms);
+   ASSERT_CMPINT32 (202, ==, client->cluster.socketcheckintervalms);
 
    mongoc_client_destroy (client);
    mongoc_uri_destroy (uri);
@@ -577,6 +1400,8 @@ test_mongoc_uri_functions (void)
    mongoc_uri_destroy (uri);
 }
 
+#define BSON_ERROR_INIT ((bson_error_t){.code = 0u, .domain = 0u, .message = {0}, .reserved = 0u})
+
 static void
 test_mongoc_uri_new_with_error (void)
 {
@@ -592,19 +1417,19 @@ test_mongoc_uri_new_with_error (void)
    ASSERT (!mongoc_uri_new_with_error ("mongodb://", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongo://localhost", &error));
    ASSERT_ERROR_CONTAINS (
       error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid URI Schema, expecting 'mongodb://'");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/?readPreference=unknown", &error));
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
                           "Unsupported readPreference value [readPreference=unknown]");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/"
                                        "?appname="
                                        "WayTooLongAppnameToBeValidSoThisShouldResultInAnErrorWayToLongAppnameToB"
@@ -622,7 +1447,7 @@ test_mongoc_uri_new_with_error (void)
                                            "sultInAnError"));
    mongoc_uri_destroy (uri);
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://user%p:pass@localhost/", &error));
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
@@ -630,72 +1455,67 @@ test_mongoc_uri_new_with_error (void)
                           "Incorrect URI escapes in username. Percent-encode "
                           "username and password according to RFC 3986");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://l%oc, alhost/", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb:///tmp/mongodb.sock", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db.na%me", &error));
    ASSERT_ERROR_CONTAINS (
       error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid database name in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?journal=true&w=0", &error));
    ASSERT_ERROR_CONTAINS (
       error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Journal conflicts with w value [w=0]");
 
-   memset (&error, 0, sizeof (bson_error_t));
-   ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?journal=true&w=-1", &error));
-   ASSERT_ERROR_CONTAINS (
-      error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Journal conflicts with w value [w=-1]");
-
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?w=-5", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Unsupported w value [w=-5]");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?heartbeatfrequencyms=10", &error));
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
                           "Invalid \"heartbeatfrequencyms\" of 10: must be at least 500");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?zlibcompressionlevel=10", &error));
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
                           "Invalid \"zlibcompressionlevel\" of 10: must be between -1 and 9");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://", &error));
    ASSERT_ERROR_CONTAINS (
       error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Missing service name in SRV URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://%", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://x", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://x.y", &error));
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://a.b.c,d.e.f", &error));
    ASSERT_ERROR_CONTAINS (error,
                           MONGOC_ERROR_COMMAND,
                           MONGOC_ERROR_COMMAND_INVALID_ARG,
                           "Multiple service names are prohibited in an SRV URI");
 
-   memset (&error, 0, sizeof (bson_error_t));
+   error = BSON_ERROR_INIT;
    ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://a.b.c:8000", &error));
    ASSERT_ERROR_CONTAINS (
       error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Port numbers are prohibited in an SRV URI");
@@ -722,8 +1542,8 @@ test_mongoc_uri_compound_setters (void)
    prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
    mongoc_uri_set_read_prefs_t (uri, prefs);
    prefs_result = mongoc_uri_get_read_prefs_t (uri);
-   ASSERT_CMPINT (mongoc_read_prefs_get_mode (prefs_result), ==, MONGOC_READ_SECONDARY);
-   ASSERT (bson_empty (mongoc_read_prefs_get_tags (prefs_result)));
+   ASSERT_CMPINT ((int) mongoc_read_prefs_get_mode (prefs_result), ==, MONGOC_READ_SECONDARY);
+   ASSERT_EQUAL_BSON (tmp_bson ("{}"), mongoc_read_prefs_get_tags (prefs_result));
 
    rc = mongoc_read_concern_new ();
    mongoc_read_concern_set_level (rc, "whatever");
@@ -735,7 +1555,7 @@ test_mongoc_uri_compound_setters (void)
    mongoc_write_concern_set_w (wc, 2);
    mongoc_uri_set_write_concern (uri, wc);
    wc_result = mongoc_uri_get_write_concern (uri);
-   ASSERT_CMPINT32 (mongoc_write_concern_get_w (wc_result), ==, (int32_t) 2);
+   ASSERT_CMPINT32 (mongoc_write_concern_get_w (wc_result), ==, 2);
 
    mongoc_read_prefs_destroy (prefs);
    mongoc_read_concern_destroy (rc);
@@ -786,33 +1606,33 @@ test_mongoc_host_list_from_string (void)
    ASSERT (_mongoc_host_list_from_string (&host_list, "localHOST:27019"));
    ASSERT_CMPSTR (host_list.host_and_port, "localhost:27019");
    ASSERT_CMPSTR (host_list.host, "localhost");
-   ASSERT (host_list.port == 27019);
+   ASSERT_CMPUINT16 (host_list.port, ==, 27019);
    ASSERT (!host_list.next);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "localhost"));
    ASSERT_CMPSTR (host_list.host_and_port, "localhost:27017");
    ASSERT_CMPSTR (host_list.host, "localhost");
-   ASSERT (host_list.port == 27017);
+   ASSERT_CMPUINT16 (host_list.port, ==, 27017);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[::1]"));
    ASSERT_CMPSTR (host_list.host_and_port, "[::1]:27017");
    ASSERT_CMPSTR (host_list.host, "::1"); /* no "[" or "]" */
-   ASSERT (host_list.port == 27017);
+   ASSERT_CMPUINT16 (host_list.port, ==, 27017);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[Fe80::1]:1234"));
    ASSERT_CMPSTR (host_list.host_and_port, "[fe80::1]:1234");
    ASSERT_CMPSTR (host_list.host, "fe80::1");
-   ASSERT (host_list.port == 1234);
+   ASSERT_CMPUINT16 (host_list.port, ==, 1234);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[fe80::1%lo0]:1234"));
    ASSERT_CMPSTR (host_list.host_and_port, "[fe80::1%lo0]:1234");
    ASSERT_CMPSTR (host_list.host, "fe80::1%lo0");
-   ASSERT (host_list.port == 1234);
+   ASSERT_CMPUINT16 (host_list.port, ==, 1234);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[fe80::1%lo0]:1234"));
    ASSERT_CMPSTR (host_list.host_and_port, "[fe80::1%lo0]:1234");
    ASSERT_CMPSTR (host_list.host, "fe80::1%lo0");
-   ASSERT (host_list.port == 1234);
+   ASSERT_CMPUINT16 (host_list.port, ==, 1234);
 
    /* preserves case */
    ASSERT (_mongoc_host_list_from_string (&host_list, "/Path/to/file.sock"));
@@ -822,22 +1642,22 @@ test_mongoc_host_list_from_string (void)
    /* weird cases that should still parse, without crashing */
    ASSERT (_mongoc_host_list_from_string (&host_list, "/Path/to/file.sock:1"));
    ASSERT_CMPSTR (host_list.host, "/Path/to/file.sock");
-   ASSERT (host_list.family == AF_UNIX);
+   ASSERT_CMPINT (host_list.family, ==, AF_UNIX);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, " :1234"));
    ASSERT_CMPSTR (host_list.host_and_port, " :1234");
    ASSERT_CMPSTR (host_list.host, " ");
-   ASSERT (host_list.port == 1234);
+   ASSERT_CMPUINT16 (host_list.port, ==, 1234);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[:1234"));
    ASSERT_CMPSTR (host_list.host_and_port, "[:1234");
    ASSERT_CMPSTR (host_list.host, "[");
-   ASSERT (host_list.port == 1234);
+   ASSERT_CMPUINT16 (host_list.port, ==, 1234);
 
    ASSERT (_mongoc_host_list_from_string (&host_list, "[:]"));
    ASSERT_CMPSTR (host_list.host_and_port, "[:]:27017");
    ASSERT_CMPSTR (host_list.host, ":");
-   ASSERT (host_list.port == 27017);
+   ASSERT_CMPUINT16 (host_list.port, ==, 27017);
 }
 
 
@@ -848,9 +1668,9 @@ test_mongoc_uri_new_for_host_port (void)
 
    uri = mongoc_uri_new_for_host_port ("uber", 555);
    ASSERT (uri);
-   ASSERT (!strcmp ("uber", mongoc_uri_get_hosts (uri)->host));
-   ASSERT (!strcmp ("uber:555", mongoc_uri_get_hosts (uri)->host_and_port));
-   ASSERT (555 == mongoc_uri_get_hosts (uri)->port);
+   ASSERT_CMPSTR ("uber", mongoc_uri_get_hosts (uri)->host);
+   ASSERT_CMPSTR ("uber:555", mongoc_uri_get_hosts (uri)->host_and_port);
+   ASSERT_CMPUINT16 (555, ==, mongoc_uri_get_hosts (uri)->port);
    mongoc_uri_destroy (uri);
 }
 
@@ -861,13 +1681,12 @@ test_mongoc_uri_compressors (void)
 
    uri = mongoc_uri_new ("mongodb://localhost/");
 
-   ASSERT (bson_empty (mongoc_uri_get_compressors (uri)));
+   ASSERT_EQUAL_BSON (tmp_bson ("{}"), mongoc_uri_get_compressors (uri));
 
 #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY
    capture_logs (true);
    mongoc_uri_set_compressors (uri, "snappy,unknown");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "unknown"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}, 'unknown': {'$exists': false}}");
    ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'unknown'");
 #endif
 
@@ -875,28 +1694,26 @@ test_mongoc_uri_compressors (void)
 #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY
    capture_logs (true);
    mongoc_uri_set_compressors (uri, "snappy");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "unknown"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}, 'unknown': {'$exists': false}}");
    ASSERT_NO_CAPTURED_LOGS ("snappy uri");
 
    /* Overwrite the previous URI, effectively disabling snappy */
    capture_logs (true);
    mongoc_uri_set_compressors (uri, "unknown");
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "unknown"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': false}, 'unknown': {'$exists': false}}");
    ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'unknown'");
 #endif
 
    capture_logs (true);
    mongoc_uri_set_compressors (uri, "");
-   ASSERT (bson_empty (mongoc_uri_get_compressors (uri)));
+   ASSERT_EQUAL_BSON (tmp_bson ("{}"), mongoc_uri_get_compressors (uri));
    ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: ''");
 
 
    /* Disable compression */
    capture_logs (true);
    mongoc_uri_set_compressors (uri, NULL);
-   ASSERT (bson_empty (mongoc_uri_get_compressors (uri)));
+   ASSERT_EQUAL_BSON (tmp_bson ("{}"), mongoc_uri_get_compressors (uri));
    ASSERT_NO_CAPTURED_LOGS ("Disable compression");
 
 
@@ -905,13 +1722,13 @@ test_mongoc_uri_compressors (void)
 
 #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=snappy");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}}");
    mongoc_uri_destroy (uri);
 
    capture_logs (true);
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=snappy,somethingElse");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "somethingElse"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri),
+                 "{'snappy': {'$exists': true}, 'somethingElse': {'$exists': false}}");
    ASSERT_CAPTURED_LOG (
       "mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'somethingElse'");
    mongoc_uri_destroy (uri);
@@ -922,38 +1739,34 @@ test_mongoc_uri_compressors (void)
 
 #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=snappy,zlib");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}, 'zlib': {'$exists': true}}");
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://localhost/");
    ASSERT (mongoc_uri_set_compressors (uri, "snappy,zlib"));
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}, 'zlib': {'$exists': true}}");
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://localhost/");
    ASSERT (mongoc_uri_set_compressors (uri, "zlib"));
    ASSERT (mongoc_uri_set_compressors (uri, "snappy"));
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'snappy': {'$exists': true}, 'zlib': {'$exists': false}}");
    mongoc_uri_destroy (uri);
 #endif
 
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'zlib': {'$exists': true}}");
    mongoc_uri_destroy (uri);
 
    capture_logs (true);
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib,somethingElse");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
-   ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "somethingElse"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'zlib': {'$exists': true}, 'somethingElse': {'$exists': false}}");
    ASSERT_CAPTURED_LOG (
       "mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'somethingElse'");
    mongoc_uri_destroy (uri);
 
    uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib&zlibCompressionLevel=-1");
-   ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib"));
+   ASSERT_MATCH (mongoc_uri_get_compressors (uri), "{'zlib': {'$exists': true}}");
    ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 1), ==, -1);
    mongoc_uri_destroy (uri);
 
@@ -1043,63 +1856,96 @@ test_mongoc_uri_read_prefs (void)
    const char *conflicts = "Invalid readPreferences";
 
    const read_prefs_test tests[] = {
-      {"mongodb://localhost/", true, MONGOC_READ_PRIMARY, NULL},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary", true, MONGOC_READ_PRIMARY, NULL},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primaryPreferred",
-       true,
-       MONGOC_READ_PRIMARY_PREFERRED,
-       NULL},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondary", true, MONGOC_READ_SECONDARY, NULL},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondaryPreferred",
-       true,
-       MONGOC_READ_SECONDARY_PREFERRED,
-       NULL},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest", true, MONGOC_READ_NEAREST, NULL},
-      /* MONGOC_URI_READPREFERENCETAGS conflict with primary mode */
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCETAGS "=", false, MONGOC_READ_PRIMARY, NULL, conflicts},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary&" MONGOC_URI_READPREFERENCETAGS "=",
-       false,
-       MONGOC_READ_PRIMARY,
-       NULL,
-       conflicts},
-      {"mongodb://localhost/"
-       "?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=",
-       true,
-       MONGOC_READ_SECONDARY_PREFERRED,
-       tags_empty},
-      {"mongodb://localhost/"
-       "?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=dc:ny",
-       true,
-       MONGOC_READ_SECONDARY_PREFERRED,
-       tags_dcny},
-      {"mongodb://localhost/"
-       "?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=dc:ny&" MONGOC_URI_READPREFERENCETAGS
-       "=",
-       true,
-       MONGOC_READ_NEAREST,
-       tags_dcny_empty},
-      {"mongodb://localhost/"
-       "?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS
-       "=dc:ny,use:ssd&" MONGOC_URI_READPREFERENCETAGS "=dc:sf&" MONGOC_URI_READPREFERENCETAGS "=",
-       true,
-       MONGOC_READ_NEAREST,
-       tags_dcnyusessd_dcsf_empty},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo",
-       false,
-       MONGOC_READ_NEAREST,
-       NULL,
-       "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo\""},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo,bar",
-       false,
-       MONGOC_READ_NEAREST,
-       NULL,
-       "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo,bar\""},
-      {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=1",
-       false,
-       MONGOC_READ_NEAREST,
-       NULL,
-       "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"1\""},
-      {NULL}};
+      {
+         .uri = "mongodb://localhost/",
+         .parses = true,
+         .mode = MONGOC_READ_PRIMARY,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary",
+         .parses = true,
+         .mode = MONGOC_READ_PRIMARY,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primaryPreferred",
+         .parses = true,
+         .mode = MONGOC_READ_PRIMARY_PREFERRED,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondary",
+         .parses = true,
+         .mode = MONGOC_READ_SECONDARY,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondaryPreferred",
+         .parses = true,
+         .mode = MONGOC_READ_SECONDARY_PREFERRED,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest",
+         .parses = true,
+         .mode = MONGOC_READ_NEAREST,
+      },
+      {
+         /* MONGOC_URI_READPREFERENCETAGS conflict with primary mode */
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCETAGS "=",
+         .parses = false,
+         .mode = MONGOC_READ_PRIMARY,
+         .log_msg = conflicts,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary&" MONGOC_URI_READPREFERENCETAGS "=",
+         .parses = false,
+         .mode = MONGOC_READ_PRIMARY,
+         .log_msg = conflicts,
+      },
+      {
+         .uri =
+            "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=",
+         .parses = true,
+         .mode = MONGOC_READ_SECONDARY_PREFERRED,
+         .tags = tags_empty,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS
+                "=dc:ny",
+         .parses = true,
+         .mode = MONGOC_READ_SECONDARY_PREFERRED,
+         .tags = tags_dcny,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS
+                "=dc:ny&" MONGOC_URI_READPREFERENCETAGS "=",
+         .parses = true,
+         .mode = MONGOC_READ_NEAREST,
+         .tags = tags_dcny_empty,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS
+                "=dc:ny,use:ssd&" MONGOC_URI_READPREFERENCETAGS "=dc:sf&" MONGOC_URI_READPREFERENCETAGS "=",
+         .parses = true,
+         .mode = MONGOC_READ_NEAREST,
+         .tags = tags_dcnyusessd_dcsf_empty,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo",
+         .parses = false,
+         .mode = MONGOC_READ_NEAREST,
+         .log_msg = "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo\"",
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo,bar",
+         .parses = false,
+         .mode = MONGOC_READ_NEAREST,
+         .log_msg = "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo,bar\"",
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=1",
+         .parses = false,
+         .mode = MONGOC_READ_NEAREST,
+         .log_msg = "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"1\"",
+      },
+      {0}};
 
    for (i = 0; tests[i].uri; i++) {
       t = &tests[i];
@@ -1107,10 +1953,10 @@ test_mongoc_uri_read_prefs (void)
       capture_logs (true);
       uri = mongoc_uri_new (t->uri);
       if (t->parses) {
-         BSON_ASSERT (uri);
+         ASSERT (uri);
          ASSERT_NO_CAPTURED_LOGS (t->uri);
       } else {
-         BSON_ASSERT (!uri);
+         ASSERT (!uri);
          if (t->log_msg) {
             ASSERT_CAPTURED_LOG (t->uri, MONGOC_LOG_LEVEL_WARNING, t->log_msg);
          }
@@ -1119,12 +1965,12 @@ test_mongoc_uri_read_prefs (void)
       }
 
       rp = mongoc_uri_get_read_prefs_t (uri);
-      BSON_ASSERT (rp);
+      ASSERT (rp);
 
-      BSON_ASSERT (t->mode == mongoc_read_prefs_get_mode (rp));
+      ASSERT_CMPINT ((int) t->mode, ==, (int) mongoc_read_prefs_get_mode (rp));
 
       if (t->tags) {
-         BSON_ASSERT (bson_equal (t->tags, mongoc_read_prefs_get_tags (rp)));
+         ASSERT_EQUAL_BSON (t->tags, mongoc_read_prefs_get_tags (rp));
       }
 
       mongoc_uri_destroy (uri);
@@ -1150,59 +1996,117 @@ typedef struct {
 static void
 test_mongoc_uri_write_concern (void)
 {
-   const mongoc_write_concern_t *wr;
-   mongoc_uri_t *uri;
-   const write_concern_test *t;
-   int i;
    static const write_concern_test tests[] = {
-      {"mongodb://localhost/?" MONGOC_URI_SAFE "=false", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED},
-      {"mongodb://localhost/?" MONGOC_URI_SAFE "=true", true, 1},
-      {"mongodb://localhost/?" MONGOC_URI_W "=-1", true, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED},
-      {"mongodb://localhost/?" MONGOC_URI_W "=0", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED},
-      {"mongodb://localhost/?" MONGOC_URI_W "=1", true, 1},
-      {"mongodb://localhost/?" MONGOC_URI_W "=2", true, 2},
-      {"mongodb://localhost/?" MONGOC_URI_W "=majority", true, MONGOC_WRITE_CONCERN_W_MAJORITY},
-      {"mongodb://localhost/?" MONGOC_URI_W "=10", true, 10},
-      {"mongodb://localhost/?" MONGOC_URI_W "=", true, MONGOC_WRITE_CONCERN_W_DEFAULT},
-      {"mongodb://localhost/?" MONGOC_URI_W "=mytag", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag"},
-      {"mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_SAFE "=false",
-       true,
-       MONGOC_WRITE_CONCERN_W_TAG,
-       "mytag"},
-      {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_SAFE "=false", true, 1},
-      {"mongodb://localhost/?" MONGOC_URI_JOURNAL "=true", true, MONGOC_WRITE_CONCERN_W_DEFAULT},
-      {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_JOURNAL "=true", true, 1},
-      {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=1000", true, 2, NULL, 1000},
-      {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=2147483648", true, 2, NULL, 2147483648LL},
-      {"mongodb://localhost/?" MONGOC_URI_W "=majority&" MONGOC_URI_WTIMEOUTMS "=1000",
-       true,
-       MONGOC_WRITE_CONCERN_W_MAJORITY,
-       NULL,
-       1000},
-      {"mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_WTIMEOUTMS "=1000",
-       true,
-       MONGOC_WRITE_CONCERN_W_TAG,
-       "mytag",
-       1000},
-      {"mongodb://localhost/?" MONGOC_URI_W "=0&" MONGOC_URI_JOURNAL "=true",
-       false,
-       MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED,
-       NULL,
-       0,
-       "Journal conflicts with w value [" MONGOC_URI_W "=0]"},
-      {"mongodb://localhost/?" MONGOC_URI_W "=-1&" MONGOC_URI_JOURNAL "=true",
-       false,
-       MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED,
-       NULL,
-       0,
-       "Journal conflicts with w value [" MONGOC_URI_W "=-1]"},
-      {NULL}};
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_SAFE "=false",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_SAFE "=true",
+         .parses = true,
+         .w = 1,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=-1",
+         .parses = false,
+         .log_msg = "Unsupported w value [w=-1]",
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=0",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=1",
+         .parses = true,
+         .w = 1,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=2",
+         .parses = true,
+         .w = 2,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=majority",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_MAJORITY,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=10",
+         .parses = true,
+         .w = 10,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_DEFAULT,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=mytag",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_TAG,
+         .wtag = "mytag",
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_SAFE "=false",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_TAG,
+         .wtag = "mytag",
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_SAFE "=false",
+         .parses = true,
+         .w = 1,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_JOURNAL "=true",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_DEFAULT,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_JOURNAL "=true",
+         .parses = true,
+         .w = 1,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=1000",
+         .parses = true,
+         .w = 2,
+         .wtimeoutms = 1000,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=2147483648",
+         .parses = true,
+         .w = 2,
+         .wtimeoutms = 2147483648LL,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=majority&" MONGOC_URI_WTIMEOUTMS "=1000",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_MAJORITY,
+         .wtimeoutms = 1000,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_WTIMEOUTMS "=1000",
+         .parses = true,
+         .w = MONGOC_WRITE_CONCERN_W_TAG,
+         .wtag = "mytag",
+         .wtimeoutms = 1000,
+      },
+      {
+         .uri = "mongodb://localhost/?" MONGOC_URI_W "=0&" MONGOC_URI_JOURNAL "=true",
+         .parses = false,
+         .w = MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED,
+         .log_msg = "Journal conflicts with w value [" MONGOC_URI_W "=0]",
+      },
+      {0}};
 
-   for (i = 0; tests[i].uri; i++) {
-      t = &tests[i];
+   for (int i = 0; tests[i].uri; i++) {
+      const write_concern_test *const t = &tests[i];
 
       capture_logs (true);
-      uri = mongoc_uri_new (t->uri);
+      mongoc_uri_t *const uri = mongoc_uri_new (t->uri);
 
       if (tests[i].log_msg) {
          ASSERT_CAPTURED_LOG (tests[i].uri, MONGOC_LOG_LEVEL_WARNING, tests[i].log_msg);
@@ -1213,23 +2117,23 @@ test_mongoc_uri_write_concern (void)
       capture_logs (false); /* clear captured logs */
 
       if (t->parses) {
-         BSON_ASSERT (uri);
+         ASSERT_WITH_MSG (uri, "expected the URI to be parsed as valid");
       } else {
-         BSON_ASSERT (!uri);
+         ASSERT_WITH_MSG (!uri, "expected the URI to be parsed as invalid");
          continue;
       }
 
-      wr = mongoc_uri_get_write_concern (uri);
-      BSON_ASSERT (wr);
+      const mongoc_write_concern_t *const wr = mongoc_uri_get_write_concern (uri);
+      ASSERT (wr);
 
-      BSON_ASSERT (t->w == mongoc_write_concern_get_w (wr));
+      ASSERT_CMPINT32 (t->w, ==, mongoc_write_concern_get_w (wr));
 
       if (t->wtag) {
-         BSON_ASSERT (0 == strcmp (t->wtag, mongoc_write_concern_get_wtag (wr)));
+         ASSERT_CMPSTR (t->wtag, mongoc_write_concern_get_wtag (wr));
       }
 
       if (t->wtimeoutms) {
-         BSON_ASSERT (t->wtimeoutms == mongoc_write_concern_get_wtimeout_int64 (wr));
+         ASSERT_CMPINT64 (t->wtimeoutms, ==, mongoc_write_concern_get_wtimeout_int64 (wr));
       }
 
       mongoc_uri_destroy (uri);
@@ -1447,21 +2351,18 @@ test_mongoc_uri_tls_ssl (const char *tls
 
    bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=foo.pem", tlsCertificateKeyFile);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (mongoc_uri_get_ssl (uri));
    ASSERT (mongoc_uri_get_tls (uri));
    mongoc_uri_destroy (uri);
 
 
    bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=foo.pem", tlsCAFile);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (mongoc_uri_get_ssl (uri));
    ASSERT (mongoc_uri_get_tls (uri));
    mongoc_uri_destroy (uri);
 
 
    bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tlsAllowInvalidCertificates);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (mongoc_uri_get_ssl (uri));
    ASSERT (mongoc_uri_get_tls (uri));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false));
@@ -1470,7 +2371,6 @@ test_mongoc_uri_tls_ssl (const char *tls
 
    bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tlsAllowInvalidHostnames);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (mongoc_uri_get_ssl (uri));
    ASSERT (mongoc_uri_get_tls (uri));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, false));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false));
@@ -1480,7 +2380,6 @@ test_mongoc_uri_tls_ssl (const char *tls
    bson_snprintf (
       url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=foo.pem", tls, tlsCertificateKeyFile);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (!mongoc_uri_get_ssl (uri));
    ASSERT (!mongoc_uri_get_tls (uri));
    mongoc_uri_destroy (uri);
 
@@ -1488,7 +2387,6 @@ test_mongoc_uri_tls_ssl (const char *tls
    bson_snprintf (
       url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=foo.pem", tls, tlsCertificateKeyFile);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (!mongoc_uri_get_ssl (uri));
    ASSERT (!mongoc_uri_get_tls (uri));
    mongoc_uri_destroy (uri);
 
@@ -1496,7 +2394,6 @@ test_mongoc_uri_tls_ssl (const char *tls
    bson_snprintf (
       url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=true", tls, tlsAllowInvalidCertificates);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (!mongoc_uri_get_ssl (uri));
    ASSERT (!mongoc_uri_get_tls (uri));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false));
    ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false));
@@ -1506,7 +2403,6 @@ test_mongoc_uri_tls_ssl (const char *tls
    bson_snprintf (
       url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=false", tls, tlsAllowInvalidHostnames);
    uri = mongoc_uri_new (url_buffer);
-   ASSERT (!mongoc_uri_get_ssl (uri));
    ASSERT (!mongoc_uri_get_tls (uri));
    ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, true));
    ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, true));
@@ -1711,8 +2607,8 @@ test_mongoc_uri_local_threshold_ms (void
 }
 
 
-#define INVALID(_uri, _host)                                           \
-   BSON_ASSERT (!mongoc_uri_upsert_host ((_uri), (_host), 1, &error)); \
+#define INVALID(_uri, _host)                                                                               \
+   ASSERT_WITH_MSG (!mongoc_uri_upsert_host ((_uri), (_host), 1, &error), "expected host upsert to fail"); \
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "must be subdomain")
 
 #define VALID(_uri, _host) ASSERT_OR_PRINT (mongoc_uri_upsert_host ((_uri), (_host), 1, &error), error)
@@ -1738,19 +2634,19 @@ test_mongoc_uri_srv (void)
    ASSERT (!mongoc_uri_new ("mongodb+srv://foo%00bar"));
    ASSERT (!mongoc_uri_new ("mongodb+srv://example.com"));
 
-   uri = mongoc_uri_new ("mongodb+srv://c.d.com");
-   BSON_ASSERT (uri);
+   uri = mongoc_uri_new_with_error ("mongodb+srv://c.d.com", &error);
+   ASSERT_OR_PRINT (uri, error);
    ASSERT_CMPSTR (mongoc_uri_get_srv_hostname (uri), "c.d.com");
-   BSON_ASSERT (mongoc_uri_get_hosts (uri) == NULL);
+   ASSERT (mongoc_uri_get_hosts (uri) == NULL);
 
    /* tls is set to true when we use SRV */
-   ASSERT_MATCH (mongoc_uri_get_options (uri), "{'tls': true}");
+   ASSERT_EQUAL_BSON (tmp_bson ("{'tls': true}"), mongoc_uri_get_options (uri));
 
    /* but we can override tls */
    mongoc_uri_destroy (uri);
-   uri = mongoc_uri_new ("mongodb+srv://c.d.com/?tls=false");
-   BSON_ASSERT (uri);
-   ASSERT_MATCH (mongoc_uri_get_options (uri), "{'tls': false}");
+   uri = mongoc_uri_new_with_error ("mongodb+srv://c.d.com/?tls=false", &error);
+   ASSERT_OR_PRINT (uri, error);
+   ASSERT_EQUAL_BSON (tmp_bson ("{'tls': false}"), mongoc_uri_get_options (uri));
 
    INVALID (uri, "com");
    INVALID (uri, "foo.com");
@@ -1779,9 +2675,9 @@ test_mongoc_uri_srv (void)
 
    /* trailing dot is OK */
    uri = mongoc_uri_new ("mongodb+srv://service.consul.");
-   BSON_ASSERT (uri);
+   ASSERT (uri);
    ASSERT_CMPSTR (mongoc_uri_get_srv_hostname (uri), "service.consul.");
-   BSON_ASSERT (mongoc_uri_get_hosts (uri) == NULL);
+   ASSERT (mongoc_uri_get_hosts (uri) == NULL);
 
    INVALID (uri, ".consul.");
    INVALID (uri, "service.consul");
@@ -1804,7 +2700,7 @@ test_mongoc_uri_srv (void)
       mongoc_uri_parse_options (uri, option, true /* from dns */, &error);                           \
       ASSERT_ERROR_CONTAINS (                                                                        \
          error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "prohibited in TXT record"); \
-      BSON_ASSERT (!bson_has_field (mongoc_uri_get_##_where (uri), lkey));                           \
+      ASSERT (!bson_has_field (mongoc_uri_get_##_where (uri), lkey));                                \
       bson_free (lkey);                                                                              \
    } while (0)
 
@@ -1816,13 +2712,13 @@ test_mongoc_uri_dns_options (void)
    bson_error_t error;
 
    uri = mongoc_uri_new ("mongodb+srv://a.b.c");
-   BSON_ASSERT (uri);
+   ASSERT (uri);
 
-   BSON_ASSERT (!mongoc_uri_parse_options (uri, "tls=false", true /* from dsn */, &error));
+   ASSERT (!mongoc_uri_parse_options (uri, "tls=false", true /* from dsn */, &error));
 
    ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "prohibited in TXT record");
 
-   ASSERT_MATCH (mongoc_uri_get_options (uri), "{'tls': true}");
+   ASSERT_EQUAL_BSON (tmp_bson ("{'tls': true}"), mongoc_uri_get_options (uri));
 
    /* key we want to set, value, value type, whether it's option/credential */
    PROHIBITED (MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, true, bool, options);
@@ -1830,8 +2726,8 @@ test_mongoc_uri_dns_options (void)
    PROHIBITED (MONGOC_URI_GSSAPISERVICENAME, malicious, utf8, credentials);
 
    /* the two options allowed in TXT records, case-insensitive */
-   BSON_ASSERT (mongoc_uri_parse_options (uri, "authsource=db", true, NULL));
-   BSON_ASSERT (mongoc_uri_parse_options (uri, "RepLIcaSET=rs", true, NULL));
+   ASSERT (mongoc_uri_parse_options (uri, "authsource=db", true, NULL));
+   ASSERT (mongoc_uri_parse_options (uri, "RepLIcaSET=rs", true, NULL));
 
    /* test that URI string overrides TXT record options */
    mongoc_uri_destroy (uri);
@@ -1867,16 +2763,16 @@ test_mongoc_uri_utf8 (void)
    bson_error_t err;
 
    /* start of 3-byte character, but it's incomplete */
-   BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://\xe8\x03", &err));
+   ASSERT (!mongoc_uri_new_with_error ("mongodb://\xe8\x03", &err));
    ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI");
 
    /* start of 6-byte CESU-8 character, but it's incomplete */
-   BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://\xfa", &err));
+   ASSERT (!mongoc_uri_new_with_error ("mongodb://\xfa", &err));
    ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI");
 
 
    /* "a<NIL>z" with NIL expressed as two-byte sequence */
-   BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://a\xc0\x80z", &err));
+   ASSERT (!mongoc_uri_new_with_error ("mongodb://a\xc0\x80z", &err));
    ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI");
 }
 
@@ -1897,6 +2793,7 @@ test_mongoc_uri_duplicates (void)
 #define RECREATE_URI(opts)                                                               \
    if (1) {                                                                              \
       mongoc_uri_destroy (uri);                                                          \
+      clear_captured_logs ();                                                            \
       uri = mongoc_uri_new_with_error ("mongodb://user:pwd@localhost/test?" opts, &err); \
       ASSERT_OR_PRINT (uri, err);                                                        \
    } else                                                                                \
@@ -1909,7 +2806,7 @@ test_mongoc_uri_duplicates (void)
 #define BSON_ITER_UNIQUE(key)                                             \
    do {                                                                   \
       bson_iter_t tmp;                                                    \
-      BSON_ASSERT (bson_iter_init_find (&iter, bson, key));               \
+      ASSERT (bson_iter_init_find (&iter, bson, key));                    \
       tmp = iter;                                                         \
       while (bson_iter_next (&tmp)) {                                     \
          if (strcmp (bson_iter_key (&tmp), key) == 0) {                   \
@@ -1924,172 +2821,182 @@ test_mongoc_uri_duplicates (void)
    RECREATE_URI (MONGOC_URI_APPNAME "=a&" MONGOC_URI_APPNAME "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_APPNAME);
    str = mongoc_uri_get_appname (uri);
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
-   RECREATE_URI (MONGOC_URI_AUTHMECHANISM "=a&" MONGOC_URI_AUTHMECHANISM "=b");
+   RECREATE_URI (MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA-1&" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA-256");
    ASSERT_LOG_DUPE (MONGOC_URI_AUTHMECHANISM);
    bson = mongoc_uri_get_credentials (uri);
    BSON_ITER_UNIQUE (MONGOC_URI_AUTHMECHANISM);
-   BSON_ASSERT (strcmp (bson_iter_utf8 (&iter, NULL), "b") == 0);
+   ASSERT (strcmp (bson_iter_utf8 (&iter, NULL), "SCRAM-SHA-256") == 0);
 
    RECREATE_URI (MONGOC_URI_AUTHMECHANISMPROPERTIES "=a:x&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=b:y");
    ASSERT_LOG_DUPE (MONGOC_URI_AUTHMECHANISMPROPERTIES);
    bson = mongoc_uri_get_credentials (uri);
-   BSON_ASSERT (bson_compare (bson, tmp_bson ("{'authmechanismproperties': {'b': 'y' }}")) == 0);
+   ASSERT_EQUAL_BSON (tmp_bson ("{'authmechanismproperties': {'b': 'y'}}"), bson);
+
+   RECREATE_URI (MONGOC_URI_AUTHMECHANISMPROPERTIES "=a:x&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=b:y");
+   ASSERT_LOG_DUPE (MONGOC_URI_AUTHMECHANISMPROPERTIES);
+   bson = mongoc_uri_get_credentials (uri);
+   ASSERT_EQUAL_BSON (tmp_bson ("{'authmechanismproperties': {'b': 'y' }}"), bson);
 
    RECREATE_URI (MONGOC_URI_AUTHSOURCE "=a&" MONGOC_URI_AUTHSOURCE "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_AUTHSOURCE);
    str = mongoc_uri_get_auth_source (uri);
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
    RECREATE_URI (MONGOC_URI_CANONICALIZEHOSTNAME "=false&" MONGOC_URI_CANONICALIZEHOSTNAME "=true");
+   ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_CANONICALIZEHOSTNAME,
+                        MONGOC_LOG_LEVEL_WARNING,
+                        MONGOC_URI_CANONICALIZEHOSTNAME " is deprecated, use " MONGOC_URI_AUTHMECHANISMPROPERTIES
+                                                        " with CANONICALIZE_HOST_NAME instead");
    ASSERT_LOG_DUPE (MONGOC_URI_CANONICALIZEHOSTNAME);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_CANONICALIZEHOSTNAME, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_CANONICALIZEHOSTNAME, false));
 
    RECREATE_URI (MONGOC_URI_CONNECTTIMEOUTMS "=1&" MONGOC_URI_CONNECTTIMEOUTMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_CONNECTTIMEOUTMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) == 2);
 
 #if defined(MONGOC_ENABLE_COMPRESSION_SNAPPY) && defined(MONGOC_ENABLE_COMPRESSION_ZLIB)
    RECREATE_URI (MONGOC_URI_COMPRESSORS "=snappy&" MONGOC_URI_COMPRESSORS "=zlib");
    ASSERT_LOG_DUPE (MONGOC_URI_COMPRESSORS);
    bson = mongoc_uri_get_compressors (uri);
-   BSON_ASSERT (bson_compare (bson, tmp_bson ("{'zlib': 'yes'}")) == 0);
+   ASSERT_EQUAL_BSON (tmp_bson ("{'zlib': 'yes'}"), bson);
 #endif
 
-   /* exception: GSSAPISERVICENAME does not overwrite. */
    RECREATE_URI (MONGOC_URI_GSSAPISERVICENAME "=a&" MONGOC_URI_GSSAPISERVICENAME "=b");
    ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_GSSAPISERVICENAME,
                         MONGOC_LOG_LEVEL_WARNING,
+                        MONGOC_URI_GSSAPISERVICENAME " is deprecated, use " MONGOC_URI_AUTHMECHANISMPROPERTIES
+                                                     " with SERVICE_NAME instead");
+   ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_GSSAPISERVICENAME,
+                        MONGOC_LOG_LEVEL_WARNING,
                         "Overwriting previously provided value for 'gssapiservicename'");
    bson = mongoc_uri_get_credentials (uri);
-   BSON_ASSERT (bson_compare (bson, tmp_bson ("{'authmechanismproperties': {'SERVICE_NAME': 'b' }}")) == 0);
+   ASSERT_EQUAL_BSON (tmp_bson ("{'authmechanismproperties': {'SERVICE_NAME': 'b' }}"), bson);
 
    RECREATE_URI (MONGOC_URI_HEARTBEATFREQUENCYMS "=500&" MONGOC_URI_HEARTBEATFREQUENCYMS "=501");
    ASSERT_LOG_DUPE (MONGOC_URI_HEARTBEATFREQUENCYMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0) == 501);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0) == 501);
 
    RECREATE_URI (MONGOC_URI_JOURNAL "=false&" MONGOC_URI_JOURNAL "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_JOURNAL);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_JOURNAL, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_JOURNAL, false));
 
    RECREATE_URI (MONGOC_URI_LOCALTHRESHOLDMS "=1&" MONGOC_URI_LOCALTHRESHOLDMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_LOCALTHRESHOLDMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_MAXPOOLSIZE "=1&" MONGOC_URI_MAXPOOLSIZE "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_MAXPOOLSIZE);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXPOOLSIZE, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXPOOLSIZE, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS
                                            "=1&" MONGOC_URI_MAXSTALENESSSECONDS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_MAXSTALENESSSECONDS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXSTALENESSSECONDS, 0) == 2);
-
-   RECREATE_URI (MONGOC_URI_MINPOOLSIZE "=1&" MONGOC_URI_MINPOOLSIZE "=2");
-   ASSERT_LOG_DUPE (MONGOC_URI_MINPOOLSIZE);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MINPOOLSIZE, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXSTALENESSSECONDS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_READCONCERNLEVEL "=local&" MONGOC_URI_READCONCERNLEVEL "=majority");
    ASSERT_LOG_DUPE (MONGOC_URI_READCONCERNLEVEL);
    rc = mongoc_uri_get_read_concern (uri);
-   BSON_ASSERT (strcmp (mongoc_read_concern_get_level (rc), "majority") == 0);
+   ASSERT (strcmp (mongoc_read_concern_get_level (rc), "majority") == 0);
 
    RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_READPREFERENCE "=primary");
    ASSERT_LOG_DUPE (MONGOC_URI_READPREFERENCE);
    rp = mongoc_uri_get_read_prefs_t (uri);
-   BSON_ASSERT (mongoc_read_prefs_get_mode (rp) == MONGOC_READ_PRIMARY);
+   ASSERT (mongoc_read_prefs_get_mode (rp) == MONGOC_READ_PRIMARY);
 
    /* exception: read preference tags get appended. */
    RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_READPREFERENCETAGS
                                            "=a:x&" MONGOC_URI_READPREFERENCETAGS "=b:y");
-   bson = mongoc_uri_get_read_prefs (uri);
-   BSON_ASSERT (bson_compare (bson, tmp_bson ("{'0': {'a': 'x'}, '1': {'b': 'y'}}")) == 0);
+   ASSERT_NO_CAPTURED_LOGS (mongoc_uri_get_string (uri));
+   rp = mongoc_uri_get_read_prefs_t (uri);
+   bson = mongoc_read_prefs_get_tags (rp);
+   ASSERT_EQUAL_BSON (tmp_bson ("[{'a': 'x'}, {'b': 'y'}]"), bson);
 
    RECREATE_URI (MONGOC_URI_REPLICASET "=a&" MONGOC_URI_REPLICASET "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_REPLICASET);
    str = mongoc_uri_get_replica_set (uri);
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
    RECREATE_URI (MONGOC_URI_RETRYREADS "=false&" MONGOC_URI_RETRYREADS "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_RETRYREADS);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYREADS, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYREADS, false));
 
    RECREATE_URI (MONGOC_URI_RETRYWRITES "=false&" MONGOC_URI_RETRYWRITES "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_RETRYWRITES);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYWRITES, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYWRITES, false));
 
    RECREATE_URI (MONGOC_URI_SAFE "=false&" MONGOC_URI_SAFE "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_SAFE);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SAFE, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SAFE, false));
 
    RECREATE_URI (MONGOC_URI_SERVERMONITORINGMODE "=auto&" MONGOC_URI_SERVERMONITORINGMODE "=stream");
    ASSERT_LOG_DUPE (MONGOC_URI_SERVERMONITORINGMODE);
    str = mongoc_uri_get_server_monitoring_mode (uri);
-   BSON_ASSERT (strcmp (str, "stream") == 0);
+   ASSERT_CMPSTR (str, "stream");
 
    RECREATE_URI (MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=1&" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_SERVERSELECTIONTIMEOUTMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_SERVERSELECTIONTRYONCE "=false&" MONGOC_URI_SERVERSELECTIONTRYONCE "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_SERVERSELECTIONTRYONCE);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false));
 
    RECREATE_URI (MONGOC_URI_SOCKETCHECKINTERVALMS "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_SOCKETCHECKINTERVALMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_SOCKETTIMEOUTMS "=1&" MONGOC_URI_SOCKETTIMEOUTMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_SOCKETTIMEOUTMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_TLS "=false&" MONGOC_URI_TLS "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_TLS);
-   BSON_ASSERT (mongoc_uri_get_tls (uri));
+   ASSERT (mongoc_uri_get_tls (uri));
 
    RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILE "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILE "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_TLSCERTIFICATEKEYFILE);
    str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "");
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
    RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD);
    str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "");
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
    RECREATE_URI (MONGOC_URI_TLSCAFILE "=a&" MONGOC_URI_TLSCAFILE "=b");
    ASSERT_LOG_DUPE (MONGOC_URI_TLSCAFILE);
    str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "");
-   BSON_ASSERT (strcmp (str, "b") == 0);
+   ASSERT_CMPSTR (str, "b");
 
    RECREATE_URI (MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "=false&" MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "=true");
    ASSERT_LOG_DUPE (MONGOC_URI_TLSALLOWINVALIDCERTIFICATES);
-   BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false));
+   ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false));
 
    RECREATE_URI (MONGOC_URI_W "=1&" MONGOC_URI_W "=0");
    ASSERT_LOG_DUPE (MONGOC_URI_W);
    wc = mongoc_uri_get_write_concern (uri);
-   BSON_ASSERT (mongoc_write_concern_get_w (wc) == 0);
+   ASSERT (mongoc_write_concern_get_w (wc) == 0);
 
    /* exception: a string write concern takes precedence over an int */
    RECREATE_URI (MONGOC_URI_W "=majority&" MONGOC_URI_W "=0");
-   ASSERT_LOG_DUPE (MONGOC_URI_W);
+   ASSERT_NO_CAPTURED_LOGS (mongoc_uri_get_string (uri));
    wc = mongoc_uri_get_write_concern (uri);
-   BSON_ASSERT (mongoc_write_concern_get_w (wc) == MONGOC_WRITE_CONCERN_W_MAJORITY);
+   ASSERT (mongoc_write_concern_get_w (wc) == MONGOC_WRITE_CONCERN_W_MAJORITY);
 
    RECREATE_URI (MONGOC_URI_WAITQUEUETIMEOUTMS "=1&" MONGOC_URI_WAITQUEUETIMEOUTMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_WAITQUEUETIMEOUTMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_WTIMEOUTMS "=1&" MONGOC_URI_WTIMEOUTMS "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_WTIMEOUTMS);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2);
-   BSON_ASSERT (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2);
 
    RECREATE_URI (MONGOC_URI_ZLIBCOMPRESSIONLEVEL "=1&" MONGOC_URI_ZLIBCOMPRESSIONLEVEL "=2");
    ASSERT_LOG_DUPE (MONGOC_URI_ZLIBCOMPRESSIONLEVEL);
-   BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0) == 2);
+   ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0) == 2);
 
    mongoc_uri_destroy (uri);
 }
@@ -2190,19 +3097,18 @@ test_one_tls_option_enables_tls (void)
                          MONGOC_URI_SSLALLOWINVALIDHOSTNAMES "=true",
                          MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK "=true",
                          MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK "=true"};
-   int i;
 
-   for (i = 0; i < sizeof (opts) / sizeof (opts[0]); i++) {
+   mlib_foreach_arr (const char *, opt, opts) {
       mongoc_uri_t *uri;
       bson_error_t error;
       char *uri_string;
 
-      uri_string = bson_strdup_printf ("mongodb://localhost:27017/?%s", opts[i]);
+      uri_string = bson_strdup_printf ("mongodb://localhost:27017/?%s", *opt);
       uri = mongoc_uri_new_with_error (uri_string, &error);
       bson_free (uri_string);
       ASSERT_OR_PRINT (uri, error);
       if (!mongoc_uri_get_tls (uri)) {
-         test_error ("unexpected tls not enabled when following option set: %s\n", opts[i]);
+         test_error ("unexpected tls not enabled when following option set: %s\n", *opt);
       }
       mongoc_uri_destroy (uri);
    }
@@ -2286,7 +3192,7 @@ test_parses_long_ipv6 (void)
    }
 }
 
-void
+static void
 test_uri_depr (void)
 {
    // Test behavior of deprecated URI options.
@@ -2318,6 +3224,69 @@ test_uri_depr (void)
    }
 }
 
+// Additional slashes and commas for embedded URIs given to connection options.
+// e.g. authMechanismProperties=TOKEN_RESOURCE=mongodb://foo,ENVIRONMENT=azure
+//                                                     ^^   ^
+static void
+test_uri_uri_in_options (void)
+{
+#define TEST_QUERY MONGOC_URI_AUTHMECHANISMPROPERTIES "=TOKEN_RESOURCE:mongodb://token-resource,ENVIRONMENT:azure"
+#define TEST_PROPS "{'TOKEN_RESOURCE': 'mongodb://token-resource', 'ENVIRONMENT': 'azure'}"
+
+   capture_logs (true);
+
+   bson_error_t error;
+
+   // Simple.
+   {
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://localhost?" TEST_QUERY, &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      bson_t props;
+      ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+      ASSERT_MATCH (&props, TEST_PROPS);
+      mongoc_uri_destroy (uri);
+   }
+
+   // With auth database.
+   {
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://localhost/db?" TEST_QUERY, &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      bson_t props;
+      ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+      ASSERT_MATCH (&props, TEST_PROPS);
+      mongoc_uri_destroy (uri);
+   }
+
+   // With userinfo.
+   {
+      mongoc_uri_t *const uri = mongoc_uri_new_with_error ("mongodb://user:pass@localhost/db?" TEST_QUERY, &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      bson_t props;
+      ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+      ASSERT_MATCH (&props, TEST_PROPS);
+      mongoc_uri_destroy (uri);
+   }
+
+   // With alternate hosts.
+   {
+      mongoc_uri_t *const uri =
+         mongoc_uri_new_with_error ("mongodb://user:pass@host1:27017,host2:27018/db?" TEST_QUERY, &error);
+      ASSERT_NO_CAPTURED_LOGS ("mongoc_uri_new_with_error");
+      ASSERT_OR_PRINT (uri, error);
+      bson_t props;
+      ASSERT (mongoc_uri_get_mechanism_properties (uri, &props));
+      ASSERT_MATCH (&props, TEST_PROPS);
+      mongoc_uri_destroy (uri);
+   }
+
+   capture_logs (false);
+
+#undef TEST_QUERY
+}
+
 void
 test_uri_install (TestSuite *suite)
 {
@@ -2330,7 +3299,7 @@ test_uri_install (TestSuite *suite)
    TestSuite_Add (suite, "/Uri/read_concern", test_mongoc_uri_read_concern);
    TestSuite_Add (suite, "/Uri/write_concern", test_mongoc_uri_write_concern);
    TestSuite_Add (suite, "/HostList/from_string", test_mongoc_host_list_from_string);
-   TestSuite_Add (suite, "/Uri/auth_mechanism_properties", test_mongoc_uri_authmechanismproperties);
+   TestSuite_Add (suite, "/Uri/auth_mechanisms", test_mongoc_uri_auth_mechanisms);
    TestSuite_Add (suite, "/Uri/functions", test_mongoc_uri_functions);
    TestSuite_Add (suite, "/Uri/ssl", test_mongoc_uri_ssl);
    TestSuite_Add (suite, "/Uri/tls", test_mongoc_uri_tls);
@@ -2346,4 +3315,5 @@ test_uri_install (TestSuite *suite)
    TestSuite_Add (suite, "/Uri/options_casing", test_casing_options);
    TestSuite_Add (suite, "/Uri/parses_long_ipv6", test_parses_long_ipv6);
    TestSuite_Add (suite, "/Uri/depr", test_uri_depr);
+   TestSuite_Add (suite, "/Uri/uri_in_options", test_uri_uri_in_options);
 }
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-util.c 2.0.2-1/src/libmongoc/tests/test-mongoc-util.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-util.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-util.c	2025-06-19 15:42:22.000000000 +0000
@@ -4,9 +4,6 @@
 #include "TestSuite.h"
 #include "test-conveniences.h"
 
-#undef MONGOC_LOG_DOMAIN
-#define MONGOC_LOG_DOMAIN "test-util"
-
 
 static void
 test_command_name (void)
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-write-concern.c 2.0.2-1/src/libmongoc/tests/test-mongoc-write-concern.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-write-concern.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-write-concern.c	2025-06-19 15:42:22.000000000 +0000
@@ -53,17 +53,11 @@ test_write_concern_basic (void)
     * Test defaults.
     */
    ASSERT (write_concern);
-   ASSERT (!mongoc_write_concern_get_fsync (write_concern));
    ASSERT (!mongoc_write_concern_get_journal (write_concern));
    ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT);
    ASSERT (!mongoc_write_concern_get_wtimeout_int64 (write_concern));
    ASSERT (!mongoc_write_concern_get_wmajority (write_concern));
 
-   mongoc_write_concern_set_fsync (write_concern, true);
-   ASSERT (mongoc_write_concern_get_fsync (write_concern));
-   mongoc_write_concern_set_fsync (write_concern, false);
-   ASSERT (!mongoc_write_concern_get_fsync (write_concern));
-
    mongoc_write_concern_set_journal (write_concern, true);
    ASSERT (mongoc_write_concern_get_journal (write_concern));
    mongoc_write_concern_set_journal (write_concern, false);
@@ -91,12 +85,11 @@ test_write_concern_basic (void)
    /*
     * Check generated bson.
     */
-   mongoc_write_concern_set_fsync (write_concern, true);
    mongoc_write_concern_set_journal (write_concern, true);
 
    bson = _mongoc_write_concern_get_bson (write_concern);
    ASSERT (bson);
-   ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter));
+   ASSERT (!bson_iter_init_find (&iter, bson, "fsync")); // Deprecated "fsync" removed in C driver 2.0.
    ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter));
    ASSERT (bson_iter_init_find (&iter, bson, "w") && BSON_ITER_HOLDS_INT32 (&iter) && bson_iter_int32 (&iter) == 3);
 
@@ -122,7 +115,7 @@ test_write_concern_bson_omits_defaults (
 
    bson = _mongoc_write_concern_get_bson (write_concern);
    ASSERT (bson);
-   ASSERT (!bson_iter_init_find (&iter, bson, "fsync"));
+   ASSERT (!bson_iter_init_find (&iter, bson, "fsync")); // fsync removed in C driver 2.0.
    ASSERT (!bson_iter_init_find (&iter, bson, "j"));
 
    mongoc_write_concern_destroy (write_concern);
@@ -130,7 +123,7 @@ test_write_concern_bson_omits_defaults (
 
 
 static void
-test_write_concern_bson_includes_false_fsync_and_journal (void)
+test_write_concern_bson_includes_false_journal (void)
 {
    mongoc_write_concern_t *write_concern;
    const bson_t *bson;
@@ -142,12 +135,11 @@ test_write_concern_bson_includes_false_f
     * Check generated bson.
     */
    ASSERT (write_concern);
-   mongoc_write_concern_set_fsync (write_concern, false);
    mongoc_write_concern_set_journal (write_concern, false);
 
    bson = _mongoc_write_concern_get_bson (write_concern);
    ASSERT (bson);
-   ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter));
+   ASSERT (!bson_iter_init_find (&iter, bson, "fsync")); // Deprecated "fsync" removed in C driver 2.0.
    ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter));
    ASSERT (!bson_iter_init_find (&iter, bson, "w"));
 
@@ -156,75 +148,43 @@ test_write_concern_bson_includes_false_f
 
 
 static void
-test_write_concern_fsync_and_journal_w1_and_validity (void)
+test_write_concern_journal_w1_validity (void)
 {
    mongoc_write_concern_t *write_concern = mongoc_write_concern_new ();
 
-   /*
-    * Journal and fsync should imply w=1 regardless of w; however, journal and
-    * fsync logically conflict with w=0 and w=-1, so a write concern with such
-    * a combination of options will be considered invalid.
-    */
 
-   /* No write concern needs GLE, but not "valid" */
+   // Journal should imply acknowledgement regardless of w.
+   // Journal is invalid with w=0 and w=-1.
+
+   /* No write concern needs acknowledgement, but not "valid" */
    ASSERT (mongoc_write_concern_is_acknowledged (NULL));
    ASSERT (!mongoc_write_concern_is_valid (NULL));
 
-   /* Default write concern needs GLE and is valid */
+   /* Default write concern needs acknowledgement and is valid */
    ASSERT (write_concern);
    ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
    ASSERT (mongoc_write_concern_is_valid (write_concern));
    ASSERT (!mongoc_write_concern_journal_is_set (write_concern));
 
-   /* w=0 does not need GLE and is valid */
+   /* w=0 does not need acknowledgement and is valid */
    mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED);
    ASSERT (!mongoc_write_concern_is_acknowledged (write_concern));
    ASSERT (mongoc_write_concern_is_valid (write_concern));
    ASSERT (!mongoc_write_concern_journal_is_set (write_concern));
 
-   /* fsync=true needs GLE, but it conflicts with w=0 */
-   mongoc_write_concern_set_fsync (write_concern, true);
-   ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
-   ASSERT (!mongoc_write_concern_is_valid (write_concern));
-   ASSERT (!mongoc_write_concern_journal_is_set (write_concern));
-   mongoc_write_concern_set_fsync (write_concern, false);
-
-   /* journal=true needs GLE, but it conflicts with w=0 */
+   /* journal=true needs acknowledgement, but it conflicts with w=0 */
    mongoc_write_concern_set_journal (write_concern, true);
    ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
    ASSERT (!mongoc_write_concern_is_valid (write_concern));
    ASSERT (mongoc_write_concern_journal_is_set (write_concern));
    mongoc_write_concern_set_journal (write_concern, false);
 
-   /* w=-1 does not need GLE and is valid */
-   mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED);
-   ASSERT (!mongoc_write_concern_is_acknowledged (write_concern));
+   /* w=-1 is considered valid (server is expected to error) */
+   mongoc_write_concern_set_w (write_concern, -1);
    ASSERT (mongoc_write_concern_is_valid (write_concern));
-   ASSERT (mongoc_write_concern_journal_is_set (write_concern));
 
-   /* fsync=true needs GLE, but it conflicts with w=-1 */
-   mongoc_write_concern_set_fsync (write_concern, true);
-   ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
-   ASSERT (!mongoc_write_concern_is_valid (write_concern));
-   ASSERT (mongoc_write_concern_journal_is_set (write_concern));
-
-   /* journal=true needs GLE, but it conflicts with w=-1 */
-   mongoc_write_concern_set_fsync (write_concern, false);
+   /* journal=true with w=default needs acknowledgement and is valid */
    mongoc_write_concern_set_journal (write_concern, true);
-   ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
-   ASSERT (mongoc_write_concern_journal_is_set (write_concern));
-
-   /* fsync=true with w=default needs GLE and is valid */
-   mongoc_write_concern_set_journal (write_concern, false);
-   mongoc_write_concern_set_fsync (write_concern, true);
-   mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT);
-   ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
-   ASSERT (mongoc_write_concern_is_valid (write_concern));
-   ASSERT (mongoc_write_concern_journal_is_set (write_concern));
-
-   /* journal=true with w=default needs GLE and is valid */
-   mongoc_write_concern_set_journal (write_concern, false);
-   mongoc_write_concern_set_fsync (write_concern, true);
    mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT);
    ASSERT (mongoc_write_concern_is_acknowledged (write_concern));
    ASSERT (mongoc_write_concern_is_valid (write_concern));
@@ -311,7 +271,7 @@ test_write_concern_from_iterator (void)
    _test_write_concern_from_iterator ("{'writeConcern': {'w': 1}}", true, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'j': true}}", true, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'j': false}}", true, false);
-   _test_write_concern_from_iterator ("{'writeConcern': {'w': -1}}", true, false);
+   _test_write_concern_from_iterator ("{'writeConcern': {'w': -1}}", false, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'w': -2}}", false, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'w': -3}}", false, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'w': -4}}", false, false);
@@ -331,7 +291,7 @@ test_write_concern_from_iterator (void)
    _test_write_concern_from_iterator ("{'writeConcern': {'j': 'never'}}", false, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'j': 1.0}}", false, false);
    _test_write_concern_from_iterator ("{'writeConcern': {'fsync': 1.0}}", false, false);
-   _test_write_concern_from_iterator ("{'writeConcern': {'fsync': true}}", true, false);
+   _test_write_concern_from_iterator ("{'writeConcern': {'fsync': true}}", false, false);
 }
 
 
@@ -344,25 +304,20 @@ test_write_concern_always_mutable (void)
 
    ASSERT (write_concern);
 
-   mongoc_write_concern_set_fsync (write_concern, true);
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'fsync': true}");
-
    mongoc_write_concern_set_journal (write_concern, true);
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'fsync': true, 'j': true}");
+   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'j': true}");
 
    mongoc_write_concern_set_w (write_concern, 2);
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'fsync': true, 'j': true}");
+   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'j': true}");
 
    mongoc_write_concern_set_wtimeout_int64 (write_concern, 100);
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'fsync': true, 'j': true, 'wtimeout': 100}");
+   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'j': true, 'wtimeout': 100}");
 
    mongoc_write_concern_set_wmajority (write_concern, 200);
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern),
-                 "{'w': 'majority', 'fsync': true, 'j': true, 'wtimeout': 200}");
+   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 'majority', 'j': true, 'wtimeout': 200}");
 
    mongoc_write_concern_set_wtag (write_concern, "MultipleDC");
-   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern),
-                 "{'w': 'MultipleDC', 'fsync': true, 'j': true, 'wtimeout': 200}");
+   ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 'MultipleDC', 'j': true, 'wtimeout': 200}");
 
    mongoc_write_concern_destroy (write_concern);
 }
@@ -649,11 +604,8 @@ test_write_concern_install (TestSuite *s
    TestSuite_Add (suite, "/WriteConcern/append", test_write_concern_append);
    TestSuite_Add (suite, "/WriteConcern/basic", test_write_concern_basic);
    TestSuite_Add (suite, "/WriteConcern/bson_omits_defaults", test_write_concern_bson_omits_defaults);
-   TestSuite_Add (suite,
-                  "/WriteConcern/bson_includes_false_fsync_and_journal",
-                  test_write_concern_bson_includes_false_fsync_and_journal);
-   TestSuite_Add (
-      suite, "/WriteConcern/fsync_and_journal_gle_and_validity", test_write_concern_fsync_and_journal_w1_and_validity);
+   TestSuite_Add (suite, "/WriteConcern/bson_includes_false_journal", test_write_concern_bson_includes_false_journal);
+   TestSuite_Add (suite, "/WriteConcern/journal_w1_validity", test_write_concern_journal_w1_validity);
    TestSuite_Add (suite, "/WriteConcern/wtimeout_validity", test_write_concern_wtimeout_validity);
    TestSuite_Add (suite, "/WriteConcern/from_iterator", test_write_concern_from_iterator);
    TestSuite_Add (suite, "/WriteConcern/always_mutable", test_write_concern_always_mutable);
diff -pruN 1.30.4-1/src/libmongoc/tests/test-mongoc-x509.c 2.0.2-1/src/libmongoc/tests/test-mongoc-x509.c
--- 1.30.4-1/src/libmongoc/tests/test-mongoc-x509.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/test-mongoc-x509.c	2025-06-19 15:42:22.000000000 +0000
@@ -5,6 +5,10 @@
 #include <mongoc/mongoc-openssl-private.h>
 #endif
 
+#ifdef MONGOC_ENABLE_SSL_SECURE_CHANNEL
+#include <mongoc/mongoc-secure-channel-private.h>
+#endif
+
 #include "TestSuite.h"
 #include "test-libmongoc.h"
 #include "test-conveniences.h" // tmp_bson
@@ -139,6 +143,29 @@ test_x509_auth (void *unused)
    drop_x509_user (true /* ignore "not found" error */);
    create_x509_user ();
 
+   // Test auth works with PKCS8 key:
+   {
+      // Create URI:
+      mongoc_uri_t *uri = get_x509_uri ();
+      {
+         ASSERT (mongoc_uri_set_option_as_utf8 (
+            uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, CERT_TEST_DIR "/client-pkcs8-unencrypted.pem"));
+         ASSERT (mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, CERT_CA));
+      }
+
+      // Try auth:
+      bson_error_t error = {0};
+      bool ok;
+      {
+         mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL);
+         ok = try_insert (client, &error);
+         mongoc_client_destroy (client);
+      }
+
+      ASSERT_OR_PRINT (ok, error);
+      mongoc_uri_destroy (uri);
+   }
+
    // Test auth works:
    {
       // Create URI:
@@ -262,15 +289,179 @@ test_x509_auth (void *unused)
                              "" /* message differs between server versions */);
       mongoc_uri_destroy (uri);
    }
+
+   // Test auth fails when client certificate does not contain public certificate:
+   {
+      // Create URI:
+      mongoc_uri_t *uri = get_x509_uri ();
+      {
+         ASSERT (
+            mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, CERT_TEST_DIR "/client-private.pem"));
+         ASSERT (mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, CERT_CA));
+         ASSERT (mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, true)); // Fail quickly.
+      }
+
+      // Try auth:
+      bson_error_t error = {0};
+      bool ok;
+      {
+         capture_logs (true); // Capture logs before connecting. OpenSSL reads PEM file during client construction.
+         mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL);
+         ok = try_insert (client, &error);
+#if defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+         ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Type is not supported");
+#elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
+         ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Can't find public certificate");
+#elif defined(MONGOC_ENABLE_SSL_OPENSSL)
+         ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Cannot find certificate");
+#endif
+         mongoc_client_destroy (client);
+      }
+
+      ASSERT (!ok);
+#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+      // OpenSSL and Secure Transport fail to create stream (prior to TLS). Resulting in a server selection error.
+      ASSERT_ERROR_CONTAINS (
+         error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "connection error");
+#else
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_CLIENT,
+                             MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                             "" /* message differs between server versions */);
+#endif
+      mongoc_uri_destroy (uri);
+   }
+
+   // Test auth fails when client certificate does not exist:
+   {
+      // Create URI:
+      mongoc_uri_t *uri = get_x509_uri ();
+      {
+         ASSERT (mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, CERT_TEST_DIR "/foobar.pem"));
+         ASSERT (mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, CERT_CA));
+         ASSERT (mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, true)); // Fail quickly.
+      }
+
+      // Try auth:
+      bson_error_t error = {0};
+      bool ok;
+      {
+         mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL);
+         capture_logs (true);
+         ok = try_insert (client, &error);
+#if defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+         ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Cannot find certificate");
+#elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
+         ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Failed to open file");
+#elif defined(MONGOC_ENABLE_SSL_OPENSSL)
+         ASSERT_NO_CAPTURED_LOGS ("tls");
+#endif
+         mongoc_client_destroy (client);
+      }
+
+      ASSERT (!ok);
+#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+      // OpenSSL fails to create stream (prior to TLS). Resulting in a server selection error.
+      ASSERT_ERROR_CONTAINS (
+         error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "connection error");
+#else
+      ASSERT_ERROR_CONTAINS (error,
+                             MONGOC_ERROR_CLIENT,
+                             MONGOC_ERROR_CLIENT_AUTHENTICATE,
+                             "" /* message differs between server versions */);
+#endif
+      mongoc_uri_destroy (uri);
+   }
    drop_x509_user (false);
 }
+
+#ifdef MONGOC_ENABLE_SSL_SECURE_CHANNEL
+static void
+remove_crl_for_secure_channel (const char *crl_path)
+{
+   // Load CRL from file to query system store.
+   PCCRL_CONTEXT crl_from_file = mongoc_secure_channel_load_crl (crl_path);
+   ASSERT (crl_from_file);
+
+   HCERTSTORE cert_store = CertOpenStore (CERT_STORE_PROV_SYSTEM,                  /* provider */
+                                          X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */
+                                          0,                                       /* unused */
+                                          CERT_SYSTEM_STORE_LOCAL_MACHINE,         /* dwFlags */
+                                          L"Root"); /* system store name. "My" or "Root" */
+   ASSERT (cert_store);
+
+   PCCRL_CONTEXT crl_from_store = CertFindCRLInStore (cert_store, 0, 0, CRL_FIND_EXISTING, crl_from_file, NULL);
+   ASSERT (crl_from_store);
+
+   if (!CertDeleteCRLFromStore (crl_from_store)) {
+      test_error (
+         "Failed to delete CRL from store. Delete CRL manually to avoid test errors verifying server certificate.");
+   }
+   CertFreeCRLContext (crl_from_file);
+   CertFreeCRLContext (crl_from_store);
+   CertCloseStore (cert_store, 0);
+}
+#endif // MONGOC_ENABLE_SSL_SECURE_CHANNEL
+
+// test_crl tests connection fails when server certificate is in CRL list.
+static void
+test_crl (void *unused)
+{
+   BSON_UNUSED (unused);
+
+#if defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL)
+   if (!test_framework_getenv_bool ("MONGOC_TEST_SCHANNEL_CRL")) {
+      printf ("Skipping. Test temporarily adds CRL to Windows certificate store. If removing the CRL fails, this may "
+              "cause later test failures and require removing the CRL file manually. To run test anyway, set the "
+              "environment variable MONGOC_TEST_SCHANNEL_CRL=ON\n");
+      return;
+   }
+#elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT)
+   printf ("Skipping. Secure Transport does not support crl_file.\n");
+   return;
+#endif
+
+   // Create URI:
+   mongoc_uri_t *uri = test_framework_get_uri ();
+   ASSERT (mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, true)); // Fail quickly.
+
+   // Create SSL options with CRL file:
+   mongoc_ssl_opt_t ssl_opts = *test_framework_get_ssl_opts ();
+   ssl_opts.crl_file = CERT_TEST_DIR "/crl.pem";
+
+   // Try insert:
+   bson_error_t error = {0};
+   mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL);
+   mongoc_client_set_ssl_opts (client, &ssl_opts);
+   capture_logs (true);
+   bool ok = try_insert (client, &error);
+#ifdef MONGOC_ENABLE_SSL_SECURE_CHANNEL
+   remove_crl_for_secure_channel (ssl_opts.crl_file);
+   ASSERT_CAPTURED_LOG ("tls", MONGOC_LOG_LEVEL_ERROR, "Mutual Authentication failed");
+#else
+   ASSERT_NO_CAPTURED_LOGS ("tls");
+#endif
+   ASSERT (!ok);
+   ASSERT_ERROR_CONTAINS (
+      error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "no suitable servers");
+
+   mongoc_client_destroy (client);
+   mongoc_uri_destroy (uri);
+}
 #endif // MONGOC_ENABLE_SSL
 
 void
 test_x509_install (TestSuite *suite)
 {
 #ifdef MONGOC_ENABLE_SSL
-   TestSuite_AddFull (suite, "/X509/auth", test_x509_auth, NULL, NULL, test_framework_skip_if_no_auth);
+   TestSuite_AddFull (suite,
+                      "/X509/auth",
+                      test_x509_auth,
+                      NULL,
+                      NULL,
+                      test_framework_skip_if_no_auth,
+                      test_framework_skip_if_no_server_ssl);
+   TestSuite_AddFull (suite, "/X509/crl", test_crl, NULL, NULL, test_framework_skip_if_no_server_ssl);
 #endif
 
 #ifdef MONGOC_ENABLE_OCSP_OPENSSL
diff -pruN 1.30.4-1/src/libmongoc/tests/unified/operation.c 2.0.2-1/src/libmongoc/tests/unified/operation.c
--- 1.30.4-1/src/libmongoc/tests/unified/operation.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/unified/operation.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,7 +25,7 @@
 #include "util.h"
 #include <mongoc/utlist.h>
 #include <common-bson-dsl-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 
 typedef struct {
    char *name;
@@ -568,7 +568,7 @@ operation_create_datakey (test_t *test,
             _mongoc_array_append_val (&arr, key_alt_name);
          }
 
-         BSON_ASSERT (mcommon_in_range_unsigned (uint32_t, arr.len));
+         BSON_ASSERT (mlib_in_range (uint32_t, arr.len));
 
          mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, arr.data, (uint32_t) arr.len);
 
@@ -2652,13 +2652,13 @@ operation_download (test_t *test, operat
 
    if (stream) {
       while ((bytes_read = mongoc_stream_read (stream, buf, sizeof (buf), 1, 0)) > 0) {
-         ASSERT (mcommon_in_range_signed (uint32_t, bytes_read));
+         ASSERT (mlib_in_range (uint32_t, bytes_read));
          _mongoc_array_append_vals (&all_bytes, buf, (uint32_t) bytes_read);
       }
       mongoc_gridfs_bucket_stream_error (stream, &op_error);
    }
 
-   ASSERT (mcommon_in_range_unsigned (uint32_t, all_bytes.len));
+   ASSERT (mlib_in_range (uint32_t, all_bytes.len));
    val = bson_val_from_bytes (all_bytes.data, (uint32_t) all_bytes.len);
    result_from_val_and_reply (result, val, NULL, &op_error);
 
@@ -4325,7 +4325,7 @@ operation_run (test_t *test, bson_t *op_
    /* Check for a "session" argument in all operations, it can be
     * an argument for any operation. */
    if (op->arguments && bson_has_field (op->arguments, "session")) {
-      bson_t copied;
+      bson_t copied = BSON_INITIALIZER;
       mongoc_client_session_t *session = NULL;
 
       op->session_id = bson_strdup (bson_lookup_utf8 (op->arguments, "session"));
@@ -4335,7 +4335,7 @@ operation_run (test_t *test, bson_t *op_
          goto done;
       }
 
-      bson_copy_to_excluding (op->arguments, &copied, "session", NULL);
+      bson_copy_to_excluding_noinit (op->arguments, &copied, "session", NULL);
       bson_destroy (op->arguments);
       op->arguments = bson_copy (&copied);
       bson_destroy (&copied);
diff -pruN 1.30.4-1/src/libmongoc/tests/unified/runner.c 2.0.2-1/src/libmongoc/tests/unified/runner.c
--- 1.30.4-1/src/libmongoc/tests/unified/runner.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/unified/runner.c	2025-06-19 15:42:22.000000000 +0000
@@ -25,7 +25,7 @@
 #include <mongoc/utlist.h>
 #include "util.h"
 #include <common-string-private.h>
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
 #include <common-oid-private.h>
 
 typedef struct {
@@ -1443,7 +1443,7 @@ check_failure_is_redacted (const bson_it
 }
 
 static bool
-check_failure_is_detailed (const bson_iter_t *failure_iter, bson_error_t *error)
+check_failure_is_detailed (const bson_iter_t *failure_iter)
 {
    if (BSON_ITER_HOLDS_UTF8 (failure_iter)) {
       // Strings are fine, that's enough proof that the failure was not redacted
@@ -1467,7 +1467,7 @@ check_failure_is_detailed (const bson_it
 }
 
 static bool
-test_check_log_message (test_t *test, bson_t *expected, log_message_t *actual, bson_error_t *error)
+test_check_log_message (bson_t *expected, log_message_t *actual, bson_error_t *error)
 {
    bool ret = false;
 
@@ -1524,7 +1524,7 @@ test_check_log_message (test_t *test, bs
             goto done;
          }
       } else {
-         if (!check_failure_is_detailed (&failure_iter, error)) {
+         if (!check_failure_is_detailed (&failure_iter)) {
             test_diagnostics_error_info ("actual log message: %s", tmp_json (actual->message));
             test_set_error (error, "expected a complete un-redacted 'failure'");
             goto done;
@@ -1550,10 +1550,7 @@ done:
 }
 
 static bool
-test_log_message_should_be_ignored (test_t *test,
-                                    log_message_t *message,
-                                    bson_t *optional_ignore_list,
-                                    bson_error_t *error)
+test_log_message_should_be_ignored (log_message_t *message, bson_t *optional_ignore_list, bson_error_t *error)
 {
    if (optional_ignore_list) {
       bson_iter_t iter;
@@ -1561,7 +1558,7 @@ test_log_message_should_be_ignored (test
       {
          bson_t expected;
          bson_iter_bson (&iter, &expected);
-         bool is_match = test_check_log_message (test, &expected, message, error);
+         bool is_match = test_check_log_message (&expected, message, error);
          bson_destroy (&expected);
          if (is_match) {
             return true;
@@ -1615,8 +1612,7 @@ test_check_expected_log_messages_for_cli
       bson_iter_init (&expected_message_iter, expected_messages) && bson_iter_next (&expected_message_iter);
 
    while (actual_message_iter || expected_message_iter_ok) {
-      if (actual_message_iter &&
-          test_log_message_should_be_ignored (test, actual_message_iter, ignore_messages, error)) {
+      if (actual_message_iter && test_log_message_should_be_ignored (actual_message_iter, ignore_messages, error)) {
          MONGOC_DEBUG ("log message ignored, %s", tmp_json (actual_message_iter->message));
          actual_message_iter = actual_message_iter->next;
          continue;
@@ -1640,7 +1636,7 @@ test_check_expected_log_messages_for_cli
       }
       bson_t expected_message;
       bson_iter_bson (&expected_message_iter, &expected_message);
-      bool is_match = test_check_log_message (test, &expected_message, actual_message_iter, error);
+      bool is_match = test_check_log_message (&expected_message, actual_message_iter, error);
       MONGOC_DEBUG ("log message check %s %s, expected: %s, actual: %s",
                     is_match ? "MATCHED" : "FAILED",
                     error && !is_match ? error->message : "",
@@ -1821,7 +1817,7 @@ done:
 static void
 append_size_t (bson_t *doc, const char *key, size_t value)
 {
-   BSON_ASSERT (mcommon_in_range_unsigned (int64_t, value));
+   BSON_ASSERT (mlib_in_range (int64_t, value));
    BSON_ASSERT (BSON_APPEND_INT64 (doc, key, (int64_t) value));
 }
 
diff -pruN 1.30.4-1/src/libmongoc/tests/unified/util.c 2.0.2-1/src/libmongoc/tests/unified/util.c
--- 1.30.4-1/src/libmongoc/tests/unified/util.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/unified/util.c	2025-06-19 15:42:22.000000000 +0000
@@ -18,7 +18,8 @@
 
 #include "test-conveniences.h"
 #include "TestSuite.h"
-#include <common-cmp-private.h>
+#include <mlib/cmp.h>
+#include <mlib/loop.h>
 
 static int
 cmp_key (const void *a, const void *b)
@@ -74,10 +75,9 @@ mcommon_string_and_type_t bson_type_map[
 bson_type_t
 bson_type_from_string (const char *in)
 {
-   int i;
-   for (i = 0; i < sizeof (bson_type_map) / sizeof (bson_type_map[0]); i++) {
-      if (0 == strcmp (in, bson_type_map[i].str)) {
-         return bson_type_map[i].type;
+   mlib_foreach_arr (mcommon_string_and_type_t, it, bson_type_map) {
+      if (0 == strcmp (in, it->str)) {
+         return it->type;
       }
    }
    test_error ("unrecognized type string: %s\n", in);
@@ -87,10 +87,9 @@ bson_type_from_string (const char *in)
 const char *
 bson_type_to_string (bson_type_t btype)
 {
-   int i;
-   for (i = 0; i < sizeof (bson_type_map) / sizeof (bson_type_map[0]); i++) {
-      if (btype == bson_type_map[i].type) {
-         return bson_type_map[i].str;
+   mlib_foreach_arr (mcommon_string_and_type_t, it, bson_type_map) {
+      if (btype == it->type) {
+         return it->str;
       }
    }
    test_error ("unrecognized type: %d\n", (int) btype);
@@ -149,8 +148,8 @@ usecs_since_epoch (void)
    struct timeval tv;
    BSON_ASSERT (bson_gettimeofday (&tv) == 0);
 
-   BSON_ASSERT (mcommon_in_range_signed (int64_t, tv.tv_sec));
-   BSON_ASSERT (mcommon_in_range_signed (int64_t, tv.tv_usec));
+   BSON_ASSERT (mlib_in_range (int64_t, tv.tv_sec));
+   BSON_ASSERT (mlib_in_range (int64_t, tv.tv_usec));
 
    const int64_t secs = (int64_t) tv.tv_sec;
    const int64_t usecs = (int64_t) tv.tv_usec;
diff -pruN 1.30.4-1/src/libmongoc/tests/x509gen/client-pkcs8-unencrypted.pem 2.0.2-1/src/libmongoc/tests/x509gen/client-pkcs8-unencrypted.pem
--- 1.30.4-1/src/libmongoc/tests/x509gen/client-pkcs8-unencrypted.pem	1970-01-01 00:00:00.000000000 +0000
+++ 2.0.2-1/src/libmongoc/tests/x509gen/client-pkcs8-unencrypted.pem	2025-06-19 15:42:22.000000000 +0000
@@ -0,0 +1,49 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCw1LxQS6Kfv8rb
+2Nd8g4ukiiHWMTJZWrGKJ7Y6fHu4kkpygqiSEDdd5SdU3STpfkzBhZw3nbFyezst
+i3K3TqdGlMbb96ahXjjD24pO4ey9RuI7BJWb9OgpBDgVQVmiqitcf5mYm4ikk1+h
+b7cKQTW8QMIh5wiroE2DnJKw+29K5IkcaOmZzv/llQO8UTZonxBslTdazQdeIRvr
+KaLTjwuXMQvZUpffDqaqqH7t1xkYDLupiTbkVn2S0q8J5Bq7uZPJTWGw+soWIq0w
+3xDZkAi1fXdqzDn8h5JOrYuAsUeVuPkqmrgaYt00KyHMflfsTDchgzwQeaxfx2YP
+qaG/u+lXAgMBAAECggEAE52lviqFwb7e3ABz9wYIqZoBIueWND9RTogVOOuyNclU
+pNtFo95Upf/TmyBlBdnS3ezaZXkCxDZTXDwJ37fD6pp6bNBOFbyEA4YJE7MQNfb1
+BaL+jaxfTJ2BMypqrRa/dKVa/ojSYZ9PjnL8FREiyt1MK8KbPZ6suprV0vgxYldE
+WNP1ROzm3CV5wg4zYgcqgYZqAWHKZEriQN7BNEL1+l+gCDJ+6zekI7/CL8XzIoY8
+MTBj7OCSGslD6RJ6SLugp0YPUfnjS8HyBG0QiqywTRjqsRh/3tayxCXEmC+gkENJ
++06KNLqbC+hqwNTB8WrLI+KKtrBdZaEdeRwOMiL9cQKBgQDnF+OKXD1jIzZQZA0R
+Js026c9yPuANls3fjvEnCZiaL0BR08u33E3ddoyqpHbaTUNQ7EL/mEfS6JeKvuYN
++qYL5dL+Jz9U6xrcINZ6OQSfIYuLBIdjnTbAP/FaAfBSIZUAb0djri+cMabovcoZ
+cDairFqcvhXT7T4e3j2lnXqLywKBgQDD47EIca2mTOMI//PzGv7VVNJ2lz/gI/Yc
+42diilyfjwp9Cd/s1qV7r3/WRmnKkmW9BIZ54DeMwaKA0kSRvz+RpWhEsKKxdzAt
+zRch8JN6IroVLQprfQP/zhCbxSwfFF2kaQyRghMBravri2BEvxqzj+6R5cEoT6g6
+Ffjct4R/JQKBgGR/shfY12WGybcaW8hqvHI2Kl4/08Z1H+EqU9urQ69B/1HWrtCt
+wTsftDr9vSZg1Xaa2OQ5AHtLZaQUMw4/Q/kGoMSgot02RX8X1M5gf48I0pvJg2uh
+0k63QCnpj+7X5enDeyNxfAkMWs76wqpfb5M9K0bhL7LziMF52wtsOgATAoGBAJPP
+v8oLXWjbI4Wq/T035Yq8EoOB5aUP/aoWvfBRT0rm+JcZWGqyHPSTnPbm8vT0OujB
+/WcBlWkUw7ZI84y2rxULpv4N+vXGZghpdUca7W1/vsIz1mT9VIM1zrp7satSBscE
+rYMuj4D4t31pEh9NxKwxs2dL4tC0KtCJu9twbv4xAoGBAJjXWgxPZ1R6ShkTJbie
+jtbkPviVHzO0yOn99ZZMOj8BkY8FjpxmhkUggKvNi0NP/kHMHQmHV/g71lCSbn46
++UVuahmhJszMcvegkIE5jkrT+R0ZcvjpZaEhElJhqQ1TpUhLtKMOkqCb0Pxt59Cp
+l6hKCBKMghQsiIC1iBLzS+YY
+-----END PRIVATE KEY-----
+-----BEGIN CERTIFICATE-----
+MIIDgzCCAmugAwIBAgIDAxOUMA0GCSqGSIb3DQEBCwUAMHkxGzAZBgNVBAMTEkRy
+aXZlcnMgVGVzdGluZyBDQTEQMA4GA1UECxMHRHJpdmVyczEQMA4GA1UEChMHTW9u
+Z29EQjEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTERMA8GA1UECBMITmV3IFlvcmsx
+CzAJBgNVBAYTAlVTMB4XDTE5MDUyMjIzNTU1NFoXDTM5MDUyMjIzNTU1NFowaTEP
+MA0GA1UEAxMGY2xpZW50MRAwDgYDVQQLEwdEcml2ZXJzMQwwCgYDVQQKEwNNREIx
+FjAUBgNVBAcTDU5ldyBZb3JrIENpdHkxETAPBgNVBAgTCE5ldyBZb3JrMQswCQYD
+VQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALDUvFBLop+/
+ytvY13yDi6SKIdYxMllasYontjp8e7iSSnKCqJIQN13lJ1TdJOl+TMGFnDedsXJ7
+Oy2LcrdOp0aUxtv3pqFeOMPbik7h7L1G4jsElZv06CkEOBVBWaKqK1x/mZibiKST
+X6FvtwpBNbxAwiHnCKugTYOckrD7b0rkiRxo6ZnO/+WVA7xRNmifEGyVN1rNB14h
+G+spotOPC5cxC9lSl98Opqqofu3XGRgMu6mJNuRWfZLSrwnkGru5k8lNYbD6yhYi
+rTDfENmQCLV9d2rMOfyHkk6ti4CxR5W4+SqauBpi3TQrIcx+V+xMNyGDPBB5rF/H
+Zg+pob+76VcCAwEAAaMkMCIwCwYDVR0PBAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
+BwMCMA0GCSqGSIb3DQEBCwUAA4IBAQAqRcLAGvYMaGYOV4HJTzNotT2qE0I9THNQ
+wOV1fBg69x6SrUQTQLjJEptpOA288Wue6Jt3H+p5qAGV5GbXjzN/yjCoItggSKxG
+Xg7279nz6/C5faoIKRjpS9R+MsJGlttP9nUzdSxrHvvqm62OuSVFjjETxD39DupE
+YPFQoHOxdFTtBQlc/zIKxVdd20rs1xJeeU2/L7jtRBSPuR/Sk8zot7G2/dQHX49y
+kHrq8qz12kj1T6XDXf8KZawFywXaz0/Ur+fUYKmkVk1T0JZaNtF4sKqDeNE4zcns
+p3xLVDSl1Q5Gwj7bgph9o4Hxs9izPwiqjmNaSjPimGYZ399zcurY
+-----END CERTIFICATE-----
diff -pruN 1.30.4-1/src/tools/mongoc-stat.c 2.0.2-1/src/tools/mongoc-stat.c
--- 1.30.4-1/src/tools/mongoc-stat.c	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/src/tools/mongoc-stat.c	2025-06-19 15:42:22.000000000 +0000
@@ -17,6 +17,7 @@
 
 #include <bson/bson.h>
 #include <mongoc/mongoc.h>
+#include <mlib/cmp.h>
 
 
 #if defined(BSON_OS_UNIX) && defined(MONGOC_ENABLE_SHM_COUNTERS)
@@ -119,7 +120,7 @@ mongoc_counters_new_from_pid (unsigned p
    close (fd);
 
    counters = (mongoc_counters_t *) mem;
-   if (counters->size != len) {
+   if (mlib_cmp (counters->size, !=, len)) {
       perror ("Corrupted shared memory segment.");
       mongoc_counters_destroy (counters);
       return NULL;
@@ -219,7 +220,7 @@ main (int argc, char *argv[])
 #include <stdio.h>
 
 int
-main (int argc, char *argv[])
+main (void)
 {
    fprintf (stderr, "mongoc-stat is not supported on your platform.\n");
    return EXIT_FAILURE;
diff -pruN 1.30.4-1/tools/build.earth 2.0.2-1/tools/build.earth
--- 1.30.4-1/tools/build.earth	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/tools/build.earth	2025-06-19 15:42:22.000000000 +0000
@@ -132,7 +132,7 @@ ADD_SASL:
 # ADD_TLS :
 #   Add TLS libraries to the environment. Requires --tls and --purpose arguments to be
 #   given. The package names can be inferred from the environment or can be provided explicitly
-#   with the --openssl_dev_pkg, --openssl_rt_pkg, --libressl_dev_pkg, and --libressl_rt_pkg
+#   with the --openssl_dev_pkg, --openssl_rt_pkg
 #   command arguments.
 ADD_TLS:
     COMMAND
@@ -140,8 +140,6 @@ ADD_TLS:
     ARG --required purpose
     ARG openssl_dev_pkg
     ARG openssl_rt_pkg
-    ARG libressl_dev_pkg
-    ARG libressl_rt_pkg
     LET to_install=""
     IF __str test "$tls" -ieq OpenSSL
         # Detect package names
@@ -168,31 +166,10 @@ ADD_TLS:
         ELSE
             RUN __fail "Unknown --purpose value “%s”" "$purpose"
         END
-    ELSE IF __str test "$tls" -ieq LibreSSL
-        # Detect package names
-        IF test "$libressl_dev_pkg$libressl_rt_pkg" != ""
-            # Nothing to infer
-        ELSE IF __is_alpine
-            LET libressl_dev_pkg = libressl-dev
-            LET libressl_rt_pkg = libressl
-        ELSE IF __is_ubuntu
-            RUN __fail "Cannot infer the LibreSSL TLS library package names on Ubuntu, as Ubuntu does not ship LibreSSL packages. Set --openssl_dev_pkg and --openssl_rt_pkg or update the ADD_TLS utility."
-        ELSE IF __is_archlinux
-            LET libressl_dev_pkg = libressl
-            LET libressl_rt_pkg = libressl
-        ELSE
-            RUN __fail "Cannot infer the LibreSSL TLS library package names. Set --openssl_dev_pkg and --openssl_rt_pkg or update the ADD_TLS utility"
-        END
-        # Set install targets
-        IF test "$purpose" = build
-            SET to_install = $libressl_dev_pkg $libressl_rt_pkg
-        ELSE IF test "$purpose" = test
-            SET to_install = $libressl_rt_pkg
-        END
     ELSE IF __str test "$tls" -ieq "off"
         # Nothing to do
     ELSE
-        RUN __fail "Unknown --tls value “%s” (Expect one of “OpenSSL”, “LibreSSL”, or “off”)" "$tls"
+        RUN __fail "Unknown --tls value “%s” (Expect one of “OpenSSL” or “off”)" "$tls"
     END
     # Perform the install
     IF test "$to_install" != ""
diff -pruN 1.30.4-1/tools/earthly.sh 2.0.2-1/tools/earthly.sh
--- 1.30.4-1/tools/earthly.sh	2025-05-07 19:11:51.000000000 +0000
+++ 2.0.2-1/tools/earthly.sh	2025-06-19 15:42:22.000000000 +0000
@@ -36,7 +36,7 @@ if ! is-file "$EARTHLY_EXE"; then
 fi
 
 run-earthly() {
-    "$EARTHLY_EXE" --buildkit-image artifactory.corp.mongodb.com/dockerhub/earthly/buildkitd:v${EARTHLY_VERSION} "$@"
+    "$EARTHLY_EXE" "$@"
 }
 
 if is-main; then
