test: enforce desktop cleanup interfaces and guard reader setup

This commit is contained in:
阿白叔 committed 2026-11-05 14:59:19 +08:00
1 parent 311d0dd9a4
commit 766d67cb57
3 files changed
+123 -24

No files matched your search

@@ -2,7 +2,7 @@
## 现象
原生 worker 创建私有 Windows Desktop 后,如果 Job Object 创建或 worker 进程启动失败,构造函数直接抛出异常,已创建的 Desktop 和 Job 句柄没有释放。重复触发失败会留下孤立的私有桌面对象,表现为桌面资源持续增加、后续同名或同类原生任务启动异常。
代码与回归测试确认:原生 worker 创建私有 Windows Desktop 后,如果 Job Object 创建或 worker 进程启动失败,构造函数直接抛出异常,已创建的 Desktop 和 Job 句柄没有释放。重复失败存在累积私有桌面资源的风险;本次未对现场所有桌面异常作归因。
状态读取路径还有一个相同的边界:`read_library_flag` 在进入资源清理保护前加载 UI 依赖;依赖加载异常时,刚创建的私有桌面无法执行 `CloseDesktop`。
@@ -11,26 +11,37 @@
1. `DesktopWorker.__init__` 的资源申请跨越多个可能失败的步骤,但没有事务式回滚。
2. 进程句柄、Job 句柄和 Desktop 句柄的释放顺序没有覆盖构造阶段异常。
3. `read_library_flag` 的依赖导入位于 `CreateDesktop` 之后、`try/finally` 之前。
4. `read_library_flag` 和 `read_library_tree_image_map` 都在清理保护外先创建 Desktop,再执行 `Path(library)` 等准备逻辑;准备阶段抛异常时也会泄漏。
## 解决方案
- 在 `DesktopWorker` 构造开始时初始化资源字段,并把 Desktop、Job、worker 创建放入同一异常边界。
- 构造失败时按 worker、Job、Desktop 顺序回滚;已启动的 worker 先终止,避免留下无父级的原生进程。
- 在状态读取创建 Desktop 前完成 UI 依赖加载,确保依赖异常不会产生未受保护的 Desktop。
- 增加回归测试,模拟 worker 启动失败并断言 Desktop、Job 均已关闭。
- 两处状态读取均在准备逻辑完成后、`try/finally` 内创建 Desktop,清理时检查资源是否存在。
- 测试中分离 Desktop、Job、Process、Thread 的接口,断言失败后关闭顺序;覆盖四个构造失败点与进程创建后的终止分支。
## 影响范围
- 只影响原生 worker 启动失败和状态读取依赖加载失败时的清理路径。
- 覆盖原生 worker 构造失败,以及状态读取准备和启动阶段的资源清理路径。
- 正常任务的私有桌面、Job Object、进程树和数据库释放策略不变。
- 不会切换用户输入桌面,也不会改变中心库写入策略。
## 验证
- `python -m pytest -q tests/test_desktop_worker.py tests/test_dialog_agent.py tests/test_native_inspection_release_regressions.py tests/test_verify_diagnostics.py`:33 passed。
- 修复分支完整 `python -m pytest -q --tb=short`:480 passed。
- 同环境、同工作树切换到 `origin/main`(`39985f7`)完整运行相同命令:471 passed。两次运行依次执行,均仅有一条 pywinauto STA 警告。
- `tests/test_desktop_worker.py`:9 passed。两处状态读取准备阶段泄漏的新增测试在修复前 2 failed,修复后通过。
- 变异验证:把回滚中的 `self.job.Close()` 故意改为 `self.job.CloseDesktop()`,测试产生 2 failed;恢复正确代码后通过。
- `python -m compileall -q src tests`:通过。
- `git diff --check`:通过。
- `git -c core.whitespace=cr-at-eol diff origin/main HEAD --check`:通过。命令显式识别 Windows CRLF;仓库 `.gitattributes` 为 `* -text`,保留源文件换行,不依赖本机 `core.whitespace` 配置。
此前 #7 将一次运行中的 `test_backup_recovery.py::test_invalid_source_does_not_touch_target` 失败称为既有基线问题,缺少同环境对照,撤回该归因。本次该用例在 main 与修复分支均通过。审查者在旧 WIP 基线测得的 19 个失败不属于本次从 main 独立提交后的测试范围。
## 合并范围修正
原 PR #7 以 ICDB WIP 分支为父提交,却以 main 为合并目标,实际携带 59 个提交、118 个文件。现从 main 单独 cherry-pick 桌面修复并补充上述审查修正;相对 main 只有本工单、两个源码文件和一个测试文件,共 4 个文件。独立代码复审未发现待处理问题。
## 分支
`codex/desktop-leak-pr`
`codex/desktop-leak-main`
+8 -4
View File
@@ -1412,13 +1412,14 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
deadline = time.monotonic() + timeout_seconds
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
desktop = None
handle = None
pid = None
handled = set()
log = log_path or Path(library).parent/'LogFiles'/'cbb_flag_read_dialogs.jsonl'
try:
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
startup = win32process.STARTUPINFO()
startup.lpDesktop = 'winsta0\\' + desktop_name
handle, thread, pid, _ = win32process.CreateProcess(
@@ -1462,7 +1463,8 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
except Exception:
pass
try:
desktop.CloseDesktop()
if desktop is not None:
desktop.CloseDesktop()
except Exception:
pass
@@ -1491,12 +1493,13 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
if not executable.is_file():
return result
desktop_name = 'CbbStatusRead_' + os.urandom(5).hex()
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
desktop = None
handle = None
pid = None
handled = set()
log = log_path or Path(library).parent/'LogFiles'/'cbb_status_read_dialogs.jsonl'
try:
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
startup = win32process.STARTUPINFO()
startup.lpDesktop = 'winsta0\\' + desktop_name
handle, thread, pid, _ = win32process.CreateProcess(
@@ -1550,7 +1553,8 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
except Exception:
pass
try:
desktop.CloseDesktop()
if desktop is not None:
desktop.CloseDesktop()
except Exception:
pass
+98 -14
View File
@@ -1,33 +1,60 @@
import pytest
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
@pytest.mark.parametrize('failure, expected', [
('desktop', []),
('job', ['desktop']),
('process', ['job', 'desktop']),
('thread', ['thread', 'terminate', 'process', 'job', 'desktop']),
])
def test_constructor_rolls_back_allocated_resources(monkeypatch, failure, expected):
import cbb_refresh_verify.desktop_worker as module
class Handle:
def __init__(self):
self.closed = False
closed = []
error = RuntimeError(failure + ' failed')
class FakeJob:
def Close(self):
self.closed = True
closed.append('job')
class FakeDesktop:
def CloseDesktop(self):
self.closed = True
closed.append('desktop')
desktop = Handle()
job = Handle()
class FakeProcess:
def Close(self):
closed.append('process')
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: desktop)
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: job)
class FakeThread:
def Close(self):
closed.append('thread')
raise error
def allocate(stage, value):
if failure == stage:
raise error
return value
process = FakeProcess()
monkeypatch.setattr(module.win32service, 'CreateDesktop',
lambda *args: allocate('desktop', FakeDesktop()))
monkeypatch.setattr(module.win32job, 'CreateJobObject',
lambda *args: allocate('job', FakeJob()))
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
monkeypatch.setattr(module.win32process, 'CreateProcess',
lambda *args: (_ for _ in ()).throw(RuntimeError('launch failed')))
lambda *args: allocate('process', (process, FakeThread(), 321, 1)))
with pytest.raises(RuntimeError, match='launch failed'):
def terminate(handle, code):
assert handle is process
closed.append('terminate')
monkeypatch.setattr(module.win32process, 'TerminateProcess', terminate)
with pytest.raises(RuntimeError) as caught:
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
assert desktop.closed is True
assert job.closed is True
assert caught.value is error
assert closed == expected
def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monkeypatch, tmp_path):
@@ -54,3 +81,60 @@ def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monk
module.read_library_flag('library.lmc', 'Block')
assert created == []
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
def test_reader_does_not_create_desktop_before_preparation_finishes(monkeypatch, tmp_path, reader):
import win32service
import cbb_refresh_verify.mentor_adapter as module
closed = []
class FakeDesktop:
def CloseDesktop(self):
closed.append('closed')
class InvalidLibrary:
def __fspath__(self):
raise ValueError('invalid library path')
executable = tmp_path / 'LibraryManager.exe'
executable.touch()
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
monkeypatch.setattr(win32service, 'CreateDesktop',
lambda *args: closed.append('created') or FakeDesktop())
with pytest.raises(ValueError, match='invalid library path'):
getattr(module, reader)(InvalidLibrary(), 'Block')
assert closed == []
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path, reader):
import win32service
import win32process
import cbb_refresh_verify.mentor_adapter as module
closed = []
class FakeDesktop:
def CloseDesktop(self):
closed.append('desktop')
def fail(*args):
raise RuntimeError('launch failed')
executable = tmp_path / 'LibraryManager.exe'
executable.touch()
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
monkeypatch.setattr(win32service, 'CreateDesktop', lambda *args: FakeDesktop())
monkeypatch.setattr(win32process, 'CreateProcess', fail)
if reader == 'read_library_flag':
flag, detail = module.read_library_flag(tmp_path / 'library.lmc', 'Block')
assert flag == module.FLAG_UNKNOWN
assert 'launch failed' in detail
else:
with pytest.raises(RuntimeError, match='launch failed'):
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
assert closed == ['desktop']