Skip to content

Fix "Cannot round NaN value" crash when predictive back gesture finishes with non-monotonic frame time - #1022

Closed
arkivanov-bot wants to merge 1 commit into
masterfrom
fix/1012-seekable-nan
Closed

arkivanov-bot wants to merge 1 commit into
masterfrom
fix/1012-seekable-nan

Conversation

@arkivanov-bot

@arkivanov-bot arkivanov-bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #1012 (I didn't use "Fixes" because this hasn't been verified on an affected Huawei/Honor device).

Root cause

The crash comes from SeekableTransitionState in animation-core. The relevant code is the same in 1.9.4, which this repo uses via JB Compose 1.9.3, and in 1.11.4, which the reporter uses (Transition.kt lines below are from 1.11.4):

  1. animateTo() creates a SeekingAnimationState with animationSpecDuration = totalDurationNanos * (1 - fraction). When the transition has zero total duration, this is 0.
  2. animateOneFrameLambda (L303) computes deltaPlayTimeNanos = (frameTimeNanos - lastFrameTimeNanos) / durationScale. durationScale is always > 0 here.
  3. recalculateAnimationValue (L398): if (playTimeNanos >= durationNanos) value = 1f else value = lerp(start, 1f, playTimeNanos.toFloat() / durationNanos). With durationNanos == 0 and a negative play time, that's lerp(0, 1, -Infinity), which is NaN.
  4. fraction = NaN, then seekToFraction() (L733) calls (NaN * totalDurationNanos).roundToLong() and throws IllegalArgumentException: Cannot round NaN value.

So the crash needs two things at once:

  • zero total transition duration. Decompose hits this when a custom PredictiveBackAnimatable is used: the item's animator is SimpleStackAnimator { anim.exitModifier/enterModifier }, which doesn't add animations to the transition. Unless the content has its own transition animations, finish() calls animateTo() on zero-duration SeekableTransitionStates.
  • a frame time smaller than the previously captured one (a non-monotonic frame clock). This is the only way to get a negative play time on this path. I haven't confirmed why this happens only on Huawei/Honor devices. The most likely cause is a vendor-modified Choreographer, since AOSP's Choreographer explicitly skips frames whose time goes backwards.

Fix

AnimationHandler.finish() now runs the two SeekableTransitionState.animateTo() calls with a MonotonicFrameClock wrapper that never reports a frame time lower than one it already reported. With a monotonic clock, deltaPlayTimeNanos >= 0, so a zero-duration animation completes with value = 1f and never produces NaN. When frame times are already monotonic, the wrapper returns them unchanged, so behaviour doesn't change.

I considered snapping zero-duration transitions (snapTo() instead of animateTo()), as suggested in the issue, and decided against it. StackAnimationScope is an AnimatedVisibilityScope, so content can have transition-driven animations (transition.animateFloat, animateEnterExit, shared elements, etc.). Their duration isn't known until the new target state has been composed (and, for deferred animations, laid out). Checking the duration up front could wrongly skip real animations, and it would also need access to the Transition instance from AnimationHandler.

Verification

  • New PredictiveBackNonMonotonicFrameTimeTest (JVM): it drives the full DefaultStackAnimation predictive back flow (custom PredictiveBackAnimatable, start → progress → back) through ImageComposeScene, so the test controls frame times, and makes the frame time go backwards right after back().
    • Without the fix, the zero-duration case fails every time with IllegalArgumentException: Cannot round NaN value. and the stack is never popped. The stack trace matches the production one (Recomposer → BroadcastFrameClock.sendFrame → animateOneFrameLambda → seekToFraction → roundToLong).
    • With the fix, both cases pass (content without transition animations = zero duration, and content with a transition.animateFloat() = non-zero duration).
    • Control: if frame times don't go backwards, or the transition has a non-zero duration, the crash doesn't happen even without the fix.
  • :extensions-compose-experimental:jvmTest: all 276 tests pass.
  • Also passing: compileReleaseKotlinAndroid, compileKotlinJs, compileKotlinWasmJs (-Dsplit_targets), apiCheck. I didn't build the iOS/macOS targets (no macOS host).

Caveats

  • Not verified on an affected device. The device-side trigger (non-monotonic frame times on Huawei/Honor) is inferred from the code: it's the only input that can produce this NaN on this path.
  • The upstream SeekableTransitionState behaviour is still there (tracked in https://issuetracker.google.com/issues/540477169). This PR only stops Decompose from triggering it.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed predictive-back stack popping when animation frame timestamps move backwards, with or without content transition animations.

…ishes with non-monotonic frame time

SeekableTransitionState.animateTo produces NaN fraction if the frame time goes backwards while animating a transition with zero total duration (e.g. when a custom PredictiveBackAnimatable is used). Run the finishing transition animations with a frame clock that never goes back in time. See #1012.
@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: e8867004-130b-4938-8be5-1a572c444069

📥 Commits

Reviewing files that changed from the base of the PR and between 66450dd and 9b91a9b.

📒 Files selected for processing (2)
  • extensions-compose-experimental/src/commonMain/kotlin/com/arkivanov/decompose/extensions/compose/experimental/stack/animation/DefaultStackAnimation.kt
  • extensions-compose-experimental/src/jvmTest/kotlin/com/arkivanov/decompose/extensions/compose/experimental/stack/animation/PredictiveBackNonMonotonicFrameTimeTest.kt

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The completion transition animations now use a frame clock that clamps decreasing timestamps. New predictive-back tests exercise this behavior with content transition animations enabled and disabled.

Changes

Predictive-back frame-time handling

Layer / File(s) Summary
Clamp completion animation frame times
extensions-compose-experimental/src/commonMain/kotlin/com/arkivanov/decompose/extensions/compose/experimental/stack/animation/DefaultStackAnimation.kt
Both transition-state animateTo calls in AnimationHandler.finish use a frame-time wrapper. The wrapper clamps timestamps when a frame clock is present and uses a child coroutine scope when one is absent. The animatable’s finish call is unchanged.
Test predictive-back completion with decreasing frame times
extensions-compose-experimental/src/jvmTest/kotlin/com/arkivanov/decompose/extensions/compose/experimental/stack/animation/PredictiveBackNonMonotonicFrameTimeTest.kt
Tests cover predictive-back completion with content transition animations enabled and disabled. They render decreasing timestamps followed by advancing timestamps, then assert there are no errors and the stack contains only "1".

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 9b91a

The predictive-back crash path is covered by the fix and regression test. No merge-blocking risk remains after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: fixing the predictive back crash caused by non-monotonic frame time when the gesture finishes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@arkivanov

Copy link
Copy Markdown
Owner

@arkivanov-bot it's mentioned in the issue that it's a Compose bug, reported here: https://issuetracker.google.com/issues/540477169. It was marked as a duplicate of https://issuetracker.google.com/issues/555294641, which was marked as fixed. The actual fix seem to be this: https://android-review.googlesource.com/c/platform/frameworks/support/+/4276642. Please check if the fix has already been released. If there was a release, try updating and see if it was actually fixed.

@arkivanov-bot

Copy link
Copy Markdown
Collaborator Author

@arkivanov Checked release status of the upstream Compose fix.

Upstream change

Gerrit 4276642 (“Prevent NaN in SeekableTransitionState animation frame calculations”) is merged into androidx-main (submitted 2026-09-09). It fixes b/555294641 (dupe of b/540477169) in androidx.compose.animation:animation-core (Transition.kt / SeekableTransitionState).

Released?

No — not in any published Maven release yet.

Evidence:

  • Tip-of-tree libraryversions.toml already has COMPOSE = "1.13.0-beta01", and the fix commit is on androidx-main under that in-development version.
  • Official release notes still list latest Compose Animation as 1.13.0-alpha03 / stable 1.12.1 (2026-09-09). The alpha03 notes do not include this relnote (“Fixed a crash in SeekableTransitionState where rounding NaN values…”).
  • Verified the distinctive fix markers (durationScale.isNaN(), if (newValue.isNaN()) 1f else …, durationNanos <= 0L) are present on androidx/androidx androidx-main, and absent from JetBrains Compose Multiplatform v1.9.3, v1.12.1, v1.13.0-alpha01, and current jb-main.

So the fix is tip-of-tree only; next published AndroidX line that should carry it is expected to be androidx.compose.animation:animation-*:1.13.0-beta01 (or later). JetBrains CMP has not synced it yet either.

What Decompose uses

deps.versions.toml: jetbrainsCompose = "1.9.3" → Jetpack Compose 1.9.4 on Android (per CMP compatibility table). Far behind the unreleased tip-of-tree fix.

Update attempt

Skipped a dependency bump: there is no released AndroidX / CMP version that contains this fix to update to. Bumping to latest published CMP (e.g. 1.12.1 / 1.13.0-alpha01) would still ship the buggy SeekableTransitionState path.

Recommendation

Keep the PR #1022 workaround (monotonic frame-clock wrapper in AnimationHandler.finish()). It remains the right library-side mitigation until a Compose Animation release that includes 4276642 is available and Decompose can adopt it (likely via a future CMP bump that maps to AndroidX ≥ 1.13.0-beta01). After that lands, we can re-check whether the wrapper can be dropped.

@arkivanov

Copy link
Copy Markdown
Owner

No, since the main issue in Compose is fixed, I will rather close the issue without adding any workaround to Decompose codebase.

@arkivanov arkivanov closed this Sep 26, 2026
isaac-udy pushed a commit to isaac-udy/Enro that referenced this pull request Oct 1, 2026
Some devices (observed on Huawei and Honor) occasionally deliver a
Choreographer frame time earlier than the previous frame's.
SeekableTransitionState does not tolerate this: while animating a
transition whose total duration is zero (a scene change with no
enter/exit animations), the negative frame delta produces a NaN
fraction and the next seek crashes with
"IllegalArgumentException: Cannot round NaN value" from
SeekableTransitionState.seekToFraction. In NavigationDisplay this
fires when a predictive-back gesture settles.

NavigationDisplay now drives its SeekableTransitionState through a
NonDecreasingFrameTime guard: a MonotonicFrameClock wrapper that clamps
frame times to be non-decreasing. One instance is shared across the
seek, animate and settle phases, so a regression across a phase
boundary (a predictive-back seek handing over to the settle animation)
is caught too.

Same class of fix as arkivanov/Decompose#1022 for the identical crash;
upstream report: https://issuetracker.google.com/issues/540477169

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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