fix: harden FlowCache lifecycle and drop redundant cache from MetadataDAO#4137
Draft
MohamadJaara wants to merge 4 commits into
Draft
fix: harden FlowCache lifecycle and drop redundant cache from MetadataDAO#4137MohamadJaara wants to merge 4 commits into
MohamadJaara wants to merge 4 commits into
Conversation
Contributor
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #4137 +/- ##
=============================================
+ Coverage 61.55% 61.56% +0.01%
- Complexity 4021 4024 +3
=============================================
Files 2067 2068 +1
Lines 67423 67447 +24
Branches 6650 6655 +5
=============================================
+ Hits 41500 41523 +23
- Misses 23276 23277 +1
Partials 2647 2647
... and 5 files with indirect coverage changes Continue to review full report in Codecov by Sentry.
🚀 New features to boost your workflow:
|
Contributor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Context
Follow-up to #4087. Do not merge until #4087 is merged I'll rebase this branch onto
developonce that lands.#4087 fixed two coroutine leaks (zombie
launchSharingcoroutines inFlowCache, and a permanentSharedFlowperobserveSerializablecall). Code review on that PR surfaced four additional concerns that this PR addresses, plus one simplification enabled by the per-key SQLDelight notifications from #4135.What changes and why
1. Race in
FlowCache.onCompletionFlowCache.ktWhen
remove(key)is called externally, it cancels the oldsharingJob. Cancellation propagates asynchronously to the upstream, firing itsonCompletion. If a newget(key)slips in between, the lateonCompletionof the old flow would have wiped the newly-registered entry.Fix:
onCompletionnow callsremoveIfOwned(key, sharingJob), which only clears state if the registered sharing job is still the one firing an identity check on theJobreference. Late completions from evicted flows become no-ops.2. Orphan
SupervisorJobwhenflowProducerthrowsFlowCache.ktIn the original implementation,
sharingJobs[key] = sharingJobwas set before invokingflowProducer(key). If the producer threw, theSupervisorJobremained as a child ofcacheScope'sJobforever (or untilcacheScopeitself was cancelled), with no corresponding storage entry.Fix:
createFlow()now uses atry/finallywith aregisteredflag. The job is only added tosharingJobsaftershareInsucceeds; if anything throws, the orphanSupervisorJobis cancelled infinally.3. Defensive validation:
cacheScopemust have aJobFlowCache.ktSupervisorJob(cacheScope.coroutineContext[Job])accepts a nullable parent. If a caller ever constructedcacheScopefrom a bareEmptyCoroutineContext, theSupervisorJobwould become orphaned and cancellation fromcacheScopewould not propagate.Fix:
requireNotNullcheck on construction. StandardCoroutineScope(...)factory always provides aJobso existing callers are unaffected; this guards against future misuse.4. Remove
FlowCachefromMetadataDAOMetadataDAOImpl.kt,UserDatabaseBuilder.ktWith the per-key
@CustomKey/@NotifyCustomKeyannotations introduced in #4135, SQLDelight now wakes up only the listener for the specific key that changed. The original reason forFlowCachehere collapsing N subscribers to one upstream query listener — no longer earns its keep. EachvalueByKeyFlow(key)subscriber gets its own cheap per-key SQLDelight flow.Changes:
valueByKeyFlowqueriesselectValueByKeydirectly with.flowOn(readDispatcher).observeSerializablelikewise queries directly, then.map { decode }.distinctUntilChanged().flowOn(readDispatcher).metadataCache: FlowCache<String, String?>field is removed fromMetadataDAOImpland fromUserDatabaseBuilder.This also dissolves the
Lazily→WhileSubscribed(5_000)behavioral change called out in the review of #4087:observeSerializableno longer does its ownshareIn, so neither sharing strategy applies.FlowCacheitself is retainedUserDAOImpl,ConversationDAOImpl, andMemberDAOstill depend on it.Tests
All changes are covered by tests in
FlowCacheTest.kt:givenEntryRecreatedAfterEviction_whenOldUpstreamLatelyCompletes_thenNewEntryIsNotRemovedregression for the eviction race.givenFlowProducerThrows_whenGetIsCalled_thenNoOrphanSharingJobIsLeftBehindfails on the unfixed code with "1 orphan job(s) remain", passes after thetry/finallyfix.givenCacheScopeWithoutJob_whenFlowCacheIsConstructed_thenItRejectsTheScopeasserts therequireNotNullrejection.givenSubscribedFlow_whenCacheScopeJobIsCancelled_thenSharingJobIsAlsoCancelledregression guard on parent-child wiring (would catch a future "fix" that swapsSupervisorJob(parent)forSupervisorJob()).givenMultipleCacheEvictions_thenSharingCoroutinesShouldNotAccumulateenhanced from fix: prevent zombie SharedFlow coroutines in FlowCache and MetadataDAO [WPB-25125] #4087 with per-childisCompleted/isCancelledassertions for better diagnostics if zombies ever regress.Existing
MetadataDAOTest,UserConfigDAOTest, andUserPrefsDAOTestconfirm theobserveSerializable/valueByKeyFlowrefactor preserves caller-visible behavior.