In the driver, all bson_t s are wrapped and owned by DocumentStorage instances, which are used as the underlying storage for Document structs.
In many places in the driver, we provide libmongoc direct access to those bson_t s: for example, when passing in options, or when providing an empty bson_t for libmongoc to fill out with the server's reply.
This is problematic because Document s are designed to be copy-on-write; before any mutations are done on a Document, the Document checks whether its underlying DocumentStorage is uniquely referenced or not. If it's not, the Document will make a copy and cede its original storage before it makes a mutation.
When we circumvent the Document's mutating methods and allow a bson_t to be directly modified, we perform no such checks.
If someone else had a conflicting reference to a document where we do a sneaky mutation like this, we could inadvertently modify their document.
It also breaks Swift guarantees about mutability that a Document struct declared with a let can still be mutated.
We should consider how to make more explicit the places we pass pointers to libmongoc, and ideally differentiate between when a mutable and a non-mutable pointer is being passed.
One idea for this is to provide a mutating method on Document taking a closure, similar to withUnsafePointer, that allows the caller direct write access to the underlying Document. The Document method could do the necessary testing for a unique reference to copy storage if it's required before executing the closure.