fix: release CAD COM references before apartment shutdown
This commit is contained in:
1 parent
f3d2570e48
commit
fff39e0645
5 files changed
+143
-4
No files matched your search
@@ -0,0 +1,34 @@
|
||||
# 私有桌面释放的修复尝试
|
||||
|
||||
本次承接 [实机反馈诊断](2026-10-16-private-desktop-diagnostics.md),修改资源清理行为,未打包或发布新版本。反馈机器的桌面残留尚未在本机复现,以下改动不能作为远端根因已解决的结论。
|
||||
|
||||
## 修改
|
||||
|
||||
1. 私有 CAD 的 probe/quit helper 在 COM 反初始化前释放本地 Application 代理。此前代理保存在函数局部变量中,释放发生在 `CoUninitialize()` 之后。
|
||||
2. 异常路径也清理已退出回溯帧中的局部引用,同时遍历 `__cause__` 和 `__context__`,避免 Quit 或身份校验失败时被调用帧继续持有代理。保留原异常类型、消息、堆栈位置和异常链;遍历有循环保护。
|
||||
3. 桌面消失确认的最大预算从 2 秒调整为 5 秒,每次枚举确认消失后立即返回。没有固定增加正常操作耗时。超过预算仍报错,仍保留 `uncertain.flag` 和库存拒绝门禁,不终止外部占用者。
|
||||
|
||||
第 3 项针对短暂外部引用提供有限恢复机会,不能修复持续泄漏或未知进程的占用。实机旧日志不足以确认是否属于这种短暂引用。
|
||||
|
||||
## 针对性回归
|
||||
|
||||
- 真实 Windows 子进程持有测试桌面句柄约 3 秒后自行关闭:修改前因 2 秒上限失败,修改后确认桌面消失并成功返回;持有者进程仍运行,工具没有终止它。
|
||||
- 持续占用桌面:仍在有限预算内报错;测试只在 finally 中回收自己创建的子进程,随后再次确认释放。
|
||||
- 弱引用检查真实 helper 的 COM 资源顺序,覆盖正常退出、本帧拒绝退出、Quit 抛错、真实 GUID 校验拒绝、显式 cause、隐式 context。最初正常和本帧拒绝两项先失败;初次修正后另外四条异常路径先失败,再补全回溯清理。最终六项通过,并检查堆栈与异常链仍保留。
|
||||
- 最终运行私有 CAD、私有桌面、库存控制、发现缓存、BOM 导入报告五组回归:**104 passed / 29.72 秒**。未重跑完整基础测试或替换验收。
|
||||
|
||||
## 真实 CAD 检查
|
||||
|
||||
修改前先运行一个不打开工程的 CAD 会话,以及一个工程副本读取会话,两者均正常释放,因此没有将它们误报为故障复现。
|
||||
|
||||
修改后在 QApplication 的 QThreadPool 后台线程中调用真实只读工程采集。使用既有测试工程的另一份副本,读取两个旧料号,采集到 5 个真实器件。结果:
|
||||
|
||||
- 整轮 56.89 秒;CAD 启动约 34.89 秒,关闭阶段约 2.45 秒。
|
||||
- quit helper 和 CAD 退出码均为 0;Job 剩余进程为 0,已捕获后代退出句柄均已确认。
|
||||
- 桌面消失确认在首次枚举即通过,没有消耗 5 秒宽限。
|
||||
- 输入桌面前后均为 Default;受控 CAD 未成为前台,也未出现于输入桌面。
|
||||
- 界面 50 毫秒定时器最大采样间隔为 94 毫秒;测试来源工程副本的前后文件哈希一致。
|
||||
|
||||
本地证据位于 `build/feedback-investigation-20261016/qt-reader-after-remediation/`。该真实成功路径检查发生在异常回溯补全之前;后续修改仅涉及异常处理分支,异常路径由上述最终回归验证。此次没有执行 Replace Part,没有操作用户原工程。
|
||||
|
||||
只读代码复核发现并促成了异常回溯持有代理的补全;最终复核未发现新的重要问题。反馈 ZIP 和 Excel 的 SHA256 与输入记录一致,原始反馈未修改,未纳入 Git。
|
||||
@@ -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):
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import weakref
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from threading import Timer
|
||||
from types import SimpleNamespace
|
||||
from traceback import extract_tb
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -12,6 +14,63 @@ from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows COM helper boundary')
|
||||
@pytest.mark.parametrize('failure', [None, 'open_project', 'quit', 'guid', 'cause', 'context'])
|
||||
def test_quit_helper_releases_application_before_com_uninitialization(monkeypatch, tmp_path, failure):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
from dx_productivity.trial_task_center import cad_identity
|
||||
references = []
|
||||
alive_at_uninitialize = []
|
||||
def nested_failure(app):
|
||||
raise ValueError('nested quit error')
|
||||
class Application:
|
||||
def Guid(self):
|
||||
return '{foreign}' if failure == 'guid' else '{owned}'
|
||||
def Quit(self):
|
||||
if failure == 'quit':
|
||||
raise RuntimeError('quit refused')
|
||||
if failure in ('cause', 'context'):
|
||||
try:
|
||||
nested_failure(self)
|
||||
except ValueError as error:
|
||||
if failure == 'cause':
|
||||
raise RuntimeError('quit refused') from error
|
||||
raise RuntimeError('quit refused')
|
||||
def attach(_name):
|
||||
app = Application()
|
||||
references.append(weakref.ref(app))
|
||||
return app
|
||||
monkeypatch.setattr(pythoncom, 'CoInitialize', lambda: None)
|
||||
monkeypatch.setattr(pythoncom, 'CoUninitialize',
|
||||
lambda: alive_at_uninitialize.append(references[0]() is not None))
|
||||
monkeypatch.setattr(win32com.client, 'GetActiveObject', attach)
|
||||
monkeypatch.setattr(runtime, 'current_desktop_name', lambda: 'dx-test')
|
||||
monkeypatch.setattr(cad_identity, 'current_desktop_name', lambda: 'dx-test')
|
||||
monkeypatch.setattr(runtime, 'project_file_path', lambda app: 'open.prj' if failure == 'open_project' else '')
|
||||
for key, value in dict(DXPART_DESKTOP='dx-test', DXPART_CAD_PID='123',
|
||||
DXPART_CAD_GUID='{owned}', DXPART_SESSION_TOKEN='a' * 32).items():
|
||||
monkeypatch.setenv(key, value)
|
||||
if failure == 'open_project':
|
||||
with pytest.raises(ValueError, match='still has a project open'):
|
||||
runtime._native_action('quit', tmp_path / 'evidence.json', 123)
|
||||
elif failure == 'guid':
|
||||
with pytest.raises(ValueError, match='GUID does not match'):
|
||||
runtime._native_action('quit', tmp_path / 'evidence.json', 123)
|
||||
elif failure:
|
||||
with pytest.raises(RuntimeError, match='quit refused') as caught:
|
||||
runtime._native_action('quit', tmp_path / 'evidence.json', 123)
|
||||
assert 'Quit' in [frame.name for frame in extract_tb(caught.value.__traceback__)]
|
||||
if failure in ('cause', 'context'):
|
||||
assert str(caught.value.__context__) == 'nested quit error'
|
||||
assert 'nested_failure' in [frame.name for frame in extract_tb(caught.value.__context__.__traceback__)]
|
||||
if failure == 'cause':
|
||||
assert str(caught.value.__cause__) == 'nested quit error'
|
||||
else:
|
||||
assert runtime._native_action('quit', tmp_path / 'evidence.json', 123) == 0
|
||||
assert alive_at_uninitialize == [False]
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows junction path handling')
|
||||
def test_private_evidence_uses_canonical_root_behind_a_legacy_alias(tmp_path):
|
||||
from dx_productivity.trial_task_center.legacy_paths import _AliasPool
|
||||
|
||||
@@ -11,6 +11,27 @@ from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop, b
|
||||
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, _Win32Process
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows deferred desktop release')
|
||||
def test_release_waits_for_a_temporary_external_reference_without_stopping_its_owner():
|
||||
desktop = PrivateDesktop('dx-test-' + uuid4().hex, enabled=True)
|
||||
desktop.__enter__()
|
||||
retained = subprocess.Popen((sys.executable, '-u', '-c',
|
||||
'import win32service,sys,time; h=win32service.OpenDesktop(sys.argv[1],0,False,1); '
|
||||
'print("ready",flush=True); time.sleep(3); h.CloseDesktop(); '
|
||||
'print("released",flush=True); time.sleep(30)', desktop.name), stdout=subprocess.PIPE)
|
||||
try:
|
||||
assert retained.stdout.readline() == b'ready\r\n'
|
||||
desktop.close()
|
||||
assert desktop.cleanup_record['desktop_confirmation']['released']
|
||||
assert retained.stdout.readline() == b'released\r\n'
|
||||
assert retained.poll() is None
|
||||
finally:
|
||||
retained.terminate()
|
||||
retained.wait(timeout=5)
|
||||
retained.stdout.close()
|
||||
desktop.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows desktop lifetime')
|
||||
def test_release_does_not_report_success_while_another_handle_keeps_desktop_alive():
|
||||
desktop = PrivateDesktop('dx-test-' + uuid4().hex, enabled=True)
|
||||
|
||||
Reference in new issue
Block a user