mongodb/mongo-ruby-driver
66.3
Adequate · 19 September 2026
60.3k
lines of production code
Ruby
primary language
1
measurement over time
What this system is
This system is the official Ruby driver for MongoDB, providing the core infrastructure for connecting to and interacting with MongoDB clusters. It handles low-level network communication via the OP\_MSG wire protocol, manages cluster topology and server discovery, and implements comprehensive authentication mechanisms including SCRAM, Kerberos, and AWS IAM. The driver also supports advanced features such as Client-Side Field Level Encryption, GridFS streaming, and distributed tracing via OpenTelemetry.
How it got here
2008–2014 — Modern driver architecture overhaul
44 changes.
This period focused on a comprehensive rewrite of the MongoDB Ruby driver, replacing legacy wire protocols and internal structures with the modern OP\_MSG protocol and a modular class hierarchy. The work introduced critical security features such as TLS hooks, OCSP verification, and Client-Side Field Level Encryption, while expanding authentication support to include AWS, Kerberos, and SCRAM-SHA-256. Extensive test infrastructure was built to validate the new server discovery, monitoring, and eventing systems.
2015–2017 — Topology, monitoring, and streaming features
31 changes.
The driver underwent significant architectural improvements to server discovery, monitoring, and connection management, introducing dedicated classes for load balancers, server selectors, and session pools. It expanded its monitoring capabilities with detailed SDAM and CMAP events, while also modernizing file handling through a new GridFS streaming API and adding support for DNS seedlist connections.
2018–2021 — Client-Side Encryption and Spec Compliance
31 changes.
This period focused on implementing Client-Side Field Level Encryption (CSFLE) with support for multiple KMS providers, alongside adding MONGODB-AWS and GSSAPI authentication mechanisms. Significant effort was also dedicated to expanding test coverage and infrastructure to ensure strict compliance with MongoDB specifications, including unified test runners and comprehensive integration tests for new features.
2022–2026 — KMS providers, backpressure, and observability
16 changes.
This period focused on expanding Key Management Service support by adding credential handling for AWS, KMIP, Local, and Azure Managed Identity providers. The driver's resilience was improved through a refactored retry mechanism featuring client-side backpressure and overload handling. Additionally, distributed tracing via OpenTelemetry was introduced to enhance observability, accompanied by extensive testing for these new features and FaaS environments.
Features
Add KMS credential and master key document classes for AWS, KMIP, and Local providers
New classes have been added to handle provider-specific configuration for AWS, KMIP, and Local Key Management Service (KMS) providers. The \Mongo::Crypt::KMS::AWS::Credentials\ class now manages AWS access keys, secret keys, and optional session tokens, converting them into the BSON format required by libmongocrypt. Similarly, \Mongo::Crypt::KMS::KMIP::Credentials\ handles KMIP endpoint configuration, and \Mongo::Crypt::KMS::Local::Credentials\ manages the local master key. Additionally, \Mongo::Crypt::KMS::Local::MasterKeyDocument\ provides a uniform interface for local KMS master key parameters. These components enable the driver to correctly format and transmit credentials for these specific KMS backends.
lib/mongo/crypt/kms/aws, lib/mongo/crypt/kms/kmip, lib/mongo/crypt/kms/local · high confidence
Add OpenTelemetry tracing for MongoDB operations and commands
The driver now supports distributed tracing via OpenTelemetry, introducing a new \Mongo::Tracing::OpenTelemetry\ module with dedicated tracers for operations (\OperationTracer\) and server commands (\CommandTracer\). This feature is controlled by the \OTEL\_RUBY\_INSTRUMENTATION\_MONGODB\_ENABLED\ environment variable and allows capturing spans for database operations, including transaction spans, with attributes following MongoDB semantic conventions. To ensure security and reduce noise, the implementation automatically skips tracing for sensitive authentication commands (such as SCRAM) and handshake traffic (hello/ismaster), and query text capture is optional, governed by the \OTEL\_RUBY\_INSTRUMENTATION\_MONGODB\_QUERY\_TEXT\_MAX\_LENGTH\ environment variable.
lib/mongo/tracing · high confidence
Added GSSAPI Kerberos authentication conversation logic
The driver now includes the core logic for handling Kerberos (GSSAPI) authentication conversations. This new \Conversation\ class manages the SASL handshake sequence, including the initial challenge, subsequent challenge-response evaluations, and finalization, by interacting with the \mongo\_kerberos\ native library to perform the actual cryptographic exchanges.
lib/mongo/auth/gssapi · high confidence
Added mongo\_console executable for interactive MongoDB sessions
A new 'mongo\_console' script has been added to the bin directory, providing an interactive Ruby shell for working with MongoDB. The script automatically loads the MongoDB library and includes its namespace into the global scope, allowing users to access MongoDB classes and methods without explicit qualification. It supports both Pry and IRB as the interactive environment, preferring Pry if available, and gracefully falls back to IRB if Pry is not installed. If neither Pry nor IRB is available, the script exits with an error message indicating that one of these tools is required.
bin · high confidence
Expanded server heartbeat and connection pool monitoring events
The monitoring subsystem now exposes detailed events for server health checks and connection pool lifecycle. Users can subscribe to new ServerHeartbeatStarted, ServerHeartbeatSucceeded, and ServerHeartbeatFailed events to track the duration and outcome of server hello/heartbeat calls, including whether they were awaited. Additionally, a comprehensive set of CMAP (Connection Monitoring and Monitoring) events—such as ConnectionCheckedOut, ConnectionCheckedIn, PoolCreated, and PoolCleared—provides visibility into connection acquisition and pool management. The ServerDescriptionChanged event has also been updated to include an 'awaited' flag, allowing users to distinguish between standard and awaited topology changes.
lib/mongo/monitoring/event · high confidence
Introduce Client-Side Field Level Encryption (CSFLE) implementation
This change adds the core Ruby implementation for Client-Side Field Level Encryption, introducing the \Mongo::Crypt\ module and its internal components. It includes the \AutoEncrypter\ and \ExplicitEncrypter\ classes to handle automatic and manual encryption workflows, context classes (\AutoEncryptionContext\, \AutoDecryptionContext\, etc.) to manage the libmongocrypt state machine, and an \EncryptionIO\ class to handle I/O operations with the key vault and KMS providers. The feature also provides FFI bindings to the \libmongocrypt\ C library, requiring version 1.20.0 or higher, and supports configuration via options such as \kms\_providers\, \schema\_map\, and \crypt\_shared\_lib\_path\.
lib/mongo/crypt · high confidence
Introduce GridFS Read and Write stream classes
The GridFS implementation now includes dedicated \Stream::Read\ and \Stream::Write\ classes to handle file I/O. The read stream provides an enumerable interface for iterating through file chunks and supports reading all data at once, while the write stream allows uploading data via a \write\ method and includes an \abort\ capability to delete partially uploaded chunks if an error occurs. Both streams integrate with the driver's timeout handling and respect the configured read/write preferences.
lib/mongo/grid/stream · high confidence
Introduce OP\_MSG wire protocol support with compression and serialization infrastructure
The driver now implements the OP\_MSG wire protocol (replacing the legacy OP\_QUERY) for all commands and writes, enabling features like unacknowledged writes and better logging. This change includes a new serialization framework with dedicated classes for bit vectors, caching hashes, and message sections, as well as a registry for op-code-based message lookup. Additionally, the driver now supports network compression via Snappy, Zlib, and Zstandard (zstd) through the OP\_COMPRESSED message, improving performance for large payloads.
lib/mongo/protocol · high confidence
Introduces IndexView for managing collection indexes
Adds a new Index::View class that provides a dedicated interface for managing indexes on a collection. This view exposes methods to create single indexes (create\_one) or multiple indexes (create\_many), drop specific indexes by name (drop\_one), and drop all indexes (drop\_all). It supports a comprehensive set of index options including unique, background, sparse, partial filters, collation, hidden status, and commit quorum, mapping Ruby options to their corresponding MongoDB server commands.
lib/mongo/index · high confidence
Introduction of SessionPool for managing server sessions
A new SessionPool class has been added to manage the lifecycle of server sessions. It provides methods to check out and check in sessions, automatically pruning those that are dirty or nearing expiration (unless in a load-balanced topology). The pool also handles ending all sessions by sending endSessions commands to the primary server.
lib/mongo/session · high confidence
New DriverBench micro-benchmark suite for performance profiling
The \profile/driver\_bench\ directory now contains a comprehensive benchmarking framework for measuring driver performance. This includes a base runner with configurable iteration and timing limits, and organized suites for BSON encoding/decoding (flat, deep, full), single-document operations (insert, find, command), multi-document operations (bulk insert, find many, GridFS), and parallel workloads (GridFS and LDJSON import/export). A Rake task (\driver\_bench:run\) orchestrates the suite, downloading necessary data files and aggregating results into a JSON report with percentile statistics.
_profile/driver\bench · high confidence
New GridFS stream API for file uploads and downloads
The GridFS library now exposes a new streaming interface for reading and writing files to an FSBucket. This change introduces a central \Stream\ module that manages read and write modes (\:r\ and \:w\) and delegates to specific \Read\ and \Write\ stream classes. Users can now obtain stream objects via \FSBucket::Stream.get\, enabling efficient, stream-based handling of file data rather than loading entire files into memory.
lib/mongo/grid · high confidence
New OCSP verification and caching for TLS sockets
The driver now supports Online Certificate Status Protocol (OCSP) verification for TLS connections. New files in lib/mongo/socket introduce an OcspVerifier that checks server certificate revocation status by querying OCSP responders (following up to 5 redirects) and an OcspCache that stores responses to avoid redundant network calls. The SSL socket implementation has been updated to invoke this verification after the TLS handshake, ensuring that revoked certificates are rejected. This change enhances security by providing real-time certificate validity checks beyond standard CA validation.
lib/mongo/socket · high confidence
New address resolution and AWS authentication infrastructure
The driver introduces a structured address resolution system with dedicated classes for IPv4, IPv6, and Unix sockets, allowing connections to be established via hostnames, IP addresses, or local socket paths. It also adds a new AWS authentication mechanism, including credential caching and request signing logic, enabling MongoDB connections to authenticate using AWS IAM credentials.
mongo · high confidence
New event pub/sub infrastructure in lib/mongo/event
The lib/mongo/event directory now contains the core components for a new event publishing and subscribing system. This includes a base event class (Mongo::Event::Base) with an experimental summary method, a listener queue (Mongo::Event::Listeners) for managing subscriptions, a Publisher module for dispatching events to registered listeners, and a Subscriber module providing a convenience method to add listeners. This change introduces the foundational plumbing for the driver's new global eventing capability.
lib/mongo/event · high confidence
New options mapping utility and redacted options class
The driver introduces a new \Mongo::Options::Mapper\ module to standardize how option keys and values are transformed (e.g., converting keys to strings or symbols) and a new \Mongo::Options::Redacted\ class that wraps options to automatically mask sensitive values like passwords when inspected or converted to strings. This provides a consistent mechanism for normalizing input options and ensures that sensitive credentials are not accidentally exposed in logs or debug output.
lib/mongo/options · high confidence
Repository initialization and development environment setup
The repository has been initialized with a comprehensive set of configuration files to standardize the development environment. This includes a \.rubocop.yml\ configuration targeting Ruby 2.7 with performance and RSpec plugins, a \.rspec\ file for test runner settings, and \.gitignore\/\.dockerignore\ files to manage build artifacts and sensitive data. The project structure is defined by \AGENTS.md\ and \CONTRIBUTING.md\, which outline workflows for linting, testing, and committing. Additionally, the \Rakefile\ has been updated to support RSpec-based testing, gem building, and RuboCop integration, while \product.yml\ and \sbom.json\ establish the project metadata and software bill of materials.
(repo-wide) · high confidence
Support for Azure Managed Identity in KMS
Users can now authenticate to Azure Key Vault using Azure Managed Identity without providing explicit client credentials. This change introduces new internal classes (\AccessToken\, \Credentials\, and \CredentialsRetriever\) that enable the driver to automatically fetch temporary access tokens from the Azure metadata service (169.254.169.254). The \CredentialsRetriever\ handles the HTTP request to the Azure IMDS endpoint, parses the response, and manages token expiration, allowing seamless integration with Azure's managed identity infrastructure for client-side encryption.
lib/mongo/crypt/kms/azure · high confidence
Support for Azure, GCP, KMIP, and Local KMS providers
The library now supports additional Key Management Service (KMS) providers beyond AWS. Users can configure encryption using Azure Key Vault, Google Cloud KMS, KMIP servers, or local keys. This is implemented via new provider modules (azure.rb, gcp.rb, kmip.rb, local.rb) and a central MasterKeyDocument class that routes configuration to the appropriate provider-specific credential and document handlers, enabling the creation of data keys with these new backends.
lib/mongo/crypt/kms · high confidence
Support for MONGODB-AWS authentication with credential caching
The driver now supports the MONGODB-AWS authentication mechanism. This change introduces a new authentication flow that retrieves AWS credentials from multiple sources (client URI, environment variables, EC2/ECS metadata, and Web Identity) and implements a thread-safe cache to store and reuse these credentials, reducing redundant network calls during authentication conversations.
lib/mongo/auth/aws · high confidence
Support for MongoDB SRV (DNS Seedlist) connection strings
Users can now connect to MongoDB clusters using the \mongodb+srv://\ URI scheme, which automatically discovers server addresses via DNS SRV records. This change introduces the \lib/mongo/uri/srv\_protocol.rb\ module to handle the parsing and validation of these URIs, including support for TXT record options and strict hostname validation, enabling seamless connection to sharded clusters without manually specifying all seed hosts.
lib/mongo/uri · high confidence
Removals
Removal of legacy pure-Ruby BSON serialization utilities
The \lib/mongo/util/bson.rb\ and \lib/mongo/util/byte\_buffer.rb\ files have been removed from the codebase. These files contained the original pure-Ruby implementation for BSON serialization, deserialization, and low-level byte buffer management. Their removal indicates that the driver has migrated away from this legacy pure-Ruby code path, likely relying on C extensions or a different internal structure for BSON handling, which simplifies the utility layer and removes deprecated serialization logic.
lib/mongo/util · high confidence
Architecture
Refactored Collection::View into modular components
The collection view implementation has been restructured into distinct modules and classes to improve organization and separation of concerns. Read operations are now handled by the Readable module, write operations by the Writable module, and explain functionality by the Explainable module. New dedicated classes have been introduced for specific aggregation workflows, including Aggregation for standard pipelines, MapReduce for legacy map-reduce operations, and ChangeStream for monitoring collection changes. This refactoring also introduces a Builder module to manage these view types and an Immutable module to handle view configuration, providing a more maintainable foundation for CRUD operations.
lib/mongo/collection/view · high confidence
Behavioural changes
Added SDAM and topology event log subscribers
The driver now includes dedicated log subscribers for Server Discovery and Monitoring (SDAM) and topology lifecycle events. Users will see new debug log messages when servers are opened or closed, when server descriptions change (including server type transitions), and when the topology itself opens, closes, or changes its member composition. These subscribers provide visibility into the driver's internal connection management and topology discovery process.
lib/mongo/monitoring · high confidence
Change streams now automatically resume on transient errors
The ChangeStream implementation now includes built-in retry logic for transient failures. If a read operation fails with an error marked as resumable, the stream will automatically attempt to resume once, allowing applications to maintain continuity without requiring manual error handling for these specific cases.
_lib/mongo/collection/view/change\stream · high confidence
Comprehensive restructuring of the error handling module
The \lib/mongo/error\ directory has been completely reorganized to provide a unified and granular exception hierarchy. All error classes now inherit from \Mongo::Error\, replacing previous inheritance from \RuntimeError\ or \Timeout::Error\ for better consistency and catchability. New specific exceptions have been introduced for distinct failure scenarios, including \AuthError\ and its subclasses (\CredentialCheckError\, \InvalidServerAuthResponse\) for authentication issues, \BadLoadBalancerTarget\ for load-balancing misconfigurations, \ConnectionCheckOutTimeout\ for pool exhaustion, and \ConnectionPerished\ for network errors. The \BulkWriteError\ class has been enhanced to expose server addresses and detailed result documents. Additionally, modules like \ChangeStreamResumable\ and \WriteRetryable\ are now explicitly included in relevant error classes to standardize retry and resume behavior across the driver.
lib/mongo/error · high confidence
Deprecation of the legacy GridFS File API in favor of FSBucket streams
The legacy GridFS file handling API, specifically the \Mongo::Grid::File::Info\ class and its associated metadata handling, is now marked as deprecated. Users will see a deprecation warning indicating that this API will be removed in driver version 3.0 and should migrate to the 'stream' API available on an \FSBucket\ instance instead. This change affects how file metadata and document information are accessed, shifting users away from the older \Grid::File\ structure toward the newer bucket-based streaming interface.
lib/mongo/grid/file · high confidence
Implement PLAIN SASL conversation for LDAP authentication
The LDAP authentication mechanism now uses a dedicated conversation class to manage the PLAIN SASL handshake. This change introduces a structured flow where the client initiates authentication by sending a specific login message containing the user credentials, replacing the previous ad-hoc message construction with a standardized conversation pattern.
lib/mongo/auth/ldap · high confidence
Introduction of dedicated cursor and socket reaper components
The library now includes dedicated \CursorReaper\ and \SocketReaper\ classes within the cluster management layer to handle resource cleanup. The \CursorReaper\ actively tracks active cursor IDs to ensure that cursors garbage collected without being exhausted are properly killed, preventing cursor leaks. The \SocketReaper\ periodically closes idle sockets across the cluster's connection pools to free up resources. These components replace previous ad-hoc cleanup logic with a more structured approach to managing server-side resources.
lib/mongo/cluster/reapers · high confidence
Isolate monitoring connection metadata and behavior
The server monitor now uses a dedicated connection class and a specialized app metadata object. The new AppMetadata class inherits from the standard app metadata but explicitly removes authentication mechanisms, ensuring that the background monitoring socket does not attempt SCRAM authentication. The new Monitor::Connection class manages these sockets, enforcing that they use the connect timeout as the socket timeout and supporting compression algorithms like zstd, snappy, and zlib. This separation ensures monitoring traffic is handled independently of user application connections.
lib/mongo/server/monitor · high confidence
Major authentication refactor and new mechanism support
The authentication subsystem in lib/mongo/auth has been completely restructured to support modern MongoDB security features. This change introduces native support for the MONGODB-AWS authentication mechanism (including credential caching and retrieval from EC2 metadata), adds SCRAM-SHA-256 support alongside the existing SCRAM-SHA-1, and implements SASLPrep for password preparation. It also adds Kerberos (GSSAPI) and LDAP authentication support, while deprecating the legacy MONGODB-CR mechanism. The refactor standardizes authentication conversations, adds speculative authentication support for SCRAM, and introduces a credential cache to improve performance for repeated authentications.
lib/mongo/auth · high confidence
Major driver architecture overhaul with new configuration and TLS hooks
The core library entry point has been completely rewritten to support a modernized architecture. Users now benefit from global TLS context hooks, allowing them to modify SSL/TLS settings (such as cipher suites) for every new connection via \Mongo.tls\_context\_hooks\. The driver introduces a centralized configuration system (\Mongo::Config\) with global options like \csfle\_convert\_to\_ruby\_types\ and \include\_server\_address\_in\_errors\, accessible directly on the \Mongo\ module. Additionally, the driver now includes built-in support for Client-Side Field Level Encryption (via \Mongo::ClientEncryption\), OCSP cache clearing, and a new caching cursor implementation, replacing the previous legacy loading structure.
lib · high confidence
Migrate Evergreen configuration to drivers-evergreen-tools
The \.evergreen\ directory has been restructured to delegate core test orchestration, AWS authentication provisioning, and Docker tooling to the external \drivers-evergreen-tools\ submodule. This migration replaces local scripts and configuration files with symlinks and thin wrappers (e.g., \config.yml\, \aws\, \csfle\) that point to the shared tooling, while retaining project-specific logic in local Ruby scripts like \ec2\_setup.rb\ and \ecs\_setup.rb\. The change updates the CI matrix to include Ruby 4.0 and MongoDB 9.0, and introduces a scheduled \ruby-dev\ build variant to test against upcoming Ruby versions.
.evergreen · high confidence
New server connection and monitoring architecture
The driver introduces a new internal server connection model, including dedicated classes for application metadata, connection handling, connection pooling, server descriptions, and background monitoring. This refactors how the driver manages socket lifecycles, handshakes, authentication, and server discovery/monitoring (SDAM), providing better isolation between monitoring and application connections, improved error diagnostics, and support for modern features like speculative authentication and load-balanced topologies.
lib/mongo/server · high confidence
New server feature detection and load balancer description classes
The driver now includes dedicated classes for managing server capabilities and load balancer topology. The new \Features\ class centralizes the mapping of MongoDB features (such as \merge\_out\_on\_secondary\, \get\_more\_comment\, \retryable\_write\_error\_label\, and \commit\_quorum\) to specific wire protocol versions, providing instance methods like \merge\_out\_on\_secondary\_enabled?\ to check support. It also enforces compatibility by raising errors if the server is too old or too new for the driver's supported wire version range (9–29) and warning if a deprecated wire version is in use. Additionally, a new \LoadBalancer\ class has been added to represent the assumed description of servers behind load balancers, storing the server address.
lib/mongo/server/description · high confidence
Refactored Collection::View and added Queryable Encryption support
The collection query interface has been restructured into modular components (Readable, Writable, Explainable, etc.) to improve maintainability and extend functionality. This change introduces native support for Queryable Encryption (QE2), including automatic creation and dropping of auxiliary encryption collections and indices, with wire version checks to ensure server compatibility. The View API now standardizes option handling, supporting collation, hint, and timeout configurations directly on the view, while deprecating legacy options like snapshot and maxScan.
lib/mongo/collection · high confidence
Refactored MongoDB operations to use the OpMsg protocol and a unified execution layer
The internal operation layer in lib/mongo/operation has been restructured to standardize on the MongoDB op\_msg wire protocol. All core operations (such as find, aggregate, insert, delete, and commands) now delegate to dedicated OpMsg subclasses that handle command construction and execution. This change introduces a new Operation::Context class to manage execution state, including transaction pinning, session handling, and Client-Side Operation Timeouts (CSOT). Additionally, result parsing has been consolidated into specific Result classes for each operation, and legacy wire protocols (OP\_KILL\_CURSORS, OP\_INSERT, etc.) have been removed.
lib/mongo/operation · high confidence
Refactored bulk write operations to support collation, array filters, and hint options
The bulk write implementation has been refactored to correctly handle the collation, array\_filters, and hint options for update and delete operations. This change introduces new internal modules (Combineable, Transformable, Validatable) and combiners (OrderedCombiner, UnorderedCombiner) to group and transform operations before sending them to the server. The BulkWrite::Result class now includes an acknowledged? method and properly aggregates server addresses, ensuring that users receive accurate feedback on write acknowledgment and operation counts across mixed clusters.
_lib/mongo/bulk\write · high confidence
Refactored cluster topology into a class hierarchy with load-balanced support
The cluster topology logic has been restructured from a monolithic implementation into a base class (\Topology::Base\) with specific subclasses for each state: \Single\, \ReplicaSetNoPrimary\, \ReplicaSetWithPrimary\, \Sharded\, \Unknown\, and the new \LoadBalanced\ topology. This change introduces a \LoadBalanced\ mode that enforces a single-server cluster and always reports readable/writable availability, while separating replica set states to distinguish between primary discovery phases. The refactoring also standardizes topology validation, server selection, and compatibility checks across all topology types, ensuring that unknown servers do not incorrectly affect topology compatibility and that logical session timeouts are calculated correctly based on data-bearing servers.
lib/mongo/cluster/topology · high confidence
Refactored connection pool internals with dedicated generation and populator managers
The connection pool implementation has been restructured to improve modularity and correctness. A new GenerationManager class now explicitly handles connection generation tracking and lifecycle management for pipe file descriptors, including logic to scope generations to specific services in load-balanced mode and safely close scheduled file descriptors. Additionally, the Populator class has been extracted into its own file to clearly define its role in maintaining the minimum pool size via a background thread, separating this responsibility from the main pool logic.
_lib/mongo/server/connection\pool · high confidence
Refactored retry logic with client backpressure and overload handling
The retry mechanism in the MongoDB driver has been refactored to introduce client-side backpressure and improved handling of server overload errors. A new backpressure module implements exponential backoff with jitter for retry delays, respecting a server-provided base backoff time when available. The retry workers (read and write) now distinguish between modern and legacy retry paths, with the write worker specifically adding logic to retry operations on overload errors (SystemOverloadedError) using the new backoff strategy. This change improves resilience during transient server load by preventing immediate retry storms.
lib/mongo/retryable · high confidence
Refactored server discovery and monitoring into dedicated topology and SDAM flow classes
The cluster's server discovery and monitoring logic has been restructured to improve clarity and spec compliance. A new \PeriodicExecutor\ class now manages the background threads that trigger monitoring tasks at regular intervals. The complex logic for handling Server Discovery and Monitoring (SDAM) events has been extracted into a dedicated \SdamFlow\ class, which centralizes the processing of server description changes, topology transitions (such as moving from Unknown to ReplicaSet or Sharded), and event publishing. Additionally, a \Topology\ module and its associated subclasses (e.g., \Single\, \LoadBalanced\, \ReplicaSetWithPrimary\) provide a structured way to define and manage cluster topology types, replacing previous ad-hoc state handling.
lib/mongo/cluster · high confidence
Refactored server selection logic into dedicated selector classes
The server selection logic for read preferences (nearest, primary, primary\_preferred, secondary, and secondary\_preferred) has been reorganized into individual classes within the \Mongo::ServerSelector\ module. This change encapsulates the specific selection criteria for each mode, including handling of tag sets, local thresholds, and the deprecated hedged reads option, ensuring that the correct server candidates are returned based on the configured read preference.
_lib/mongo/server\selector · high confidence
Refactored write concern implementation with new base class and validation
The write concern logic has been restructured into a new class hierarchy under \Mongo::WriteConcern\, introducing a \Base\ class that centralizes option handling and validation. This change enforces stricter rules, such as prohibiting the \:journal\ option in favor of \:j\, preventing invalid combinations like \:w =\> 0\ with \:j\ or \:fsync\, and rejecting negative \:w\ values. Two specific implementations, \Acknowledged\ and \Unacknowledged\, now inherit from this base, providing distinct behaviors for the \get\_last\_error\ command and the \acknowledged?\ check, ensuring consistent option transformation and error reporting for write operations.
_lib/mongo/write\concern · high confidence
Removed legacy MongoDB message classes
The internal MongoDB driver implementation has removed several low-level message classes (GetMoreMessage, InsertMessage, KillCursorsMessage, Message, MessageHeader, MsgMessage, QueryMessage, RemoveMessage, UpdateMessage) and the opcodes definition file. This refactoring eliminates the previous per-operation message object structure, simplifying the internal communication layer with the database.
lib/mongo/message · high confidence
Replaced legacy demo script with comprehensive CRUD and aggregation examples
The previous \examples/demo.rb\ script, which used an internal \XGen::Mongo::Driver\ interface, has been removed and replaced with a new set of standalone example scripts (\aggregate.rb\, \create.rb\, \delete.rb\, \index.rb\, \query.rb\, and \update.rb\). These new examples demonstrate standard MongoDB operations using the public API, including inserting documents, querying with various operators and logical conditions, updating and deleting records, creating indexes, and performing aggregation pipelines.
examples · high confidence
SCRAM-SHA-1 conversation implementation with cached salted password
The SCRAM-SHA-1 authentication flow now uses a dedicated conversation class that implements the key derivation (HI) and salted password calculation using OpenSSL's PBKDF2-HMAC-SHA1. To improve performance, the resulting salted password is cached via a credential cache, ensuring it is not recalculated for every authentication attempt within the same session.
lib/mongo/auth/scram · high confidence
SRV record monitoring and resolution behavior changes
The SRV monitor now enforces a 'log-and-continue' policy for invalid or mismatched SRV records, ensuring that DNS resolution errors do not crash the background monitoring thread. Additionally, the driver now supports limiting the number of mongos servers used in sharded cluster connections via the srv\_max\_hosts option, and allows valid SRV hostnames with fewer than three domain parts.
lib/mongo/srv · high confidence
X.509 authentication now supports speculative authentication
The X.509 authentication flow has been refactored to support speculative authentication attempts. The new \lib/mongo/auth/x509/conversation.rb\ implementation exposes a \speculative\_auth\_document\ method that returns the initial handshake document, allowing the client to attempt authentication before the server has fully established the connection state. This change aligns the X.509 mechanism with the broader conversation pattern used by other auth mechanisms, potentially improving connection establishment performance.
lib/mongo/auth/x509 · high confidence
Fixes
Fix cursor batchSize when limit is zero
The driver now correctly handles queries where the limit is set to zero, ensuring the cursor's batch size is calculated properly instead of potentially returning incorrect results or failing. This resolves an issue where a zero limit was not being interpreted as 'no limit' for batch sizing purposes.
lib/mongo · high confidence
Test coverage
Add transaction spec test runner infrastructure; Added AWS Lambda test harness for Ruby MongoDB driver; Added AWS test utility support classes for EC2 and ECS provisioning; Added Atlas connectivity tests; Added CRUD spec test runner infrastructure; Added SDAM event verification helpers for tests; Added comprehensive test coverage for Collection::View modules; Added comprehensive test coverage for the Field Level Encryption (FLE) Ruby bindings; Added connectivity tests for Atlas Secure Frontend Processor (SFP); Added integration tests for FaaS environment detection; Added integration tests for authentication, AWS credentials, and bulk operations; Added integration tests for retryable write operations; Added profiling scripts for connection pool fairness and driver benchmarks; Added shared integration tests for retryable write behaviors; Added shared test suites for app metadata, authentication, protocol, server selection, and sessions; Added spec runners for MongoDB driver specification tests; Added stress tests for connection pool, fork reconnection, and cleanup; Added test coverage for AWS authentication components; Added test coverage for GridFS chunk and file info components; Added test coverage for GridFS components; Added test coverage for GridFS read and write streams; Added test coverage for Mongo::Collection::View equality, cloning, and iteration; Added test coverage for MongoDB Ruby driver error classes; Added test coverage for MongoDB authentication mechanisms; Added test coverage for MongoDB server selector modes; Added test coverage for URI options mapping and SRV protocol validation; Added test coverage for address parsing and validation; Added test coverage for bulk write combinators and result handling; Added test coverage for cluster reapers and topology initialization; Added test coverage for cluster topology types; Added test coverage for server-side components; Added test coverage for session management and transaction retry logic; Added test coverage for socket connection and TLS configuration; Added test for clean exit with SRV URI; Added test infrastructure and documentation for AWS authentication and Kerberos integration; Added test infrastructure for change stream specifications; Added test suite for Mongo::Auth::User::View; Added test suite for core driver components; Added tests for Azure KMS credentials retrieval; Added tests for CMAP monitoring event summaries; Added tests for Client Side Operations Timeout with encryption; Added tests for FaaS environment detection and handshake metadata truncation; Added tests for KMIP MasterKeyDocument serialization; Added tests for KMS credential validation; Added tests for LDAP conversation SASL start behavior; Added tests for Mongo::Options::Redacted behavior; Added tests for Mongo::WriteConcern::Acknowledged and Unacknowledged; Added tests for MongoDB monitoring event classes; Added tests for MongoDB monitoring log subscribers; Added tests for OpenTelemetry command and operation tracers; Added tests for SASL StringPrep validation; Added tests for SRV monitor, resolver, and result validation; Added tests for Server Monitor AppMetadata and Connection timeout behavior; Added tests for X.509 authentication conversation logic; Added tests for client backpressure and overload retry behavior; Added tests for server wire version range and feature checks; Added tests for the Mongo::Index::View API; Added tests for the MongoDB Client-Side Encryption FFI bindings; Added tests for the event publisher and subscriber components; Added unit tests for SCRAM and SCRAM-SHA-256 authentication conversations; Added unit tests for connection pool internals; Added unit tests for the new operations layer; Added unit tests for wire protocol message classes; Expanded integration tests for client-side encryption; Expanded spec test coverage for driver features; New test infrastructure for client lifecycle and authorization; Removal of legacy test suite files; Unified test runner implementation for MongoDB specifications; Updated test certificates for TLS and OCSP verification.
Dependencies
Add drivers-evergreen-tools submodule
The repository now includes the \drivers-evergreen-tools\ submodule (commit 890a93b), which provides shared configuration and utilities for the project's Evergreen CI/CD infrastructure. This change establishes the baseline tooling for running tests and managing server environments, supporting subsequent updates to test matrices, serverless configurations, and KMS integrations.
.mod · high confidence
New gemfiles for testing specific dependencies and features
Added new gemfiles to support testing against specific versions and features: \bson\_4-stable.gemfile\ and \bson\_master.gemfile\ for testing against the \bson-ruby\ repository branches, \bson\_min.gemfile\ for testing with \bson\ version 4.14.1, \mongo\_kerberos.gemfile\ for Kerberos authentication, \snappy\_compression.gemfile\ for Snappy compression, and \zstd\_compression.gemfile\ for Zstandard compression. These files leverage a new \standard.rb\ helper that defines common development, testing, and optional dependencies like \rspec\, \rubocop\, and AWS SDKs.
gemfiles · high confidence
Update minimum Ruby version and BSON dependency
The driver now requires Ruby 2.7 or higher and depends on BSON version 4.14.1 or newer (up to but not including 6.0.0).
(dependencies) · high confidence
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
Baseline
- First survey — no prior run to compare against. CAI 66.
Lenses
- Code Health 89
- Architecture 100
- Maturity 59
- Readiness 62
- Security 69
- Domain Modelling 100
Changes since last survey
- 300 commits — 257 feature/other, 43 fixes
By area
- lib/mongo — 109 commits
- spec/spec_tests — 42 commits
- .evergreen/config — 38 commits
- (root) — 31 commits
- spec/mongo — 17 commits
- docs/reference — 12 commits
- spec/integration — 12 commits
- spec/support — 7 commits
- .github/workflows — 5 commits
- docs/index.txt — 4 commits
- profile/benchmarking — 3 commits
- profile/driver_bench — 2 commits
- spec/runners — 2 commits
- (repo) — 1 commit
- .evergreen/README.md — 1 commit
- .evergreen/config.yml — 1 commit
- .evergreen/download-mongodb.sh — 1 commit
- .evergreen/run-tests-serverless.sh — 1 commit
- .evergreen/run-tests.sh — 1 commit
- .evergreen/tools.rb — 1 commit
Notable commits
- fix: DOCSP-31496: fix API link (#2743)
- fix: DOCSP-37038: Fix broken link (#2841)
- fix: DOCSP-48221 Fix 404 in API Docs (#2924)
- fix: Fix 'occured' -> 'occurred' typos in response_handling.rb retry comments (#3022)
- fix: Fix ArgumentError when a server is marked unknown (#2949)
- fix: Fix CI (#2933)
- fix: Fix CI regressions: OCSP TLS URI options and lint variant (#3066)
- fix: Fix KMIP test setup (#2687)
- fix: Fix broken link in Mongo::Monitoring::Event::Secure (#2775)
- fix: Fix failing atlas connectivity specs (#2829)
- fix: Fix failing specs (#2929)
- fix: Fix failures on latest (#2692)
- fix: Fix serverless tests (#2802)
- fix: Fix test failures (#3106)
- fix: RUBY-3154 Fix broken mongocryptd spec (#2704)
- fix: RUBY-3160 fix all parse errors except bson-tutorials (#2672)
- fix: RUBY-3189 Fix URI Options table (#2673)
- fix: RUBY-3192 Fix serverless test setup (#2679)
- fix: RUBY-3216 Fix wildcard projection spec (#2734)
- fix: RUBY-3332 Fix tailable cursors (#2793)
- …and 280 more
Architecture
- 0 containers · 1 bounded contexts · 0 dependency edges (baseline)
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
mongodb/mongo-ruby-driver was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 19 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit 6375dc607da5b3cbdf85d2c07aa1d2d9b0c6c29c — the exact code this score is about.
- Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
- Measured by watchdog.canine.dev using codehealth-analyzer preprod-b51f968c9b10.