polaris: `EntityCache` leaks memory & prone to inconsistencies & race conditions

Describe the bug

org.apache.polaris.core.persistence.cache.EntityCache uses two containers:

  private final Cache<Long, EntityCacheEntry> byId;
  private final AbstractMap<EntityCacheByNameKey, EntityCacheEntry> byName;

The first one is a Caffeine cache, the second one is a Java Map.

byName can become inconsistent due to race conditions, multiple threads acting on the same entity IDs and/or entity names. The implementation assumes, that there are no multi-threaded accesses against the same entity IDs and/or entity names, which is not guaranteed.

To Reproduce

No response

Actual Behavior

No response

Expected Behavior

No response

Additional context

No response

System information

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 18 (14 by maintainers)

Most upvoted comments

@ben-manes I noticed that you are working on the IndexedCache class. Could you review the one I embedded in #1339 please?

Here is some feedback on using IndexedCache as suggested by @ben-manes. I have hacked an implementation of EntityCache that uses it.

Let me try to unblock this discussion.

To determine whether these issues are real, I worked on JCStress tests. JCStress is a testing framework developed by Oracle that helps verify correct behavior of concurrent Java code.

I have implemented multiple concurrency tests against the EntityCache and found strange behaviour. Would it be possible to get a review? The full analysis is available here. Note that the test cases are far from covering all code paths in EntityCache. So there may be other undiscovered issues. The code is available here.

Observed behaviour:

  • The cache can return stale data even after it has returned fresh data
  • The cache can return null even in the case where an entity exist in the database
  • The cache can issue more database calls than necessary

There is also a strange result where all actors observed the entity in version 3 but none observed entity in version 2, which should have been the case. However I have no explanation for that one.

@eric-maynard @flyrain could you review the tests and confirm they are correct please?

Elaborating more on this, because it seems that the concurrency implications in EntityCache.java of the implementation are maybe not obvious to everybody:

  1. byName is a j,u.c.ConcurrentHashMap. It is not guaranteed to be in sync with the byId Caffeine cache, because updates to byName happen outside of the (“atomic”) operations of Caffeine. This means, that ‘byName’ can contain different values than in ‘byId’.
  2. Since byName updates are not in-sync with byId, it can contain stale entries and retain those forever. This means, that the map can grow infinitely.
  3. In turn byName queries can yield wrong results, which may cause issues at the calling code

NB: Ben proposed a workaround above ~ 2 months ago