Repository navigation
Add error handling for Element lifecycle user callbacks - #173148
Conversation
| assert(child.attached == attached); | ||
| assert(child.parentData != null); | ||
| if (!(_isRelayoutBoundary ?? true)) { | ||
| if (!(child._isRelayoutBoundary ?? true)) { |
There was a problem hiding this comment.
Unrelated change. This is a typo from #169958
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Is this only a best effort thing? should we have a catch or finally to clean up the reset of tree?
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
This may potentially be called twice if the crash is in _ensureDeactivated
There was a problem hiding this comment.
don't think this is an issue though, but may make stack trace a bit messy
There was a problem hiding this comment.
I tried removing the "ensure" part out of deactivate but one of our tests is calling deactivate directly so I couldnt. See #173148 (comment)
| ), | ||
| ); | ||
| // _Make sure the old child subtree are deactivated and disposed. | ||
| try { |
There was a problem hiding this comment.
Is this only a best effort thing? should we have a catch or finally to clean up the reset of tree?
| return newChild; | ||
| } | ||
| } catch (_) { | ||
| // Attempt to do some clean-up if activation or mount fails to leave tree in a reasonable state. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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).
| /// build phase. | ||
| inactive, | ||
|
|
||
| /// The [Element] encountered a unrecoverable error while being rebuilt when it |
There was a problem hiding this comment.
| /// The [Element] encountered a unrecoverable error while being rebuilt when it | |
| /// The [Element] encountered an unrecoverable error while being rebuilt when it |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
| /// When a unrecoverable error is encountered, the framework calls | |
| /// When an unrecoverable error is encountered, the framework calls |
| } | ||
| } | ||
|
|
||
| static void _deactivateFailedSubtreeRecursively(Element element) { |
There was a problem hiding this comment.
should this be call during production as well? I think so, but just want to double check
| /// 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, |
There was a problem hiding this comment.
What exactly happen ad the end of this? do they just hang there without getting disposed?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I think I prefer the current name since it could also be fail to deactivate?
There was a problem hiding this comment.
is there a code path to put element in this state when they fail to deactivate?
There was a problem hiding this comment.
Yeah, in _InactiveElements._deactivateRecursively, Element._deactivateFailedSubtreeRecursively(element); is called if the element fails to deactivate (and the deactivation exception will be rethrown).
| try { | ||
| _deactivateRecursively(element); | ||
| } finally { | ||
| _elements.add(element); |
There was a problem hiding this comment.
if the element failed to deactivate do we still want to add it to the elements?
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
It's probably fine for something to get _deactivateFailedChildSilently'd twice (but it seems unlikely)?
| assert(newChild._lifecycleState == _ElementLifecycle.active); | ||
| return newChild; | ||
| } | ||
| } catch (_) { |
There was a problem hiding this comment.
do we use (_) in our repo? i thought this is against style guide
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
flutter/packages/flutter/lib/src/widgets/framework.dart
Lines 4529 to 4536 in 1c0ee96
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
If the caller doesn't do that it should still be fine. The element will get stuck in the inactive state forever.
There was a problem hiding this comment.
looking at the updateChild, it only mark the newChild to failed, instead of existing child (which got deactivated). or did I miss something?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
nvm, this is answered in other thread
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._lifecycleStatebeing correct. When a user-supplied lifecycle callback (e.g.,State.deactivate) fails the framework currently only ensures that everyElementin the tree has the right lifecycle state, so an out-of-treeElementthat is supposed to be disposed may still have anactivestate and continue being rebuilt by the BuildScope (because it's in the dirty list). See the comments in #172289Also 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.updateChildcalls. If anElementsubclass callsElement.updateChildto add child but forgets to update its child list accordingly (such thatvisitChildrenmisses 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-assistbot 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.