Skip to content

Drop stale cache write-backs from a fetch that began before an identity change#3563

Closed
vegaro wants to merge 7 commits into
mainfrom
cesar/implement-spec-and-plan
Closed

Drop stale cache write-backs from a fetch that began before an identity change#3563
vegaro wants to merge 7 commits into
mainfrom
cesar/implement-spec-and-plan

Conversation

@vegaro

@vegaro vegaro commented Jun 8, 2026

Copy link
Copy Markdown
Member

Summary

WorkflowsCache and OfferingsCache are user-agnostic — an identity transition wipes them with clearCache(). But an in-flight backend fetch can write back after the clear, repopulating the just-cleared cache with the previous user's data, which is then served until the next fetch self-heals it:

T0  fetch(userA) → backend request in flight
T1  identity change → clearCache()        // wipes in-memory + disk
T2  userA's onSuccess lands → cache write  // repopulates with userA data

@Synchronized couldn't close this: it serializes individual mutations but can't order a clear() against a write-back that crosses the async backend boundary.

This adds a clear-generation token to both caches. Each owns a monotonic cacheGeneration: Int, bumped inside its @Synchronized clearCache(). A fetch captures currentGeneration() at its start and threads that value through the whole async sequence; every write commits only if the captured generation still matches — checked under the same lock the increment uses, so clear-then-write is atomic. A write from any prior epoch is dropped, and the cleared cache stays empty until the next fetch repopulates it for the current user.

Both caches are covered together: a workflows-only guard would leave offerings (the thing workflows are keyed to) still racy. Chosen over an appUserID compare because a monotonic counter is correct under fast A→B→A login churn, where the id matches again but the epoch differs.

What changed

Area Change
WorkflowsCache cacheGeneration + currentGeneration(); bump in clearCache(); expectedGeneration guard on cacheWorkflow, cacheWorkflowsList, cacheWorkflowsListInMemory, cacheWorkflowDetailEnvelope
WorkflowManager capture in getWorkflowsList (threaded through the success write, prefetch loop, and error-restore paths) and getWorkflow (captured at entry; prefetch passes the list's epoch)
OfferingsCache cacheGeneration + currentGeneration(); bump in clearCache(); expectedGeneration guard on cacheOfferings
OfferingsManager capture in fetchAndCacheOfferings, threaded through createAndCacheOfferings (network-success and disk-fallback paths)

Out of scope by design: clearInMemoryOfferingsCache() / forceCacheStale() / forceWorkflowsListCacheStale() do not bump the generation (locale-override and forced-staleness have separate semantics). No appUserID is introduced into either cache. All new symbols are internal — no public API change.

Test plan

  • WorkflowsCacheTest / OfferingsCacheTest: currentGeneration() increments on clearCache(); each gated write is a no-op on a stale generation and commits on the current one; the non-identity-transition clear methods leave the generation unchanged.
  • WorkflowManagerTest / OfferingsManagerTest: the real race against a real cache — capture the success callback, clearCache(), then fire the callback; assert the cleared cache stays empty and disk is not rewritten.
  • Full :purchases unit suite (3223 tests), detektAll, api-check — all green, no public API diff.

🤖 Generated with Claude Code

vegaro and others added 6 commits June 8, 2026 18:46
Adds a monotonic cacheGeneration counter to WorkflowsCache, bumped inside
the @synchronized clearCache(). Write methods (cacheWorkflow,
cacheWorkflowsList, cacheWorkflowsListInMemory, cacheWorkflowDetailEnvelope)
now take an expectedGeneration parameter and silently drop the write when the
generation has advanced, preventing an in-flight fetch from repopulating the
cache after an identity transition clears it.

WorkflowManager call sites updated with workflowsCache.currentGeneration() as
a temporary compile-fix; Task 2 will replace these with a generation captured
at fetch start for true race-condition safety.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The default `expectedGeneration = workflowsCache.currentGeneration()` was
evaluated by the synthesized getWorkflow$default on the caller side, so an
`every {}` block recording getWorkflow on a mocked WorkflowManager (whose
workflowsCache field is null) threw an NPE. Default to null and resolve the
generation inside the method body instead, preserving capture-at-entry for
on-demand fetches.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…traint

Adds a stale-generation test for cacheWorkflowsListInMemory (the load-bearing
disk-restore write path) and tests pinning the spec non-goal that
forceWorkflowsListCacheStale, clearInMemoryOfferingsCache, and forceCacheStale
do not bump the generation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@vegaro vegaro added the pr:fix A bug fix label Jun 8, 2026
…and-plan

# Conflicts:
#	purchases/src/main/kotlin/com/revenuecat/purchases/common/workflows/WorkflowManager.kt
#	purchases/src/test/java/com/revenuecat/purchases/common/workflows/WorkflowsCacheTest.kt
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.23%. Comparing base (1b6280d) to head (c03bf75).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3563      +/-   ##
==========================================
+ Coverage   80.19%   80.23%   +0.04%     
==========================================
  Files         371      371              
  Lines       15239    15271      +32     
  Branches     2112     2118       +6     
==========================================
+ Hits        12221    12253      +32     
  Misses       2168     2168              
  Partials      850      850              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@vegaro vegaro added pr:other and removed pr:fix A bug fix labels Jun 9, 2026
@vegaro vegaro closed this Jul 2, 2026
@vegaro
vegaro deleted the cesar/implement-spec-and-plan branch July 2, 2026 06:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant