fix: clear stale DeviceGroup before retry to prevent access violation

When connect fails, the partially-created DeviceGroup object could
trigger an access violation in __del__ during GC. Explicitly set
_device_group = None before each retry and in the except handler.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
jim800121chen 2026-03-09 22:21:08 +08:00
parent eca1363298
commit 22d6076568

View File

@ -703,6 +703,10 @@ def handle_connect(params):
last_err = None
for attempt in range(max_retries):
try:
# Clear any stale device group from previous failed attempt
# to prevent DeviceGroup.__del__ access violation during GC.
_device_group = None
if use_without_check:
_log(f"{_device_chip}: connect_devices_without_check(usb_port_id={target_dev.usb_port_id}, connectable={target_dev.is_connectable}) attempt {attempt+1}/{max_retries}...")
_device_group = kp.core.connect_devices_without_check(
@ -717,6 +721,7 @@ def handle_connect(params):
last_err = None
break
except Exception as conn_err:
_device_group = None # prevent __del__ crash on stale handle
last_err = conn_err
_log(f"connect attempt {attempt+1} failed: {conn_err}")
if attempt < max_retries - 1:
@ -738,7 +743,8 @@ def handle_connect(params):
if last_err is not None:
hint = ""
if sys.platform == "win32":
hint = " On Windows, ensure the WinUSB driver is installed for this device (use Zadig: https://zadig.akeo.ie)."
hint = (" On Windows, ensure the WinUSB driver is installed for this device."
" Re-run the installer or use Zadig (https://zadig.akeo.ie).")
raise RuntimeError(f"Failed to connect after {max_retries} attempts: {last_err}.{hint}")
# KL720 needs longer timeout for large NEF transfers (12MB+ over USB)