fix: release CAD COM references before apartment shutdown

This commit is contained in:
阿白叔 committed 2026-10-16 11:04:05 +08:00
1 parent f3d2570e48
commit fff39e0645
5 files changed
+143 -4

No files matched your search

@@ -6,6 +6,7 @@ from pathlib import Path
import subprocess
import sys
import time
from traceback import clear_frames
from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
@@ -222,6 +223,7 @@ def _native_action(action, evidence, expected_pid):
import win32gui
import win32process
pythoncom.CoInitialize()
app = None
try:
desktop = os.environ.get('DXPART_DESKTOP', '')
token = os.environ.get('DXPART_SESSION_TOKEN', '')
@@ -260,7 +262,23 @@ def _native_action(action, evidence, expected_pid):
app.Quit()
else:
raise ValueError('unknown private CAD action')
except BaseException as failure:
# Failed COM calls can retain the proxy in their traceback locals,
# including frames reachable only through a chained exception. Keep
# the exception and stack locations, releasing those finished frames.
pending, seen = [failure], set()
while pending:
item = pending.pop()
if item is None or id(item) in seen:
continue
seen.add(id(item))
clear_frames(item.__traceback__)
pending.extend((item.__cause__, item.__context__))
raise
finally:
# Release our automation proxy while its COM apartment is still alive.
# Leaving it in this frame until return defers Release past shutdown.
app = None
pythoncom.CoUninitialize()
return 0
@@ -21,6 +21,9 @@ from typing import Mapping, Sequence
from .errors import TaskCenterError
DESKTOP_RELEASE_TIMEOUT_SECONDS = 5.0
@dataclass(frozen=True, slots=True)
class StartupInfo:
lpDesktop: str
@@ -48,16 +51,20 @@ class _Win32Api:
def confirm_desktop_released(self, name: str):
started = time.monotonic()
deadline = started + 2.0
# USER references can outlive the owned processes briefly. Allow a
# bounded grace period, without delaying the usual immediate release
# or accepting a desktop that still has a persistent external owner.
budget = DESKTOP_RELEASE_TIMEOUT_SECONDS
deadline = started + budget
self.desktop_release_check = {'desktop': name, 'released': None,
'elapsed_seconds': 0.0, 'budget_seconds': 2.0}
'elapsed_seconds': 0.0, 'budget_seconds': budget}
while True:
# EnumDesktops avoids reopening/closing a handle which Windows may
# share with another desktop handle held by this process.
names = self.service.GetProcessWindowStation().EnumDesktops()
present = name.casefold() in {value.casefold() for value in names}
self.desktop_release_check = {'desktop': name, 'released': not present,
'elapsed_seconds': time.monotonic() - started, 'budget_seconds': 2.0,
'elapsed_seconds': time.monotonic() - started, 'budget_seconds': budget,
'caller_pid': os.getpid(), 'caller_thread_id': get_native_id()}
if not present:
return
@@ -68,7 +75,7 @@ class _Win32Api:
except Exception as error:
self.desktop_release_check['caller_desktop_error'] = str(error)
raise TaskCenterError('private_desktop_cleanup', 'owned private desktop still exists after cleanup')
time.sleep(0.05)
time.sleep(min(0.05, max(0.0, deadline - time.monotonic())))
def create_process(self, command: Sequence[str], desktop: str, cwd: Path | None, env: Mapping[str, str] | None,
*, stdout=None, stderr=None):