Unexpected behavior using pymavlink to change flight mode

When changing the mode manually in the Jupyter BlueOS Extension I am getting unexpected changes where the system will enter stabilization mode instead of the intended manual mode. It does not always occur and is intermittent. Is there a way to make my code more consistent - I have changed from checking if the mode is in a list of acceptable modes to hardcoding the mode id into the code but this is only temporary and I’ll need to be able to check the acceptable modes. Here is my code:

from pymavlink import mavutil
import sys
import time
import math
from datetime import datetime
import csv
import numpy as np

# Create the connection
master = mavutil.mavlink_connection('udpin:172.27.144.1:14551')
# Wait a heartbeat before sending commands
master.wait_heartbeat()

mode = 'MANUAL'

#Check to see if manual exists as a valid mode
if mode not in master.mode_mapping():
    print('Unknown mode: {}'.format(mode))
    print('Try:', list(master.mode_mapping.keys()))
    sys.exit(1)
    
#Get mode ID from preset list
mode_id = master.mode_mapping()[mode]
print('mode ID is: ', mode_id)
#Set new mode
master.mav.command_long_send(
    master.target_system, 
    master.target_component,
    mavutil.mavlink.MAV_CMD_DO_SET_MODE,
    0,
    1, mode_id, 0, 0, 0, 0, 0)

#wait for mode change response from system
while True:
    ack_msg = master.recv_match(type='COMMAND_ACK', blocking=True)
    ack_msg = ack_msg.to_dict()
    
    if ack_msg['command'] != mavutil.mavlink.MAV_CMD_DO_SET_MODE:
        continue
    print(mavutil.mavlink.enums['MAV_RESULT'][ack_msg['result']].description)
    break

#Arm the ROV
master.mav.command_long_send(
    master.target_system,
    master.target_component,
    mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM,
    0,
    1, 0, 0, 0, 0, 0, 0)
#Wait for the motors to be armed
master.motors_armed_wait()

print('Motors armed waiting 5 seconds before mission start')
time.sleep(5)

#Disarm the ROV
master.mav.command_long_send(
    master.target_system,
    master.target_component,
    mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM,
    0,
    0, 0, 0, 0, 0, 0, 0)
#Wait for the motors to be disarmed
master.motors_disarmed_wait()

print('Motors are disarmed')

Running this code will output either:

mode ID is: 19 #Manual
mode ID is: 0 #Stabilization

See pymavlink repo mavutil.py mode_mapping_sub