diff --git a/docs/diagnostics/2026-11-05-desktop-leak-issue5.md b/docs/diagnostics/2026-11-05-desktop-leak-issue5.md new file mode 100644 index 0000000..0c271a3 --- /dev/null +++ b/docs/diagnostics/2026-11-05-desktop-leak-issue5.md @@ -0,0 +1,47 @@ +# Issue 5:私有桌面泄露 + +## 现象 + +代码与回归测试确认:原生 worker 创建私有 Windows Desktop 后,如果 Job Object 创建或 worker 进程启动失败,构造函数直接抛出异常,已创建的 Desktop 和 Job 句柄没有释放。重复失败存在累积私有桌面资源的风险;本次未对现场所有桌面异常作归因。 + +状态读取路径还有一个相同的边界:`read_library_flag` 在进入资源清理保护前加载 UI 依赖;依赖加载异常时,刚创建的私有桌面无法执行 `CloseDesktop`。 + +## 根因 + +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。 +- 两处状态读取均在准备逻辑完成后、`try/finally` 内创建 Desktop,清理时检查资源是否存在。 +- 测试中分离 Desktop、Job、Process、Thread 的接口,断言失败后关闭顺序;覆盖四个构造失败点与进程创建后的终止分支。 + +## 影响范围 + +- 覆盖原生 worker 构造失败,以及状态读取准备和启动阶段的资源清理路径。 +- 正常任务的私有桌面、Job Object、进程树和数据库释放策略不变。 +- 不会切换用户输入桌面,也不会改变中心库写入策略。 + +## 验证 + +- 修复分支完整 `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 -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-main` diff --git a/src/cbb_refresh_verify/desktop_worker.py b/src/cbb_refresh_verify/desktop_worker.py index b7081fa..62c1582 100644 --- a/src/cbb_refresh_verify/desktop_worker.py +++ b/src/cbb_refresh_verify/desktop_worker.py @@ -72,27 +72,52 @@ class DesktopWorker: def __init__(self, command, name, *, interactive_input=False): self.name = name self.interactive_input = bool(interactive_input) - self.desktop = None if self.interactive_input else win32service.CreateDesktop( - name, 0, win32con.GENERIC_ALL, None) - # Track the session, but never use kill-on-close: PCB descendants can - # still own a database transaction when the Python supervisor exits. - self.job = win32job.CreateJobObject(None, '') - self.job_bound = False + self.desktop = None + self.job = None + self.handle = None self.companions = [] self.companion_pids = [] - startup = win32process.STARTUPINFO() - # subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess. - startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input) - self.handle, thread, self.pid, _ = win32process.CreateProcess( - command[0], subprocess.list2cmdline(command), None, None, False, - win32con.CREATE_NO_WINDOW, None, None, startup) - thread.Close() + self.job_bound = False + # Track the session, but never use kill-on-close: PCB descendants can + # still own a database transaction when the Python supervisor exits. try: - win32job.AssignProcessToJobObject(self.job, self.handle) - self.job_bound = True + self.desktop = None if self.interactive_input else win32service.CreateDesktop( + name, 0, win32con.GENERIC_ALL, None) + self.job = win32job.CreateJobObject(None, '') + startup = win32process.STARTUPINFO() + # subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess. + startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input) + self.handle, thread, self.pid, _ = win32process.CreateProcess( + command[0], subprocess.list2cmdline(command), None, None, False, + win32con.CREATE_NO_WINDOW, None, None, startup) + thread.Close() + try: + win32job.AssignProcessToJobObject(self.job, self.handle) + self.job_bound = True + except Exception: + # Kill-through-job is a cleanup guarantee, not a launch requirement. + self.job_bound = False except Exception: - # Kill-through-job is a cleanup guarantee, not a launch requirement. - self.job_bound = False + if self.handle is not None: + try: + win32process.TerminateProcess(self.handle, 1) + except Exception: + pass + try: + self.handle.Close() + except Exception: + pass + if self.job is not None: + try: + self.job.Close() + except Exception: + pass + if self.desktop is not None: + try: + self.desktop.CloseDesktop() + except Exception: + pass + raise def start_companion(self, command): startup = win32process.STARTUPINFO() diff --git a/src/cbb_refresh_verify/mentor_adapter.py b/src/cbb_refresh_verify/mentor_adapter.py index d61f524..a31e8c1 100644 --- a/src/cbb_refresh_verify/mentor_adapter.py +++ b/src/cbb_refresh_verify/mentor_adapter.py @@ -1407,17 +1407,19 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None): if not executable.is_file(): return FLAG_UNKNOWN, f'找不到 Library Manager: {executable}' - deadline = time.monotonic() + timeout_seconds - desktop_name = 'CbbFlagRead_' + os.urandom(5).hex() - desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None) from pywinauto import Desktop from pywinauto.controls.common_controls import TreeViewWrapper + deadline = time.monotonic() + timeout_seconds + desktop_name = 'CbbFlagRead_' + os.urandom(5).hex() + 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( @@ -1461,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 @@ -1490,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( @@ -1549,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 diff --git a/tests/test_desktop_worker.py b/tests/test_desktop_worker.py new file mode 100644 index 0000000..bf96162 --- /dev/null +++ b/tests/test_desktop_worker.py @@ -0,0 +1,140 @@ +import pytest + + +@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 + + closed = [] + error = RuntimeError(failure + ' failed') + + class FakeJob: + def Close(self): + closed.append('job') + + class FakeDesktop: + def CloseDesktop(self): + closed.append('desktop') + + class FakeProcess: + def Close(self): + closed.append('process') + + 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: allocate('process', (process, FakeThread(), 321, 1))) + + 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 caught.value is error + assert closed == expected + + +def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monkeypatch, tmp_path): + import builtins + import win32service + import cbb_refresh_verify.mentor_adapter as module + + created = [] + original_import = builtins.__import__ + executable = tmp_path / 'LibraryManager.exe' + executable.touch() + + def deny_pywinauto(name, *args, **kwargs): + if name == 'pywinauto' or name.startswith('pywinauto.'): + raise ImportError('pywinauto unavailable') + return original_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, '__import__', deny_pywinauto) + monkeypatch.setattr(module, 'library_manager_path', lambda: executable) + monkeypatch.setattr(win32service, 'CreateDesktop', + lambda *args: created.append(args)) + + with pytest.raises(ImportError, match='pywinauto unavailable'): + 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']