Whenever an OperationContext is created, an OperationShardingState is created as a decoration on the OperationContext. When it's created through the regular process of a ServiceEntryPoint, a ScopedOperationCompletionShardingAction is created that will go out of scope at the end of ServiceEntryPoint::execCommandDatabase(). When an OperationContext is created outside of the regular process of a ServiceEntryPoint, a ScopedOperationCompletionShardingAction is not created.
If an exception occurs during a WriteOp that matches StaleConfigInfo or CannotImplicitlyCreateCollectionInfo, the OperationShardingState will set a failed status in an error Status member variable. This Status is expected to be handled and reset by the destructor of ScopedOperationCompletionShardingActions. That is currently the only place where the Status could be reset.
When the OperationShardingState is destructed, an invariant exists that asserts that the error Status member variable in OperationShardingState has been reset.
In the case that an OperationContext is created outside of the ServiceEntryPoint codepath, a ScopedOperationCompletionShardingActions object will never exist to reset the error Status member variable. Upon destruction of the OperationContext, the destructor for the OperationShardingState will be called as well. If there was ever a StaleConfig or CannotImplicitlyCreateCollection status/exception, in a WriteOp, during the lifetime of the OperationContext, the destructor will trip the invariant.
We should either relax the invariant, or think of other appropriate places to reset the OperationShardingState error Status member variable.