Repository navigation
fix(interceptor): invalidate event tap CFMachPort on deinit - #999
Conversation
CoreGraphics 内部持有 CGEventTapCreate 返回的 CFMachPort 引用, 仅释放引用不会销毁它; 不调用 CFMachPortInvalidate 的话, WindowServer 会保留 (已禁用的) tap 注册直到进程退出。 ScrollCore/ButtonCore 每次休眠唤醒都重建 5 个 Interceptor, 僵尸注册以每天约 10-25 个的 速度累积, 数百个之后全系统输入明显变卡 (Caldis#970 的成因)。 附带回归测试: Interceptor 销毁后, 本进程在 WindowServer tap 表中的注册数应回到基线。 init 在权限检查前就创建 tap, 所以权限被拒的路径同样覆盖; 仅当 tap 创建本身失败时跳过。 已验证: 修复前测试失败 (残留 1 个注册), 修复后通过。 Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR addresses a CoreGraphics event tap resource leak in Interceptor by explicitly invalidating the underlying CFMachPort during teardown, preventing stale (disabled) WindowServer event-tap registrations from accumulating across sleep/wake or session switches (reported in #970).
Changes:
- Invalidate the event tap
CFMachPortinInterceptor.deinitto ensure WindowServer-side registration is released. - Add a regression test that tracks this process’s
CGGetEventTapListcount acrossInterceptorlifetime. - Wire the new test file into the Xcode test target.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
Mos/Utils/Interceptor.swift |
Calls CFMachPortInvalidate during deinit to prevent leaked WindowServer tap registrations. |
MosTests/InterceptorTapLeakTests.swift |
Adds a regression test asserting tap registrations return to baseline after Interceptor is released. |
Mos.xcodeproj/project.pbxproj |
Adds the new test file to the MosTests build phase. |
Copilot review: 忽略返回码时, 查询失败会被误读成 0 个注册, 让回归信号不可信。 首次查询失败 → XCTSkip; 之后失败 → 断言失败 (nil ≠ 期望值)。 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Independent real-world confirmation of the leak mechanism described in this PR. Environment / 环境
During visible system input/UI lag—most obvious in Dock hover and magnification— No other input utility, Dock, WindowServer, or the Mac itself was restarted. The other 129 disabled registrations remained unchanged, but the Dock became smooth immediately after restarting Mos. A WindowServer CPU resource report generated at the time of the symptom recorded 90 seconds of CPU over 140 seconds (64% average). Its heaviest stack was This independently confirms the root-cause analysis and also shows that the issue affects macOS 15.7.x, not only macOS 26.x. I have not tested a build containing this patch yet, so this validates the mechanism rather than the patched binary itself. |
|
I confirm this bug independently: I diagnosed the same leak on macOS 26.6 with Mos 4.2.1, before I found this PR. I would really love to see this fix merged. |
|
Thank you for the thorough investigation, reproduction, and regression test. I reviewed the code and history; this lifecycle bug appears to have existed for a long time, while later sleep/wake and button-feature iterations amplified how quickly it accumulated. The fix is well targeted. Merging it now—thanks again! |
|
@MrMage Your CFMachPort invalidation fix shipped in 4.3.0-beta (https://github.com/Caldis/Mos/releases/tag/4.3.0-beta-20260820.1), credited inline in the release notes. Thanks for catching a leak class that's easy to miss and hard to observe. |
This PR fixes a resource leak in
Interceptorthat seems to be the cause of #970: after the Mac has been asleep (or users switch accounts) repeatedly, the whole system's input becomes laggy while Mos itself shows ~0% CPU, and killing Mos restores fluidity.The same bug class was recently root-caused, fixed, and confirmed in Karabiner-Elements (pqrs-org/Karabiner-Elements#4505 — includes a video of the symptom) and in Easydict (tisfeng/Easydict#1170, maintainer-confirmed). Scripts to reproduce and observe the leak are at the bottom.
Fixes #970. Plausibly also related to the intermittent post-idle scroll delays in #627.
This fix and analysis were prepared with AI assistance (Claude), per CONTRIBUTING.md: I understand every changed line (except for the Chinese comments 😅), and all measurements/repro outputs below are from a real machine (macOS 26.5, Apple Silicon), reviewed by a human.
Motivation / mechanism
CoreGraphics holds internal references to the
CFMachPortreturned byCGEventTapCreate(observed retain count 4 immediately after creation), so releasing the client reference never deallocates it — and the WindowServer keeps the (disabled) event-tap registration until the process exits. The only correct disposal is an explicitCFMachPortInvalidate.Interceptor.deinitcurrently doesCGEvent.tapEnable(false)+CFRunLoopRemoveSource+ nils the references — without the invalidate. Every deallocatedInterceptortherefore leaks one zombie registration in the WindowServer's global tap table:ScrollCore.disable()+ButtonCore.disable()destroy 5 interceptors on everywillSleepNotification/sessionDidResignActiveNotification, recreated on wake — so each sleep/wake or fast-user-switch cycle leaks 5 registrations.KeyRecorder(one per shortcut-recording session), the monitor window's interceptors, and runtime Accessibility-permission loss/regain cycles.Observed on my machine (Mos 4.2.x, macOS 26.5, uptime 6.5 days): 105–110 stale registrations (~16/day). WindowServer's per-event tap-table processing scales with table size; once the table is large (in my case other leaking apps contributed too), the whole Mac's input turns visibly laggy while the responsible apps sit at 0% CPU — exactly the profile in #970 (WindowServer at 77–100% of a core during window drags, Mos at ~0%). Killing the process reaps all its entries instantly, which is why "kill Mos in Activity Monitor" fixes it and a fresh Mos is fine again.
Standalone verification (no Mos involved): creating 1,000 disabled listen-only taps with the script below makes input noticeably sluggish within seconds; releasing them (or process exit) restores it. Repeating an Interceptor-style teardown (release without invalidate) in a loop grows the owning process's tap-table entry count by exactly 1 per cycle; with
CFMachPortInvalidatethe entry is reaped immediately.What changed
Interceptor.deinit:CFMachPortInvalidate(tap)before dropping the reference (one line + comment). No behavior change on any input path — the tap is already disabled at this point; this only releases the WindowServer-side registration that was previously leaked.MosTests/InterceptorTapLeakTests.swift: creates anInterceptorand asserts the process's ownCGGetEventTapListregistration count returns to baseline once it's gone. Becauseinitcreates the tap before theAXIsProcessTrustedguard instart()can throw, the permission-denied path (e.g. CI) creates-and-leaks too — so the test covers it with the same assertion instead of skipping; it only skips when tap creation itself fails.Validation
xcodebuild -scheme Debug -configuration Debug buildsucceeds with the change, and the regression test was executed both ways (ad-hoc-signed locally, since the project pins the maintainer's signing team): fails on the unfixedInterceptor(XCTAssertEqual failed: ("0") is not equal to ("1")— one residual registration) and passes with the fix.taplist.swift(below) before/after a few sleep/wake cycles — Mos's disabled-entry count should stay at 0 instead of growing by 5 per cycle.Compatibility / risk
Disposal-only change at object teardown; no event-handling, permission, or configuration behavior is touched.
pause()/start()cycles reuse the live tap and are unaffected (invalidate happens only indeinit).Scripts
taplist.swift— enumerate the WindowServer tap table grouped by owning process (swift taplist.swift)Observed on my machine (before restarting the two leaking apps):
bloatgen.swift— demonstrate that stale disabled registrations alone degrade input (swift bloatgen.swift 1000 30)