test(macos): view model lifecycle/leak tests + timer teardown fixes#493
Conversation
Field reports flagged memory leaks and background slowness in the menu bar app. The prime suspect was refresh timers outliving their view models: the UsageViewModel timer was scheduled but never invalidated, and LiveBurnViewModel only stopped via SwiftUI .onDisappear, which an NSPopover close may not fire. Production fixes (surgical): - Add TimerBox, a small @unchecked Sendable holder so a @mainactor view model's nonisolated deinit can invalidate its timer without touching isolated state. - UsageViewModel: store the refresh timer in a TimerBox, add stop(), invalidate in deinit, make start() internal + idempotent, and expose isRefreshTimerActive as a test hook. - LiveBurnViewModel: move its timer into a TimerBox and invalidate it in deinit as a backstop for a missed .onDisappear. Adds ViewModelLifecycleTests covering: both view models deallocate after stop(); LiveBurnViewModel deallocates even without stop(); no runner/provider calls after stop(); and autostart:false has no side effects. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KJPzcAQdxufCWMnap8vTTL
|
Warning Review limit reached
Next review available in: 59 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces a TimerBox helper class to manage repeating Timer instances outside of @MainActor view models (LiveBurnViewModel and UsageViewModel). This ensures that the timers are properly invalidated when the view models deallocate, preventing memory leaks and background CPU usage when views (like popovers) disappear without triggering .onDisappear. It also adds comprehensive lifecycle tests to verify this behavior. The review feedback highlights a critical thread-safety issue in TimerBox: since deinit is nonisolated, it can run on a background thread, leading to unsafe background invalidation of the Timer and potential data races. A thread-safe implementation using NSLock and main-thread dispatching for invalidation is suggested.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| final class TimerBox: @unchecked Sendable { | ||
| var timer: Timer? | ||
|
|
||
| var isActive: Bool { timer?.isValid ?? false } | ||
|
|
||
| /// Invalidates and clears the timer. Safe to call repeatedly. | ||
| func invalidate() { | ||
| timer?.invalidate() | ||
| timer = nil | ||
| } | ||
|
|
||
| deinit { timer?.invalidate() } | ||
| } |
There was a problem hiding this comment.
Thread Safety and Data Race Issues in TimerBox
There are two major issues with the current implementation of TimerBox:
- Thread Safety of
Timer.invalidate():Timer(NSTimer) is not thread-safe, and itsinvalidate()method must be called from the same thread on which the timer was installed (the main thread/run loop in this case). Sincedeinitof the view models isnonisolated, it can run on any background thread if the last reference to the view model is released on a background thread. If that happens,TimerBox'sdeinitwill also run on a background thread, invalidating the timer on a background thread. This can lead to undefined behavior, crashes, or the timer failing to stop. - Data Race on
timer: SinceTimerBoxis marked@unchecked Sendable, the compiler does not enforce data-race safety. Iftimeris assigned on the main thread and read/invalidated on a background thread (duringdeinit), there is a potential data race on thetimerproperty.
Solution
We can use an NSLock to synchronize access to the underlying _timer property, and ensure that invalidate() always dispatches the actual invalidation to the main thread if called from a background thread.
final class TimerBox: @unchecked Sendable {
private let lock = NSLock()
private var _timer: Timer?
var timer: Timer? {
get {
lock.lock(); defer { lock.unlock() }
return _timer
}
set {
lock.lock(); defer { lock.unlock() }
_timer = newValue
}
}
var isActive: Bool {
lock.lock(); defer { lock.unlock() }
return _timer?.isValid ?? false
}
/// Invalidates and clears the timer. Safe to call repeatedly.
func invalidate() {
lock.lock()
let t = _timer
_timer = nil
lock.unlock()
guard let timer = t else { return }
if Thread.isMainThread {
timer.invalidate()
} else {
DispatchQueue.main.async {
timer.invalidate()
}
}
}
deinit {
invalidate()
}
}There was a problem hiding this comment.
2 issues found across 4 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57ccf9f311
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| /// Test hook: whether the refresh timer is currently scheduled. | ||
| var isRefreshTimerActive: Bool { timerBox.isActive } | ||
|
|
||
| deinit { timerBox.invalidate() } |
There was a problem hiding this comment.
Stop the ingest watch from the deinit fallback
When .onDisappear is missed and the live view model is released, start() may already have launched the long-lived burn ingest --watch, but this new deinit path only invalidates the refresh timer. The only path that terminates the watch is stop(), so the background helper can continue running after the Live view is gone even though the timer cleanup succeeded; please also stop the ledger watch from this fallback path.
Useful? React with 👍 / 👎.
…l-2aienr-lifecycle
…llback Review findings on #493: - TimerBox: the timer is now behind an NSLock (deinit can run on any thread that drops the last reference, racing main-thread access), and invalidate() takes the timer out under the lock then calls Timer.invalidate() on the main thread only - directly when already there, else via DispatchQueue.main.async - since a timer must be invalidated on the thread that scheduled it. isActive reads the locked storage, so it is false immediately after invalidate() even while an off-main teardown is still hopping to main. deinit delegates to invalidate(). - LiveBurnViewModel.deinit: also stop the long-lived `burn ingest --watch` child (capture the ledger into a local, then Task { stopIngestWatch() }), so a missed .onDisappear no longer leaks the watch process along with the timer. Not observable via the test fakes (the watch only starts when the runner exposes a bundled binary, and stopping it never touches the runner), so this is a production-only change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KJPzcAQdxufCWMnap8vTTL
…l-2aienr-lifecycle
Stacked on #491 (base:
claude/zealous-maxwell-2aienr).Why
Field reports flag memory leaks and background slowness in the menu bar app. The prime suspects are the refresh timers keeping the view models (and their refresh loops) alive:
UsageViewModelscheduled a repeating 60sTimerinstart()and never invalidated it — nostop(), nodeinitteardown. Its timer closure captures[weak self], so the model itself could deallocate, but the timer kept firing on the main run loop forever.LiveBurnViewModelhasstop(), but nothing guarantees it runs: the view relies on SwiftUI.onDisappear, which may not fire when an NSPopover closes. A missed.onDisappearleaves the refresh timer and the backgroundburn ingest --watchalive.Production fixes (surgical)
TimerBox(@unchecked Sendable): holds theTimeroutside the@MainActorview model's isolation so the model's nonisolateddeinitcan invalidate it without touching actor-isolated state. Its owndeinitalso invalidates, so releasing the owning model tears the timer down. Timers are only ever scheduled/invalidated on the main run loop.UsageViewModel: timer now lives in aTimerBox; addedfunc stop(); invalidate indeinit;start()is now internal (was private) and idempotent; addedvar isRefreshTimerActive: Boolas a test hook.LiveBurnViewModel: timer moved into aTimerBox, invalidated indeinitas a backstop for a missed.onDisappear; addedvar isRefreshTimerActive: Bool.No public/behavioral change for
AppDelegate(holdsUsageViewModelfor app lifetime) orLiveBurnView(samestart()/stop()signatures).Tests (
Tests/BurnTests/ViewModelLifecycleTests.swift)Using a
FakeRunner(reused fromBurnLedgerParsingTests) and a countingCountingProvider, all injected so no network/subprocess is touched:LiveBurnViewModeldeallocates afterstart()/stop().LiveBurnViewModeldeallocates even withoutstop()(weak-self timer +deinitteardown).stop()— waits past one.m5(3s) refresh interval and asserts the call count is frozen and the timer is invalidated.UsageViewModel(autostart: false)has no side effects: zero fetches, zero ledger calls, no timer, immediate dealloc.UsageViewModeldeallocates afterstart()/stop().UsageViewModeltimer stops onstop()(viaisRefreshTimerActive, plus a stable provider fetch count).Timing uses short run-loop pumps +
Task.yield()interleaving; total added CI time is well under the ~15s budget (dominated by the single 3.5s wait in test 3).Note: no Swift toolchain in the authoring environment — CI (
macos-app-tests, macos-14) is the compile/run gate.🤖 Generated with Claude Code
https://claude.ai/code/session_01KJPzcAQdxufCWMnap8vTTL
Generated by Claude Code