Skip to content

Add error handling for Element lifecycle user callbacks - #173148

Merged
auto-submit[bot] merged 16 commits into
flutter:masterfrom
LongCatIsLooong:deactivate-throw
Aug 14, 2025
Merged

auto-submit[bot] merged 16 commits into
flutter:masterfrom
LongCatIsLooong:deactivate-throw

Conversation

@LongCatIsLooong

@LongCatIsLooong LongCatIsLooong commented Aug 2, 2025 •

Copy link
Copy Markdown
Contributor

This is for #172289, but since this fix is speculative so I'll wait for the confirmation from the original reporters before closing the issue.

As a bonus this fixes #65655

The framework Element rebuild logic relies heavily on Element._lifecycleState being correct. When a user-supplied lifecycle callback (e.g., State.deactivate) fails the framework currently only ensures that every Element in the tree has the right lifecycle state, so an out-of-tree Element that is supposed to be disposed may still have an active state and continue being rebuilt by the BuildScope (because it's in the dirty list). See the comments in #172289

Also related:
#100777
Internal:
b/425298525 b/431537277
b/300829376 b/415724119 b/283614822

TODO (in a different PR)

The original issue could also be caused by incorrect Element.updateChild calls. If an Element subclass calls Element.updateChild to add child but forgets to update its child list accordingly (such that visitChildren misses that child), you'll get a child Element that thinks it's a child of the parent but the parent doesn't recognize the child so won't take that child into account during reparenting or unmounting. This is a programmer error that we should try to catch in the framework.

Pre-launch Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

@github-actions github-actions Bot added the framework flutter/packages/flutter repository. See also f: labels. label Aug 2, 2025
assert(child.attached == attached);
assert(child.parentData != null);
if (!(_isRelayoutBoundary ?? true)) {
if (!(child._isRelayoutBoundary ?? true)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Unrelated change. This is a typo from #169958

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces robust error handling for Element lifecycle callbacks, specifically for deactivate, to prevent framework state corruption when user-provided code throws an exception. The use of try...finally blocks to ensure critical framework logic executes is a solid approach. The refactoring of Element.deactivate into a public hook and a private implementation is also a clean and effective pattern. The new tests are valuable and cover the intended failure scenarios well. I have one minor suggestion in a test file to remove a redundant line.

),
);
// _Make sure the old child subtree are deactivated and disposed.
try {

@LongCatIsLooong LongCatIsLooong Aug 4, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This isn't enough. If you inflate a widget during the process and a descendant Element fails to activate, the current pattern in framework.dart is to replace the entire subtree rooted at the performRebuild call with an ErrorWidget. So some inflated elements are still active (since the inflation process was partially successful) even if they never get incorporated into the tree.

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.

Is this only a best effort thing? should we have a catch or finally to clean up the reset of tree?

@LongCatIsLooong LongCatIsLooong Aug 4, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah I guess if activation fails we should also build the ErrorWidget to replace the subtree that actually failed to re-activate instead of that subtree that we're trying to inflate. Updating.
Edit: I ended up just deactivating the whole tree that will be replaced by this ErrorWidget.

try {
element.deactivate();
} catch (_) {
element._ensureDeactivated();

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.

This may potentially be called twice if the crash is in _ensureDeactivated

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.

don't think this is an issue though, but may make stack trace a bit messy

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried removing the "ensure" part out of deactivate but one of our tests is calling deactivate directly so I couldnt. See #173148 (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.

yeah I think this is fine

),
);
// _Make sure the old child subtree are deactivated and disposed.
try {

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.

Is this only a best effort thing? should we have a catch or finally to clean up the reset of tree?

@LongCatIsLooong
LongCatIsLooong marked this pull request as draft August 4, 2025 23:53
@LongCatIsLooong
LongCatIsLooong marked this pull request as ready for review August 5, 2025 18:14
@github-actions github-actions Bot added p: material_ui material_ui package in flutter/packages p: cupertino_ui cupertino_ui package in flutter/packages labels Aug 5, 2025
return newChild;
}
} catch (_) {
// Attempt to do some clean-up if activation or mount fails to leave tree in a reasonable state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The previous implementation only tries to do that if _activateWithparent fails.

/// Implementations of this method should end with a call to the inherited
/// method, as in `super.deactivate()`.
@mustCallSuper
@visibleForOverriding

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I added the annotation because I was trying to move _ensureDeactivated out, but since nothing is failing I'll keep the annotation (same as activate).

@github-actions github-actions Bot added the f: routes Navigator, Router, and related APIs. label Aug 6, 2025
/// build phase.
inactive,

/// The [Element] encountered a unrecoverable error while being rebuilt when it

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.

Suggested change
/// The [Element] encountered a unrecoverable error while being rebuilt when it
/// The [Element] encountered an unrecoverable error while being rebuilt when it

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.

These are great docs btw, thanks for adding them :)

/// This indicates the [Element]'s subtree is in an inconsistent state and must
/// not be re-incorporated into the tree again.
///
/// When a unrecoverable error is encountered, the framework calls

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.

Suggested change
/// When a unrecoverable error is encountered, the framework calls
/// When an unrecoverable error is encountered, the framework calls

}
}

static void _deactivateFailedSubtreeRecursively(Element element) {

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.

should this be call during production as well? I think so, but just want to double check

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes

/// This is one of the two final stages of the element lifecycle and is not
/// reversible. Reaching this state typically means that a widget implementation
/// is throwing unhandled exceptions that need to be properly handled.
failed,

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.

failedToActivate

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.

What exactly happen ad the end of this? do they just hang there without getting disposed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes because we don't know what to do with them, they will be stuck in a limbo. Some may have failed before initState was called so these Elements are not disposable, and others may have not gone through proper deactivation. The decision to not dispose them is pretty arbitrary, but since these elements are in inconsistent states I don't know if one option will be better than other, as they will be equally bad.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think I prefer the current name since it could also be fail to deactivate?

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.

is there a code path to put element in this state when they fail to deactivate?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, in _InactiveElements._deactivateRecursively, Element._deactivateFailedSubtreeRecursively(element); is called if the element fails to deactivate (and the deactivation exception will be rethrown).

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.

gotcha, thanks

try {
_deactivateRecursively(element);
} finally {
_elements.add(element);

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.

if the element failed to deactivate do we still want to add it to the elements?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point I restructured the deactivate flow, now I don't think an element will be added to the list if it fails to deactivate.

return updatedChild!;
} else {
newChild.mount(this, newSlot);
assert(newChild._lifecycleState == _ElementLifecycle.active);

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.

This can't be _ElementLifecycle.failed and go to catch case right? maybe we should assert that in catch case. I don't think that is possible, but probably should be safe

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

With asserts enabled, the new code would still rethrow the assert like it should if the resulting lifecycle state is not active? (maybe I'm not understanding the question correctly)

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.

if the lifecycle is anything other than active, this will go to the catch and go through the _deactivateFailedChildSilently. I was just thinking that in the catch body before it goes o _deactivateFailedChildSilently, can we add an assert(newChild._lifecycleState != _ElementLifecycle.failed) to make sure an element doesn't somhow get _deactivateFailedChildSilently twice

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh you mean adding assert(newChild._lifecycleState != _ElementLifecycle.failed) to the catch clause below? But if that assert fires if will prevent the "real" exception from being rethrow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's probably fine for something to get _deactivateFailedChildSilently'd twice (but it seems unlikely)?

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.

yeah this is fine.

assert(newChild._lifecycleState == _ElementLifecycle.active);
return newChild;
}
} catch (_) {

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.

do we use (_) in our repo? i thought this is against style guide

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think using wildcard in pattern matching is fine? Here I'd consider the _ to be a wildcard pattern instead of anonymous argument since the catch clause is pretty pattern-match-y.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hmm I looked at dart's syntax again:

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

It doesn't look like that _ is being used as a wildcard identifier, as the pattern matching is expressed in the on clause. So the (_) here probably is an anonymous identifier / argument.

But I think I just copied that from the existing implementation:

} catch (_) {
// Attempt to do some clean-up if activation fails to leave tree in a reasonable state.
try {
deactivateChild(newChild);
} catch (_) {
// Clean-up failed. Only surface original exception.
}
rethrow;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried replacing _ with an identifier there's an "emply_catch_block" lint that doesn't like that change. Also the style guide says:

Provide full type information and names even for parameters that are otherwise unused. This makes it easier for people reading the code to tell what is actually going on (e.g. what is being ignored).

But catch (e) isn't any more informative than catch (_) I think.

element._ensureDeactivated();
// Do not rethrow:
// The subtree has already thrown a different error and the framework is
// cleaning up on a best-effort basis.

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.

widget subtree may end up with different states with assertions enabled / disabled

won't they all become failed at the end?

_deactivateRecursively(element);
// This element is only added to _elements if the whole subtree is
// successfully deactivated.
_elements.add(element);

@LongCatIsLooong LongCatIsLooong Aug 8, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If a descendant fails to deactivate, the root won't be marked as .failed here (it's still .inactive). The caller (of Element.deactivateChild) may catch the exception and marked the entire subtree as failed like inflateWidget does.

@LongCatIsLooong LongCatIsLooong Aug 8, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If the caller doesn't do that it should still be fine. The element will get stuck in the inactive state forever.

ghost Aug 13, 2025

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.

looking at the updateChild, it only mark the newChild to failed, instead of existing child (which got deactivated). or did I miss something?

ghost Aug 13, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sorry can you point me to the line that this is happening? IIRC updateChild doesn't have any try ... catch blocks in it so it simply rethrows everything. If a descendant element of the existing child fails to deactivate the updateChild method is going to return immediately, so it won't even get a chance to call inflateWidget to create the new child as far as I can tell.

ghost Aug 13, 2025

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.

nvm, this is answered in other thread

ghost 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.

Replied to some of the thread. I think the code looks mostly fine, just some questions

ghost 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.

LGTM

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

Labels

f: routes Navigator, Router, and related APIs. framework flutter/packages/flutter repository. See also f: labels. p: cupertino_ui cupertino_ui package in flutter/packages p: material_ui material_ui package in flutter/packages

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Throwing in didChangeDependencies after establishing dependencies causes failures during test teardown

3 participants