Skip to content

fix(desktop): invalidate leaked run-loop timers and pump the live-scroll test drain to its deadline (#13460) - #13468

Merged
Git-on-my-level merged 6 commits into
mainfrom
fix/desktop-scroll-test-flake-13460
Sep 11, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
fix/desktop-scroll-test-flake-13460

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13460.

  • UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing passes alone and fails when batched with CI's worker-0-2-h1 suites on an unmodified origin/main tree. The detector reads its terminal position via DispatchQueue.main.async; the test drained with a single RunLoop.main.run(mode:before:), which returns as soon as any leftover .common-mode timer from an earlier suite fires.
  • The per-suite isolation re-run this triggers (38 × ~55 s) is what pushed the "Test desktop Swift app" step past its 1800 s budget on feat(desktop): opt-in on-device embeddings with FTS hybrid retrieval; backend keyword fallback for screen search #13456.
  • This PR pumps the drain to its deadline (the pattern ChatTranscriptGestureHarnessTests and AuthRestoreWatchdogTests already use) and fixes the leak at its source: the chat follow glide, the live-edge pinner, and the WAL recording timers now invalidate on deinit, with guard tests that release an armed owner and assert the timer is invalid.

Product invariants affected

  • INV-CHAT-1 — ChatScrollBehavior.swift only gains deinit timer invalidation on the follow glide and live-edge pinner. No transcript, session, or agent state is stored or mirrored; the kernel-owned transcript is untouched.
  • INV-CHAT-2 — ChatScrollLiveEdgeTests.swift is this invariant's guard test; only the harness drain changes. Scroll ownership, placement, and virtualization behaviour and the guarded assertions are unchanged.

Failure-Class

Failure-Class: new

FC-run-loop-timer-outlives-owner, defined in this PR: a repeating timer on RunLoop.main is retained by the run loop, not its owner, so an owner released without invalidating keeps firing. Guard tests in ChatScrollLiveEdgeTests and WALServiceUploadTests are the prevention artifact.

What changed

  • Desktop/Tests/ChatScrollLiveEdgeTests.swift — drainMainQueue() pumps RunLoop.main until its 50 ms deadline (same commit as carried on feat(desktop): opt-in on-device embeddings with FTS hybrid retrieval; backend keyword fallback for screen search #13456); new DEBUG-guarded tests prove a released ChatFollowGlide / ChatLiveEdgePinner leaves no live timer.
  • Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift — ChatFollowGlide and ChatLiveEdgePinner invalidate their 60 Hz .common timer in deinit (main-thread assumeIsolated, same shape as ChatOmiMarkFrameView). Behaviour while alive is unchanged.
  • Desktop/Sources/WAL/WALService.swift — chunk/flush timers invalidate in deinit; WALServiceUploadTests gains testRecordingTimersInvalidateOnDeinit.
  • Desktop/Tests/UnhandledKeystrokeSilenceTests.swift — drops the panel's hosting view before closing so the hosted SwiftUI tree leaves no run-loop sources behind.
  • .github/failure-classes/FC-run-loop-timer-outlives-owner.json — the class definition.

Root cause found in CI's worker-0-2-h1 batch: earlier suites left .common/default-mode repeating timers on RunLoop.main (armed glide/pinner released without cancel(), WALService instances released while recording, a real floating-bar panel closed with its hosting view attached). The detector's DispatchQueue.main.async read then lost the race with a single run(mode:before:) drain.

Verification

From desktop/macos on Xcode 26.6 / Swift 6.3.3, CI's exact batch (38 suites SuggestionCommitmentGuardTests…WorkContextCheapPathTests, one SwiftPM process):

  • Unmodified 022432d0f8: 280 tests, 1 failure (UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing, settledAtBottom 0 ≠ 1) — reproduces the issue.
  • This branch, 3 consecutive runs: 282 tests, 0 failures each.
  • Touched suites alone: UserScrollDetectorTests (6), ChatScrollLiveEdgeTests (14), UnhandledKeystrokeSilenceTests (4), WALServiceUploadTests (25), WALServiceOrphanSdCardTests, WifiSyncServiceTests — all green.
  • python3 desktop/macos/scripts/check_desktop_test_quality.py — OK.

Known limit: the deinit invalidation only runs when the owner is released on the main thread (same tradeoff as ChatOmiMarkFrameView). Other repeating-timer owners (DesktopUsageDailyReporter, MeetingDetector, RecordingTimer, ResourceMonitor, …) have the same shape and are not touched here.

🤖 Generated with Claude Code

Review in cubic

Git-on-my-level and others added 6 commits September 10, 2026 23:44
…oll drain

UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing fails
order-dependently when it shares a SwiftPM process with certain other suites
(reproduced on an unmodified origin/main desktop tree with CI's batch
worker-0-2-h1 composition). The detector queues its terminal bounds read with
DispatchQueue.main.async; the test drained with one RunLoop.main.run(mode:before:),
which returns as soon as any source fires, so a repeating .common-mode timer
left behind by an earlier suite ended the drain before the read ran. Pump the
run loop until the deadline instead, as ChatTranscriptGestureHarnessTests and
AuthRestoreWatchdogTests already do. The existing wall-clock-wait annotation is
retained; no new wait is added.

Verification: the 38-suite batch that failed on CI (exact composition) now
passes 3/3 locally (242 tests, 0 failures); suite alone and the whole file pass;
python3 desktop/macos/scripts/check_desktop_test_quality.py OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ChatFollowGlide and ChatLiveEdgePinner add repeating .common-mode timers
with RunLoop.main.add. The run loop retains those timers independently of
the object, so SwiftUI or a test releasing an armed clock left a 60 Hz
source that ended later RunLoop.main.run(mode:before:) drains before
queued DispatchQueue.main.async work (the UserScrollDetector flake in
#13460). Invalidate on deinit, matching ChatOmiMarkFrameView.

Failure-Class: none

Verification: xcrun swift test --package-path Desktop --filter
UserScrollDetectorTests|ChatScrollLiveEdgeTests|ChatPressPromotionPolicyTests
passed (UserScrollDetectorTests 6 tests, ChatScrollLiveEdgeTests 14 tests).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
WALService.startRecording schedules repeating chunk and flush timers via
Timer.scheduledTimer. Tests in the same process (WALServiceUploadTests
calls startRecording without stopRecording in tearDown) released the
service while those timers stayed on the main run loop. Invalidate them
on deinit so a leftover default-mode source cannot starve later
RunLoop.main.run(mode:before:) drains.

Failure-Class: none

Verification: xcrun swift test --package-path Desktop --filter
WALServiceUploadTests|WALServiceOrphanSdCardTests|WifiSyncServiceTests
passed (WALServiceUploadTests 25 tests including
testRecordingTimersInvalidateOnDeinit).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
UnhandledKeystrokeSilenceTests constructs a real FloatingControlBarWindow
(NSHostingView + SwiftUI) and previously only called close(). Clear
contentView on teardown so the hosted view tree cannot keep run-loop
sources alive after the suite finishes in a batched SwiftPM process.

Verification: xcrun swift test --package-path Desktop --filter
UnhandledKeystrokeSilenceTests passed (4 tests).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
A repeating run-loop timer is retained by RunLoop.main, not by its owner; an
owner released without invalidating leaves a source that breaks later
single-shot run-loop drains in the same process (#13460). The guard tests in
ChatScrollLiveEdgeTests and WALServiceUploadTests are the prevention artifact.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

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

Confidence score: 3/5

  • In desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift, releasing an owner off the main thread can bypass cancel(), leaving its RunLoop.main timer alive and consuming background CPU after the view or session is gone; ensure the retained timer is invalidated regardless of the release thread.
  • In desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json, the entry focuses on internal timer ownership rather than the user-visible cleanup outcome; describe that chat scrolling and recording cleanup no longer consume background CPU after closure.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift:230">
P2: When one of these owners is released off the main thread, the `Thread.isMainThread` guard skips `cancel()`, leaving its `RunLoop.main` timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.</violation>
</file>

<file name="desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json">

<violation number="1" location="desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json:2">
P3: The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.

(Based on your team's feedback about user-facing desktop changelog outcomes.)</violation>
</file>

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

Re-trigger cubic

// invalidate here, SwiftUI dropping a transcript (or a test releasing the
// glide) leaves a 60 Hz `.common` source on `RunLoop.main` that ends later
// `run(mode:before:)` drains before queued main-async work can run.
if Thread.isMainThread {

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: When one of these owners is released off the main thread, the Thread.isMainThread guard skips cancel(), leaving its RunLoop.main timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift, line 230:

<comment>When one of these owners is released off the main thread, the `Thread.isMainThread` guard skips `cancel()`, leaving its `RunLoop.main` timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.</comment>

<file context>
@@ -218,6 +222,16 @@ final class ChatFollowGlide {
+    // invalidate here, SwiftUI dropping a transcript (or a test releasing the
+    // glide) leaves a 60 Hz `.common` source on `RunLoop.main` that ends later
+    // `run(mode:before:)` drains before queued main-async work can run.
+    if Thread.isMainThread {
+      MainActor.assumeIsolated { cancel() }
+    }
</file context>

@@ -0,0 +1,3 @@
{
"change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake."

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.

(Based on your team's feedback about user-facing desktop changelog outcomes.)

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json, line 2:

<comment>The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.

(Based on your team's feedback about user-facing desktop changelog outcomes.) </comment>

<file context>
@@ -0,0 +1,3 @@
+{
+  "change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake."
+}
</file context>
Suggested change
"change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake."
"change": "Fixed chat scrolling and recording cleanup so the app no longer uses background CPU after those views or sessions close."

@Git-on-my-level
Git-on-my-level merged commit 31b4ee5 into main Sep 11, 2026
31 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/desktop-scroll-test-flake-13460 branch September 11, 2026 06:03
Git-on-my-level added a commit that referenced this pull request Sep 26, 2026
)

* test(desktop): inherit defaults and timer isolation

Reuse unique defaults-domain ownership and XCTest teardown in the auth
fixtures repaired by #13260. Both chat repeating timer owners from #13468
now use a shared invalidating token; drive elapsed time and callbacks through
a manual scheduler to exercise completion, retargeting, cancel and release.
Ratchet existing direct shared-defaults mutations at 292, with narrow local
integration reasons, in the existing quality guard and manifest lanes.

Verification: make setup; 15 Python checker tests; both named local manifest
checks; strict Swift 6 isolated type checks. A temporary SwiftPM fixture using
the exact changed timer classes/test methods and defaults support passed six
XCTest cases. Removing token deinit invalidation made two release tests fail.
Integrated desktop compilation and historical suite sequencing are delegated
to the parent task after combining worktrees; no live app was launched.

Failure-Class: FC-run-loop-timer-outlives-owner

* docs(desktop): keep test isolation guidance within component budget

* feat(desktop): require explicit automation effects and read-only dispatch

* test(desktop): cover lazy action effects and async defaults ownership

* test(desktop): expect mandatory effect descriptions in discovery

* test(desktop): make timer lifetime observable through the flow

* docs(desktop): explain cold-path automation effects

* test: raise stale shared-defaults baseline to main's current debt (this branch adds 0)

* fix(desktop): add typed effects to main-side action registrations added after this branch forked

* test: probe descriptor safety label tracks main's added remote_write delivery persistence
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.

Order-dependent desktop test flake: UserScrollDetectorTests fails when batched with other suites (costs the Swift suite step its time budget)

1 participant