Skip to content

test(macos): view model lifecycle/leak tests + timer teardown fixes#493

Merged
willwashburn merged 4 commits into
mainfrom
claude/zealous-maxwell-2aienr-lifecycle
Jul 3, 2026
Merged

test(macos): view model lifecycle/leak tests + timer teardown fixes#493
willwashburn merged 4 commits into
mainfrom
claude/zealous-maxwell-2aienr-lifecycle

Conversation

@willwashburn

@willwashburn willwashburn commented Jul 3, 2026

Copy link
Copy Markdown
Member

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:

  • UsageViewModel scheduled a repeating 60s Timer in start() and never invalidated it — no stop(), no deinit teardown. Its timer closure captures [weak self], so the model itself could deallocate, but the timer kept firing on the main run loop forever.
  • LiveBurnViewModel has stop(), but nothing guarantees it runs: the view relies on SwiftUI .onDisappear, which may not fire when an NSPopover closes. A missed .onDisappear leaves the refresh timer and the background burn ingest --watch alive.

Production fixes (surgical)

  • New TimerBox (@unchecked Sendable): holds the Timer outside the @MainActor view model's isolation so the model's nonisolated deinit can invalidate it without touching actor-isolated state. Its own deinit also 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 a TimerBox; added func stop(); invalidate in deinit; start() is now internal (was private) and idempotent; added var isRefreshTimerActive: Bool as a test hook.
  • LiveBurnViewModel: timer moved into a TimerBox, invalidated in deinit as a backstop for a missed .onDisappear; added var isRefreshTimerActive: Bool.

No public/behavioral change for AppDelegate (holds UsageViewModel for app lifetime) or LiveBurnView (same start()/stop() signatures).

Tests (Tests/BurnTests/ViewModelLifecycleTests.swift)

Using a FakeRunner (reused from BurnLedgerParsingTests) and a counting CountingProvider, all injected so no network/subprocess is touched:

  1. LiveBurnViewModel deallocates after start()/stop().
  2. LiveBurnViewModel deallocates even without stop() (weak-self timer + deinit teardown).
  3. No runner calls after stop() — waits past one .m5 (3s) refresh interval and asserts the call count is frozen and the timer is invalidated.
  4. UsageViewModel(autostart: false) has no side effects: zero fetches, zero ledger calls, no timer, immediate dealloc.
  5. UsageViewModel deallocates after start()/stop().
  6. UsageViewModel timer stops on stop() (via isRefreshTimerActive, 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

Review in cubic

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
@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@willwashburn, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 59 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c70d16cc-8059-474b-964e-9fb10ceb90e0

📥 Commits

Reviewing files that changed from the base of the PR and between f797cdc and f3af3f4.

📒 Files selected for processing (4)
  • apps/macos/Sources/Burn/LiveBurnViewModel.swift
  • apps/macos/Sources/Burn/TimerBox.swift
  • apps/macos/Sources/Burn/UsageViewModel.swift
  • apps/macos/Tests/BurnTests/ViewModelLifecycleTests.swift
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/zealous-maxwell-2aienr-lifecycle

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +17 to +29
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() }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Thread Safety and Data Race Issues in TimerBox

There are two major issues with the current implementation of TimerBox:

  1. Thread Safety of Timer.invalidate(): Timer (NSTimer) is not thread-safe, and its invalidate() method must be called from the same thread on which the timer was installed (the main thread/run loop in this case). Since deinit of the view models is nonisolated, 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's deinit will 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.
  2. Data Race on timer: Since TimerBox is marked @unchecked Sendable, the compiler does not enforce data-race safety. If timer is assigned on the main thread and read/invalidated on a background thread (during deinit), there is a potential data race on the timer property.

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()
    }
}

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 4 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread apps/macos/Sources/Burn/TimerBox.swift Outdated
Comment thread apps/macos/Sources/Burn/TimerBox.swift

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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() }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Base automatically changed from claude/zealous-maxwell-2aienr to main July 3, 2026 15:48
claude added 3 commits July 3, 2026 15:51
…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
@willwashburn willwashburn merged commit 2a137b4 into main Jul 3, 2026
4 of 5 checks passed
@willwashburn willwashburn deleted the claude/zealous-maxwell-2aienr-lifecycle branch July 3, 2026 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants