3333from bson .min_key import MinKey
3434from bson .objectid import ObjectId
3535from pymongo import common
36- from pymongo .errors import ConfigurationError
36+ from pymongo .errors import ConfigurationError , PyMongoError
3737from pymongo .read_preferences import ReadPreference , _AggWritePref , _ServerMode
3838from pymongo .server_description import ServerDescription
3939from pymongo .server_selectors import Selection
@@ -563,7 +563,11 @@ def _update_rs_from_primary(
563563 if None not in new_election_tuple :
564564 if None not in max_election_tuple and new_election_tuple < max_election_tuple :
565565 # Stale primary, set to type Unknown.
566- sds [server_description .address ] = server_description .to_unknown ()
566+ sds [server_description .address ] = server_description .to_unknown (
567+ PyMongoError (
568+ f"primary marked stale due to electionId/setVersion mismatch, { new_election_tuple } is stale compared to { max_election_tuple } "
569+ )
570+ )
567571 return _check_has_primary (sds ), replica_set_name , max_set_version , max_election_id
568572 max_election_id = server_description .election_id
569573
@@ -578,7 +582,11 @@ def _update_rs_from_primary(
578582 max_election_safe = tuple (MinKey () if i is None else i for i in max_election_tuple )
579583 if new_election_safe < max_election_safe :
580584 # Stale primary, set to type Unknown.
581- sds [server_description .address ] = server_description .to_unknown ()
585+ sds [server_description .address ] = server_description .to_unknown (
586+ PyMongoError (
587+ f"primary marked stale due to electionId/setVersion mismatch, { new_election_tuple } is stale compared to { max_election_tuple } "
588+ )
589+ )
582590 return _check_has_primary (sds ), replica_set_name , max_set_version , max_election_id
583591 else :
584592 max_election_id = server_description .election_id
@@ -591,7 +599,9 @@ def _update_rs_from_primary(
591599 and server .address != server_description .address
592600 ):
593601 # Reset old primary's type to Unknown.
594- sds [server .address ] = server .to_unknown ()
602+ sds [server .address ] = server .to_unknown (
603+ PyMongoError ("primary marked stale due to discovery of newer primary" )
604+ )
595605
596606 # There can be only one prior primary.
597607 break
0 commit comments