Fix: ANR caused by model.add(), model.initializeFromJson(), or modelstore.load() #2281
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
One Line Summary
Fix the ANR that can caused by model.add(), model.initializeFromJson(), or modelstore.load()
Details
Motivation
Fix the ANR that may potentially interrupt the normal usage of apps.
Scope
OperationRepo.enqueue() now performs internal enqueue in a specific coroutine and the operation may not be added instantly even the method returns immediately. The purpose of it is to prevent a potential deadlock situation when enqueuing is running into loading. This deadlock currently only happens to OperationModelStore because it is loaded in a background thread to optimize the starting process. When operations like addTag or optIn is called immediately after initWithContext, there is a chance to lock some specific resource that is needed for the loading to complete.
Testing
Unit testing
Was not able to make a targeted unit test because the deadlock situation involves instances not only in modeling but also in the app level.
Manual testing
The first commit simulates a deadlock situation by calling addTag shortly after initWithContext and purposely delay model.initializeFromJson for addTag in the main thread to be blocked. Now if we run the test app, it will freeze on the startup screen.
After the fix, we can see that app does not freeze anymore.
Affected code checklist
Checklist
Overview
Testing
Final pass
This change is