Skip to content

fix(player): stop MediaController listener race from swallowing real playback failures (#642) - #649

Merged
github-actions[bot] merged 1 commit into
devfrom
fix/player-mediacontroller-listener-race
Aug 26, 2026
Merged

github-actions[bot] merged 1 commit into
devfrom
fix/player-mediacontroller-listener-race

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

Summary

Fixes issue #642 ("Playback broken - regression"). Root-caused on-device via adb logcat, not just static reading — see the diagnosis comment on #642 for the full trace.

Two compounding bugs in PlayerViewModel's MediaController connection lifecycle, both firing on essentially every Player-screen open:

  1. playerListener referenced before it's initialized. It was declared textually after init{} in the class body. init{} calls connectController(), which can invoke connectWithRetry()'s callback synchronously (MoreExecutors.directExecutor() + an already-resolved singleton controllerFuture — true on essentially every open after the app's first-ever MediaController connection this session, since LibraryViewModel also resolves it on every Library visit). At that point playerListener hadn't been assigned yet, so controller.addListener(null) threw — logged on-device verbatim as "listener must not be null". The retry recovered ~500ms later, which is presumably why this went unnoticed until it compounded with bug 2.

  2. The forced retry created a real double-trigger race. loadItem()'s completion tail and connectWithRetry()'s success tail could each independently run their own "reattach or play" bootstrap for the same freshly-opened item, bumping playGeneration twice instead of once (confirmed on-device: "Ignoring stale onIsPlayingChanged(false) — gen 2 < current 2"). Every bump makes onIsPlayingChanged unconditionally treat the next false event as a stale ExoPlayer transition blip and swallow it — an assumption that breaks under a genuine double-trigger. A swallowed event can be the real "playback never actually started" signal, leaving PlayerUiState.isPlaying stuck at the optimistic true set by play(), with togglePlayPause() re-deriving the same true on every tap (reads the real ctrl.isPlaying, which is false, flips to !false = true — visually a no-op). That's the reported symptom: shows as playing, no sound, play/pause button doesn't respond.

Fix

  • Move playerListener's declaration above init{}.
  • Consolidate loadItem()'s and connectWithRetry()'s "reattach or play" tails into one attachOrPlay() function, guarded by hasAttachedOrPlayed so only one of the two call sites can actually run it per ViewModel instance.

Why the existing suite (87 tests) never caught this

Both bugs depend on real ListenableFuture/dispatcher timing Robolectric-free mock tests don't reproduce, and specifically for bug 1: mockController (mockk, relaxed) has no real implementation behind addListener() to validate Media3's actual non-null contract, so it silently accepts null.

Tests added

  • playerListener is fully initialized before it's attached to the controller — captures the actual listener argument passed to addListener() and invokes a method on it; a null capture would NPE at the call site regardless of the argument value, which is what makes this a real regression guard for bug 1.
  • attachOrPlay only bootstraps playback once per ViewModel instance — calls attachOrPlay() (made internal, matching LibravaultLogger's existing documented "internal for direct testability" convention, since the real async race isn't reproducible through this module's synchronous UnconfinedTestDispatcher harness) a second time directly and asserts it's a no-op.

Full existing suite re-run clean: feature:player (14/14, incl. the 2 new), feature:library, feature:reader all pass.

Not in scope

The Settings-screen freeze/rendering-artifact also reported alongside this issue is a separate, not-yet-root-caused problem — nothing Settings-related showed up in the logcat capture's window. Tracked as an open follow-up on #642, not fixed here.

🤖 Generated with Claude Code

Co-Authored-By: Claude Sonnet 5 noreply@anthropic.com

…playback failures

Confirmed on-device via adb logcat (issue #642 — "Playback broken - regression")
that PlayerViewModel had two compounding bugs, both firing on essentially every
Player-screen open, not just the vault-audio-unification work landed the same
day:

1. `playerListener` was declared textually *after* `init{}` in the class body.
   `init{}` calls connectController(), which can invoke connectWithRetry()'s
   callback synchronously (MoreExecutors.directExecutor() + an already-resolved
   singleton controllerFuture — true on essentially every open after the app's
   first ever MediaController connection this session). At that point
   `playerListener` hadn't been assigned yet, so `controller.addListener(null)`
   threw — logged verbatim on-device as "listener must not be null". The retry
   silently recovered ~500ms later, which is presumably why this went unnoticed.

2. That forced retry opened a real race: loadItem()'s completion tail and
   connectWithRetry()'s success tail could each independently run their own
   "reattach or play" bootstrap for the same freshly-opened item, bumping
   playGeneration twice instead of once (confirmed on-device: "gen 2 < current 2").
   Every bump makes onIsPlayingChanged unconditionally treat the *next* `false`
   event as a stale ExoPlayer transition blip and swallow it — an assumption
   that breaks when there are two real triggers stacked up. A swallowed event
   can be the genuine "playback never actually started" signal, leaving
   PlayerUiState.isPlaying stuck at the optimistic `true` set by play() with
   togglePlayPause() re-deriving the same `true` on every tap — exactly the
   reported symptom (shows as playing, no sound, button doesn't respond).

Fixes:
- Move playerListener's declaration above init{} so it's always initialized
  before connectController() can possibly reach it.
- Consolidate loadItem()'s and connectWithRetry()'s "reattach or play" tails
  into one attachOrPlay() function, guarded by hasAttachedOrPlayed so only one
  of the two triggers can actually run it per ViewModel instance.

Neither bug was caught by the existing Robolectric suite: mockk's relaxed
MediaController mock has no real implementation behind addListener() to
validate a non-null contract, so it silently accepts null. New regression
tests capture the actual listener argument (would NPE on a null capture) and
call attachOrPlay() a second time directly (attachOrPlay made internal for
this, matching LibravaultLogger's existing "internal for direct testability"
convention) to assert the guard holds — the real async race isn't
reproducible through this module's synchronous UnconfinedTestDispatcher
harness.

Closes #642.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@github-actions github-actions Bot added the risk:low Principal review classified this PR as low risk label Aug 26, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was opened outside the automated pipeline (author isn't libravault-pipeline-bot[bot]) and doesn't link an issue (no Closes #N-style line in its body), so there's no acceptance criteria for qa-agent.yml to verify against — it would otherwise sit with no risk/status label and nothing downstream would pick it up (see issue #223's actual history, and issue #343 for this issue-less case specifically). This deterministic backstop (pr-intake.yml) classified its risk and applied status:needs-review to route it straight to principal review.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@github-actions

Copy link
Copy Markdown
Contributor

Principal review — verdict: auto-merge

What I verified (not just read)

  • Re-ran classify_pr_risk.py origin/dev HEAD myself: 292 changed lines, touches no sensitive path → risk:low. Matches the label on the PR and there's only one commit, so no re-classification was needed, but I checked anyway.
  • Actually ran the test suite, not just trusted "14/14 pass" in the PR body: ./gradlew :feature:player:testDebugUnitTest --tests "...PlayerViewModelTest" → BUILD SUCCESSFUL, 14 tests, 0 failures, 0 errors. Confirmed via the JUnit XML report, not just Gradle's summary line.
  • Mutation-tested both new regression tests to make sure they're real guards, not tautologies:
    • Moved playerListener's declaration back below init{} (reintroducing bug 1) → playerListener is fully initialized before it's attached to the controller fails, as expected.
    • Removed the hasAttachedOrPlayed guard from attachOrPlay (reintroducing bug 2) → attachOrPlay only bootstraps playback once per ViewModel instance fails, as expected.
    • Restored the committed file after each; working tree is clean (git status/git diff --stat empty).
  • Traced the actual race by hand against PlayerModule.provideMediaControllerFuture (MediaController.Builder(...).buildAsync(), default main-looper callback) and connectWithRetry's MoreExecutors.directExecutor() listener: confirmed the double-attachOrPlay scenario is real even after bug 1 is fixed — it requires connectWithRetry's runCatching block to fail for any reason after controller = ctrl is assigned but before the item check, at which point a concurrently-resolving loadItem() coroutine can independently see controller != null and call attachOrPlay first, then the scheduled retry calls it again. The plain-Boolean guard is fine here since both call sites run on the main looper (no actual cross-thread concurrency), so there's no check-then-act atomicity gap despite the var.
  • Confirmed the incidental fix inside the moved listener block: the old code logged myGeneration after overwriting it ("gen $myGeneration < current $playGeneration" always printed the same number twice — visible in the PR's own on-device evidence, "gen 2 < current 2"). The moved version captures the stale value first, so the log is now actually informative. Not mentioned in the PR description, but it's a strict improvement with no behavior change.
  • Confirmed neither changed file (PlayerViewModel.kt, PlayerViewModelTest.kt) matches any sensitive_paths glob in .github/agent-policy.yml, and no new networking dependency/import was introduced.
  • Checked out both the PR and issue Playback broken- regression  #642 for status:blocked — neither is present, and neither carries status:security/status:release-blocker.
  • gh issue list --search for prior tracking of this specific bug turned up only Playback broken- regression  #642 itself — no duplicate to file, and no new CONFIRMED finding here to record permanently.

Correctness read

The attachOrPlay consolidation is a faithful, careful merge of the two previously-duplicated "reattach or play" tails from loadItem() and connectWithRetry() — I compared every field read/write (initialSeekMs, playbackStateHolder.state.value, playGeneration, playedItemUri, speed/position params) line by line against both original call sites and found no behavioral drift; the params each call site now passes (startPositionMs/savedSpeed vs. _uiState.value.savedStartPositionMs/_uiState.value.playbackSpeed) are numerically identical to what the original inline blocks used, since both are populated from the same loadRealItem/loadVaultItem state update.

internal fun attachOrPlay for direct testability matches the LibravaultLogger.write precedent AGENTS.md's test conventions call out (mark pure-enough helpers internal, not private).

No issues found. Nice catch (root-caused via adb logcat, not just static reading) and a well-scoped fix — no unrelated cleanup riding along.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Principal review classified this PR as low risk status:approved-auto-merge Principal review passed, risk:low — will auto-merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants