Skip to content

fix(composition): Stop detached infinite animations driving frames - #25055

Open
MartinZikmund wants to merge 2 commits into
masterfrom
dev/mazi/fix-detached-subtree-animations
Open

MartinZikmund wants to merge 2 commits into
masterfrom
dev/mazi/fix-detached-subtree-animations

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #25054

PR Type:

🐞 Bugfix

What changed? 🚀

A composition animation on a visual below the root of a removed subtree kept running after the subtree left the tree. ContainerVisual stops animations only on the directly removed child, and Compositor.RegisterAnimation captured the window's target at start time. So an infinite animation (e.g. a ProgressRing/Lottie inside a removed panel):

  • kept Compositor.RenderRootVisual requesting a new frame every vsync, forever (if (_runningAnimations.Count > 0) ... RequestNewFrame()): constant rendering at 60/120 Hz, heat, battery;
  • leaked the whole detached subtree: _runningAnimations → animation → AnimationFrame handler → visual → parent chain.

The fix (compositor side, Skia):

  • _runningAnimations remembers each animation's host. After any change to the composition tree (ContainerVisual children change or a Visual.CompositionTarget assignment bumps a version), the next frame re-validates where running animations tick. Steady-state frames skip this.
  • An unbounded animation (IterationBehavior.Forever) whose host lost its target is unregistered and parked in a list that holds the animation and host weakly: no ticking, no frame requests, and the detached subtree stays collectable. When the host is attached again it resumes; keyframe animations are time-based, so it continues as if it had kept running, which matches WinUI, where composition animations survive tree changes.
  • Finite animations keep their current behavior (they end on their own and may be awaited through a CompositionScopedBatch).
  • Animations started while their host isn't attached used to be dropped silently (they never ticked); they're now parked the same way and start once attached.
  • A visual moved to another window is re-targeted.

How WinUI deals with this, for context: the composition engine is a separate compositor that only presents connected trees, and WinUI controls explicitly tear down their animations on Unloaded (e.g. AnimatedVisualPlayer::OnUnloaded → UnloadContent(), with Complete() called on unload "so that the AnimationPlay cannot outlive the AnimatedVisualPlayer"). Uno's in-process compositor drives frames from its animation registry, so it needs to know which animations are still connected.

Raised in review of #25046, which is now stacked on this PR (#25187 covers the retention in the meantime).

Tests: Given_KeyFrameAnimation_Detached (runtime, Skia), an infinite opacity animation on a child whose parent is removed:

  • When_Ancestor_Removed_Then_Animation_Stops_Requesting_Frames: fails on master (Compositor.IsAnimating stays true), passes with the fix.
  • When_Ancestor_Removed_Then_Detached_Visual_Is_Collectable: fails on master (visual kept alive), passes with the fix.
  • When_Ancestor_Readded_Then_Animation_Resumes: passes on both (guards the resume path).

Regression: Windows_UI_Composition, Given_AnimatedVisualPlayer, Given_ProgressRing, AnimatedVisuals and Given_Storyboard runtime tests on Skia Desktop: 165/165 pass (127/127 re-run after a final hardening for an animation instance shared across targets, TODO #24102).

PR Checklist ✅

🤖 Generated with Claude Code

https://claude.ai/code/session_01NL1zD4nmcDjrcPhceNXFNm

MartinZikmund and others added 2 commits October 6, 2026 13:21
An animation on a visual below the root of a removed subtree stayed
registered with the window's target, so Compositor kept requesting a
frame every vsync and rooted the detached subtree. Unbounded animations
whose host loses its target are now parked weakly and resume on
re-attach; animations started while detached tick once attached.
Targets are re-validated only on frames after a tree change.

Fixes #25054

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NL1zD4nmcDjrcPhceNXFNm
Copilot AI balanced review requested due to automatic review settings October 6, 2026 11:21
@MartinZikmund MartinZikmund self-assigned this Oct 6, 2026
@github-actions github-actions Bot added the area/skia ✏️ Categorizes an issue or PR as relevant to Skia label Oct 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 22s —— View job


Review of #25055

Verdict: ship, with minor suggestions.

The approach is sound. It is a compositor-side fix with a version-gated revalidation (steady-state frames are unaffected), weak parking for detached infinite animations, and tests that fail on master and pass with the fix. I only read the diff and did not build or run any tests.

Issues: 0 blocking, 1 minor (posted inline: no de-dup or pruning for the parked list).

Cross-cutting notes

  • Finite animations whose host loses its target keep ticking against the old target (by design, per the PR). They still request frames until they finish, which is bounded. This is worth a one-line comment next to the retarget condition.
  • Parked animations are held only weakly. This is correct only if the host or the user keeps a strong reference to the animation (e.g. the host's animator collection). A short test showing a parked, never-attached animation still starts after the host attaches, with the caller dropping its own reference, would pin that down.
  • Visual.CompositionTarget's setter now calls into the compositor. Compositor.OnVisualTreeChanged is internal and cheap, so this looks fine, but confirm Compositor is never null for visuals during construction.
  • Style and conventions look fine: tabs, braces, and conventional commit titles.

}

private void AddDetachedAnimation(CompositionAnimation animation, CompositionObject host)
=> (_detachedAnimations ??= new()).Add((new(animation), new(host)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor (robustness): the parked list is only pruned inside RefreshAnimationTargets, which runs only when _visualTreeVersion changes and a frame renders. If animations are repeatedly started on never-attached hosts and the tree is quiet, dead weak entries accumulate. Also nothing prevents the same animation being parked twice (e.g. Start called repeatedly while detached), which would later hit the ContainsKey guard and leave a duplicate entry. Consider a de-dup check here (RemoveDetachedAnimation first) and an opportunistic prune.

public partial class Compositor
{
private Dictionary<CompositionAnimation, ICompositionTarget> _runningAnimations = new();
private Dictionary<CompositionAnimation, RunningAnimation> _runningAnimations = new();
Comment on lines +123 to +129
else if (!RemoveDetachedAnimation(animation))
{
if (this.Log().IsDebugEnabled())
{
this.Log().Debug($"Cannot unregister unknown animation");
}
}
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 237644 found UI Test snapshots differences: skia-linux-screenshots: 130, skia-windows-screenshots: 177

Details
  • skia-linux-screenshots: 130 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ColorPickerSample.png-dark
    • ClipboardTests.png-dark
    • ColorPickerSample.png
    • CompositionPath.png-dark
    • CompositionPath.png
    • AutomationProperties_AutomationId.png-dark
    • AutomationProperties_AutomationId.png
    • CalendarView_Theming.png-dark
    • Buttons.png-dark
    • Buttons.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • DynamicFont.png-dark
    • DynamicFont.png
    • Examples.png
    • DoubleImageBrushInList.png-dark
  • skia-windows-screenshots: 177 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • CalendarView_Theming.png-dark
    • ClipboardTests.png
    • CalendarView_Theming.png
    • DisplayInformation.png-dark
    • DoubleImageBrushInList.png-dark
    • DoubleImageBrushInList.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Grid_DynamicRowColumn.png-dark
    • Grid_DynamicRowColumn.png
    • Grid_InsideStackPanel_InsideButton.png-dark
    • Grid_InsideStackPanel_InsideButton.png
    • Grid_in_Canvas.png-dark
    • Grid_in_Canvas.png
    • Grid_in_GridClipping.png-dark

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at head 4a18af5: read the diff and the surrounding code in Compositor.skia.cs, Visual.cs, ContainerVisual.skia.cs, KeyFrameEvaluator.cs, and the new tests. The AnimatedVisualPlayer citation is accurate: AnimatedVisualPlayer::OnUnloaded calls UnloadContent() (controls/dev/AnimatedVisualPlayer/AnimatedVisualPlayer.cpp, lines 439-451). Infinite keyframe animations wrap their progress (KeyFrameEvaluator, WrapProgress), so a parked infinite animation resumes at the phase it would have reached. That part of the design holds. The claim that WinUI composition animations survive tree changes cannot be checked here: the composition engine is not in microsoft-ui-xaml, which has only forward declarations.

Validation: code review only. I did not build, and I did not run the runtime tests.

Findings, most severe first:

  1. A finite animation started while detached finishes early (medium, behaviour bug). The PR says animations started while detached "start once attached". That is not true for finite animations. ScalarKeyFrameAnimation.Start creates the evaluator, whose clock starts at that moment, and AdvanceToCurrentTimestamp adds the whole wall-clock gap on the first evaluation. A finite animation started on a detached visual and attached after its duration jumps straight to its final value. Attached sooner, it starts mid-way. Infinite animations are not affected, because their progress wraps. Suggest restarting the evaluator clock when a parked finite animation is first registered, and only then. Add a runtime test: start a finite opacity animation on a detached child, wait longer than its duration, attach, and assert that it starts at the beginning and plays its full duration.

  2. The parked list grows without bound between tree changes (medium). _detachedAnimations is pruned only in RefreshAnimationTargets, which runs only after a tree-version bump. Each entry holds two WeakReference objects, and each UnregisterAnimation for a parked animation does a linear scan. A page that starts many animations on visuals that are never attached, and makes no tree change, accumulates entries. Suggest pruning dead entries when the list has doubled since the last prune, and avoiding the linear scan on removal.

  3. Test gaps (low). Nothing covers (a) the finite-started-detached case above, or (b) a parked animation whose caller drops its own reference, which is the case the weak-hold design depends on. In Given_KeyFrameAnimation_Detached.cs, the #else branches are unreachable under [PlatformCondition(... Skia)], and the file-level handling is redundant.

  4. Per-frame cost (low, question). RefreshAnimationTargets walks every running and parked animation on each frame in which the tree version changed. That is fine at steady state. During virtualised list churn it is O(animations) per frame. Please say whether this was measured.

@mergify

mergify Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

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

Labels

area/performance area/skia ✏️ Categorizes an issue or PR as relevant to Skia

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Composition animations below a removed subtree keep rendering at display rate and leak the subtree

5 participants