Cannot find any free port in range 8200..8299 (Appium Android)

The problem

I’m not able to run about 100 Android tests (can run iOS) but I’m able to run less than 100 tests for sure.

Environment

  • Appium version: 1.18.0
  • Desktop OS/version: Mac Os Catalina 10.15.4
  • Node.js version: 12.16.3
  • Npm: 6.14.7
  • Mobile platform/version under test: Android
  • Emulator: PIXEL_3a_API_R

Details

ADB seems to not delete the unused active session. In the end, I see 100 active sessions are there. The available port is 8200 -8299 for UIautomator 2 and that’s why it seems that I’m not able to run more than 100 tests.

Error:

Starting logs capture with command: /Users/username/Library/Android/sdk/platform-tools/adb -P 5037 -s emulator-5554 logcat -v threadtime
     E       selenium.common.exceptions.WebDriverException: Message: An unknown server-side
 error occurred while processing the command. Original error: Cannot find any free port in range
 8200..8299}. Please set the available port number by providing the systemPort capability or
 double check the processes that are locking ports within this range and terminate these which
 are not needed anymore

Link to Appium logs

The above problem could be related to client code but I am not providing any input to cleanup. Is there a way to close previous appium session using client code?

Did you end up finding a solution for this?
I wonder if making sure that driver.quit is called after every test would ensure that the port is freed up?

Execute
adb -s $UDID forward --remove-all
just before launching appium

adb -s $UDID forward --remove-all

did not work for me. I tried

--session-override

this did work, but I am worried about get_screenshot() method as it requires the daemon to create a saperate session. Will update