You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@polaris.apache.org by "pingtimeout (via GitHub)" <gi...@apache.org> on 2025/04/08 17:00:49 UTC
[PR] Entity cache with indexed cache [polaris]
pingtimeout opened a new pull request, #1339:
URL: https://github.com/apache/polaris/pull/1339
<!--
Possible security vulnerabilities: STOP here and contact security@apache.org instead!
Please update the title of the PR with a meaningful message - do not leave it "empty" or "generated"
Please update this summary field:
The summary should cover these topics, if applicable:
* the motivation for the change
* a description of the status quo, for example the current behavior
* the desired behavior
* etc
PR checklist:
- Do a self-review of your code before opening a pull request
- Make sure that there's good test coverage for the changes included in this PR
- Run tests locally before pushing a PR (./gradlew check)
- Code should have comments where applicable. Particularly hard-to-understand
areas deserve good in-line documentation.
- Include changes and enhancements to the documentation (in site/content/in-dev/unreleased)
- For Work In Progress Pull Requests, please use the Draft PR feature.
Make sure to add the information BELOW this comment.
Everything in this comment will NOT be added to the PR description.
-->
This pull request introduces the integration of JCStress tests into the Polaris project to enhance concurrency testing. It also includes a rewrite of the `EntityCache` class to fix concurrency issues that are surfaced by the JCStress tests. Fixes #761.
The most important changes include adding new dependencies, configuring the JCStress plugin, and creating several JCStress test cases for concurrency validation of the `EntityCache` class.
### Dependency and Configuration Additions:
* [`bom/build.gradle.kts`](diffhunk://#diff-f11ddd31805406938cbae2a53975b7f8af4fdcabea69384d213067d5e0a76eb9R53): Added `polaris-jcstress-tests` to the project dependencies.
* [`gradle/libs.versions.toml`](diffhunk://#diff-697f70cdd88ba88fe77eebda60c7e143f6ad1286bca75017421e93ad84fb87dfR100): Added the JCStress plugin with version `0.8.15`, released under the ASLv2.
* Indirect test dependency: https://github.com/openjdk/jcstress/, released under the GPLv2
### EntityCache concurrency tests:
* [`jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java`](diffhunk://#diff-e58c84b84664d563ef6f2d899c80904455d950bc3a6d47aa972da1b6400794acR1-R175): Added tests to ensure the coherence of the `EntityCache` when accessed concurrently by multiple threads.
* [`jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheGetAndRefreshIfNeededTest.java`](diffhunk://#diff-de9cb8cb5f7ff57981c4178e4681823f2587bec735b887ffc3452e7ec17378e2R1-R73): Added tests to verify the thread-safety of the `getAndRefreshIfNeeded` method.
* [`jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheGetByIdTest.java`](diffhunk://#diff-ada8ec23f866d87dab5887f82666d82d4f300660e436a1a4a53f6996d70d9e8dR1-R151): Added tests to ensure the `getOrLoadById` method behaves correctly under concurrent access.
### Documentation:
* [`jcstress-tests/README.md`](diffhunk://#diff-1d9c09b8f7df121e9bde734a1e69cd2b8d03d8ed5bf994dde95c68c3993245e8R1-R155): Added comprehensive documentation explaining the purpose of JCStress tests, how to run them, and how to interpret the results.
### EntityCache reimplementation:
Heavily inspired by @ben-manes implementation of `IndexedCache`.
The code includes a new `IndexedCache` class. That class is a Caffeine cache that stores entries twice, once indexing the entries using the `long` id field, and once using a compound field using the name. Any update to the cache is guarded by a lock on the key so that it remains consistent under high concurrency.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2034626667
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
Review Comment:
Well, it's deserved :)
(And we have to)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "dennishuo (via GitHub)" <gi...@apache.org>.
dennishuo commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2072293174
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -267,104 +189,70 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
-
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
-
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ lock.writeLock().lock();
+ try {
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
+
+ // Either confirmed cache miss, or the entity is stale. Invalidate it just in case.
+ cache.invalidate(entityId);
+
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.maybeLoadEntityById(
+ callContext, entityToValidate.getCatalogId(), entityId, entityToValidate.getType());
+ if (cacheLookupResult == null) {
+ // Entity has been purged, and we have already cleaned the cache and the name-to-id mapping,
+ // nothing else to do.
+ return null;
}
- // assert that entity, grant records and version are all set
- callContext.getDiagServices().checkNotNull(entity, "unexpected_null_entity");
- callContext.getDiagServices().checkNotNull(grantRecords, "unexpected_null_grant_records");
+ ResolvedPolarisEntity entity = cacheLookupResult.getCacheEntry();
Review Comment:
It looks like we got rid of the codepath that optimizes "only loading what changed" via `refreshResolvedEntity` here. I agree that codepath is kind of gnarly and could be argued to be over-optimization, but it's indeed a behavioral change that we might want to be careful about.
In particular, the case that it optimizes for is:
1. An entity's main contents are frequently updated
2. That entity's grants only rarely change
3. That entity has lots of grants associated with it
4. Grants might be more expensive to load because they are a range scan rather than a point-lookup
With `refreshResolvedEntity`, the cache will eliminate all load on the "grants lookup" index in the database, even if the entity itself is fast changing. For a single entity this isn't a huge deal probably, but if there's 100,000 fast-changing entities in a system, the blowup of grant re-lookup could be noticeable.
If we do make this entire cache implementation just one option out of several, I guess it's fine to wait until the performance issue actually comes up to re-add the complexity (or allow the service owner to select the other cache implementation).
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -20,194 +20,99 @@
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.collect.HashBiMap;
+import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.GuardedBy;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.config.BehaviorChangeConfiguration;
import org.apache.polaris.core.config.FeatureConfiguration;
import org.apache.polaris.core.config.PolarisConfiguration;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
-/** An in-memory entity cache with a limit of 100k entities and a 1h TTL. */
+/** The entity cache, can be private or shared */
public class InMemoryEntityCache implements EntityCache {
-
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ @GuardedBy("lock")
+ private final Cache<Long, ResolvedPolarisEntity> cache;
+
+ // Map of entity names to entity ids
+ @GuardedBy("lock")
+ private final HashBiMap<Long, EntityCacheByNameKey> nameToIdMap;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final ReentrantReadWriteLock lock;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public InMemoryEntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
+ // remember the meta store manager
+ this.polarisMetaStoreManager = polarisMetaStoreManager;
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
+ // enabled by default
+ this.cacheMode = EntityCacheMode.ENABLE;
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
+ this.nameToIdMap = HashBiMap.create();
+ this.lock = new ReentrantReadWriteLock();
long weigherTarget =
PolarisConfiguration.loadConfig(FeatureConfiguration.ENTITY_CACHE_WEIGHER_TARGET);
- Caffeine<Long, ResolvedPolarisEntity> byIdBuilder =
+ Caffeine<Long, ResolvedPolarisEntity> cacheBuilder =
Caffeine.newBuilder()
.maximumWeight(weigherTarget)
.weigher(EntityWeigher.asWeigher())
.expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener); // Set the removal listener
+ // Add a removal listener so that the name-to-id mapping is also purged after every
+ // cache
+ // replacement, invalidation or expiration . Configure a direct executor so that the
+ // removal
+ // listener is invoked by the same thread that is updating the cache.
Review Comment:
Is there a window of time between when the native removal happens (without holding any writeLock) and when the listener runs where the two mappings get out of sync?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -267,104 +189,70 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
-
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
-
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ lock.writeLock().lock();
+ try {
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
+
+ // Either confirmed cache miss, or the entity is stale. Invalidate it just in case.
+ cache.invalidate(entityId);
+
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.maybeLoadEntityById(
+ callContext, entityToValidate.getCatalogId(), entityId, entityToValidate.getType());
+ if (cacheLookupResult == null) {
+ // Entity has been purged, and we have already cleaned the cache and the name-to-id mapping,
Review Comment:
Does this `already cleaned the cache and the name-to-id mapping` refer to line 223 where we called `cache.invalidate`? Where does the by-name map get cleaned here? Should line 223 call `this.remove` instead?
Also, perhaps reiterate in this comment the fact that this was done within the write-locked block which is why we don't have to think more deeply about concurrent invalidate vs cacheNewEntry attempts, e.g. `...and we have already cleaned the cache and the name-to-id mapping while holding the writeLock,...`
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -378,50 +266,83 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
+ ResolvedPolarisEntity cachedEntity = getEntityById(entityId);
+ if (cachedEntity != null) {
+ // Cache hit, nothing more to do
+ return new EntityCacheLookupResult(cachedEntity, true);
+ }
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
+ // Cache miss, we may have to load the entity from the metastore
+ return maybeLoadEntityById(callContext, entityCatalogId, entityId, entityType);
+ }
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
+ private EntityCacheLookupResult maybeLoadEntityById(
+ PolarisCallContext callContext,
+ long entityCatalogId,
+ long entityId,
+ PolarisEntityType entityType) {
+ lock.writeLock().lock();
+ try {
+ ResolvedPolarisEntity cachedEntity = getEntityById(entityId);
+ if (cachedEntity != null) {
+ // Cache was populated concurrently, nothing more to do, exit the critical section as
+ // quickly as possible
+ return new EntityCacheLookupResult(cachedEntity, true);
+ }
- // load it
ResolvedEntityResult result =
polarisMetaStoreManager.loadResolvedEntityById(
callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
if (!result.isSuccess()) {
+ // Entity not found, and it was not in the cache, nothing else to do
Review Comment:
Although this is already a latent issue, could you also update the comment here with a TODO to also check that the `result.getReturnStatus()` is indeed `ENTITY_NOT_FOUND`? We might also want a github issue to audit all the callsites of `isSuccess()` to find situations where a caller assumes the only possible non-success is a particular type of failure (e.g. assuming not-found or assuming conflicting-update, etc., when it could've been something else)
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -267,104 +189,70 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
-
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
-
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ lock.writeLock().lock();
+ try {
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
+
+ // Either confirmed cache miss, or the entity is stale. Invalidate it just in case.
+ cache.invalidate(entityId);
+
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.maybeLoadEntityById(
Review Comment:
Though I see the appeal of eliminating "redundant database calls", the fundamental tradeoff is indeed whether to allow redundant database calls but lock a smaller section vs locking the bigger section for more contention.
In a way this impl is using the writeLock for two distinct purposes:
1. Protect the in-memory atomicity of byName and byId, e.g. a "data structure" lock
2. Prevent concurrent writers from doing duplicate fetches
The semantic of (2) only really requires "locking" the exact entityId (and perhaps entityName) being contended, essentially letting later read-through attempts wait on a Future for something already fetching inflight. The problem is that we probably don't want to deal with the complexity of fine-grained per-entity-id locks/semaphores, so now the writeLock causes cross-catalog/cross-entity contention.
The behavior here basically changes two ways now:
1. If the distributed database has some poisoned ranges/catalogIds that are super-slow or hang forever, the writeLock now allows the poisoned ranges to pollute the ability to serve requests (since for now cache-updates aren't "best-effort" but actually block serving the request entirely) on other catalogs/entities
2. Even if the database backend isn't systematically poisoned, but if someone uses a stateless proxy layer in front of the distributed database like some managed Polaris services do today, any hiccups in the stateless layer effectively allow cross-service pollution of latency spikes in situations where "duplicate" attempts might've allowed 9 out of 10 requests to succeed from a healthy proxy layer even if the first-to-arrive attempt happens to get stuck on an unlucky host. This case is problematic even if we do introduce fine-grained locking.
If we split out this entire `InMemoryEntityCache` implementation as a separate option, then users who have simple database backend layers that don't exhibit such heterogeneity can choose this one, while those with more distributed layers might choose the original impl.
We can also add TODOs to maybe provide a configurable option to this cache for whether to optimize for "no duplicate database fetches" or to optimize for liveness in the face of heterogeneous backend unhealthiness. Then the latter would do the call to the MetaStoreManager outside of any locks and reconcile after re-acquiring the lock.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-3197452530
I think this change needs attention, as it addresses data race conditions in Apache Polaris.
This cache is sadly not just used as a "dumb but easy to reason about" read-through-cache, but rather modified by call sites based on certain conditions. That leaves quite some room for race conditions.
The purpose of a cache is IMO to remove load from something, the backend database in this case. But to do its jobs "right", call sites have to query the database and compare the cached state with that of the database.
The problems are orthogonal, but both the race conditions and database load are real for every user of Apache Polaris, who all access the backend database directly. If someone else chooses to use a different persistence architecture, it's up to them to reason about a cache that matches their specific needs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035402942
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
+ // We are the first to act upon this entity id, invalidate it
+ this.cache.invalidate(new IdKey(entityId));
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.getOrLoadEntityById(
Review Comment:
> To be clear, it is possible that there are still unidentified race conditions in the code. The fact that the cache has two different ways of accessing the same entity is a very tricky design.
+100
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033879574
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
Review Comment:
I don't care about attribution; you can treat the examples as public domain imho
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073684376
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -20,194 +20,99 @@
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.collect.HashBiMap;
+import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.GuardedBy;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.config.BehaviorChangeConfiguration;
import org.apache.polaris.core.config.FeatureConfiguration;
import org.apache.polaris.core.config.PolarisConfiguration;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
-/** An in-memory entity cache with a limit of 100k entities and a 1h TTL. */
+/** The entity cache, can be private or shared */
public class InMemoryEntityCache implements EntityCache {
-
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ @GuardedBy("lock")
+ private final Cache<Long, ResolvedPolarisEntity> cache;
+
+ // Map of entity names to entity ids
+ @GuardedBy("lock")
+ private final HashBiMap<Long, EntityCacheByNameKey> nameToIdMap;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final ReentrantReadWriteLock lock;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public InMemoryEntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
+ // remember the meta store manager
+ this.polarisMetaStoreManager = polarisMetaStoreManager;
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
+ // enabled by default
+ this.cacheMode = EntityCacheMode.ENABLE;
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
+ this.nameToIdMap = HashBiMap.create();
+ this.lock = new ReentrantReadWriteLock();
long weigherTarget =
PolarisConfiguration.loadConfig(FeatureConfiguration.ENTITY_CACHE_WEIGHER_TARGET);
- Caffeine<Long, ResolvedPolarisEntity> byIdBuilder =
+ Caffeine<Long, ResolvedPolarisEntity> cacheBuilder =
Caffeine.newBuilder()
.maximumWeight(weigherTarget)
.weigher(EntityWeigher.asWeigher())
.expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener); // Set the removal listener
+ // Add a removal listener so that the name-to-id mapping is also purged after every
+ // cache
+ // replacement, invalidation or expiration . Configure a direct executor so that the
+ // removal
+ // listener is invoked by the same thread that is updating the cache.
Review Comment:
You may need to call cleanUp() to ensure under your locks to ensure eviction happens under it. The write buffer, thread context switches, races could lead to an eviction happening afterwards since eviction uses a single lock. Caffeine uses ring buffers in a pub/sub fashion so that the shared policy state doesn’t require synchronization of all methods. The cleanup still might not be strong enough unless you coordinate above it correctly. I guess it’s to say the cache needs to promise the behavior, you can’t assume how it might work
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035431024
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.apache.polaris.core.persistence.cache.FakeMetaStoreManager.CATALOG_ID;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.LL_Result;
+
+public class EntityCacheCoherenceTest {
+ /** The cache key associated with the catalog that is returned by the fake meta store manager. */
+ private static final EntityCacheByNameKey KEY = new EntityCacheByNameKey(CATALOG, "test");
+
+ @JCStressTest
+ @Description(
+ "Tests that the two caches inside EntityCache are coherent with one another. In this test, two"
+ + " actors are calling getOrLoadById and getOrLoadByName. The entities received by the"
+ + " actors are not checked as part of this test. Instead, an arbiter runs after the"
+ + " actors have performed their calls and checks the version of the entity that are in"
+ + " each of the two caches using the getter methods getEntityById and getEntityByName. "
+ + " Expected behaviour is that the two caches return the same entity version. Any"
+ + " discrepancy indicates that the caches are out of sync.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "The caches are out of sync"),
+ @Outcome(expect = UNKNOWN, desc = "Not sure what happened"),
+ })
+ @State()
+ public static class UsingGetters {
+ private final PolarisCallContext context;
+ private final EntityCache entityCache;
+
+ public UsingGetters() {
+ context = new PolarisCallContext(new FakeBasePersistence(), new FakePolarisDiagnostics());
+ entityCache = new EntityCache(new FakeMetaStoreManager());
+ }
+
+ @Actor
+ public void actor1() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+
+ @Actor
+ public void actor2() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
Review Comment:
No, it's fine. Thanks for the explanation!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073407737
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -20,194 +20,99 @@
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.collect.HashBiMap;
+import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.GuardedBy;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.config.BehaviorChangeConfiguration;
import org.apache.polaris.core.config.FeatureConfiguration;
import org.apache.polaris.core.config.PolarisConfiguration;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
-/** An in-memory entity cache with a limit of 100k entities and a 1h TTL. */
+/** The entity cache, can be private or shared */
public class InMemoryEntityCache implements EntityCache {
-
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ @GuardedBy("lock")
+ private final Cache<Long, ResolvedPolarisEntity> cache;
+
+ // Map of entity names to entity ids
+ @GuardedBy("lock")
+ private final HashBiMap<Long, EntityCacheByNameKey> nameToIdMap;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final ReentrantReadWriteLock lock;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public InMemoryEntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
+ // remember the meta store manager
+ this.polarisMetaStoreManager = polarisMetaStoreManager;
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
+ // enabled by default
+ this.cacheMode = EntityCacheMode.ENABLE;
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
+ this.nameToIdMap = HashBiMap.create();
+ this.lock = new ReentrantReadWriteLock();
long weigherTarget =
PolarisConfiguration.loadConfig(FeatureConfiguration.ENTITY_CACHE_WEIGHER_TARGET);
- Caffeine<Long, ResolvedPolarisEntity> byIdBuilder =
+ Caffeine<Long, ResolvedPolarisEntity> cacheBuilder =
Caffeine.newBuilder()
.maximumWeight(weigherTarget)
.weigher(EntityWeigher.asWeigher())
.expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener); // Set the removal listener
+ // Add a removal listener so that the name-to-id mapping is also purged after every
+ // cache
+ // replacement, invalidation or expiration . Configure a direct executor so that the
+ // removal
+ // listener is invoked by the same thread that is updating the cache.
Review Comment:
Not really, but only thanks to the direct executor usage:
1. The Caffeine cache entry removal happens while holding the write lock. That is, during the `cache.invalidate(...)` method call.
2. The Caffeine cache does invoke the removal listener asynchronously. I.e. during the call to replace/remove an entity, it schedules a call to the removal listener on a separate executor. This will indeed cause the listener to be executed on a different thread, which could lead to the race condition you describe.
3. However, by instructing Caffeine to use a direct executor, the listener is called synchronously by the calling thread before the replace/remove entity call even returns. I.e. when Caffeine calls `executor.submit(...)`, the direct executor transforms that into a synchronous method call.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033751485
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
+ // the cache, once indexed by its identifier and once indexed by its name.
+ this.cache =
+ new IndexedCache.Builder<CacheKey, ResolvedPolarisEntity>()
+ .primaryKey(e -> new IdKey(e.getEntity().getId()))
+ .addSecondaryKey(e -> new NameKey(new EntityCacheByNameKey(e.getEntity())))
+ .expireAfterWrite(Duration.ofMinutes(5))
+ .maximumSize(10_000)
Review Comment:
Since the expiry limits and general cache behaviour is going to be different from old code... Should be make these parameters configurable immediately? User may need to adjust their cache config, I guess :sweat_smile:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035479230
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
+ // We are the first to act upon this entity id, invalidate it
+ this.cache.invalidate(new IdKey(entityId));
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.getOrLoadEntityById(
Review Comment:
However, I think this is more of an optimization issue, not correctness... Invalidating twice or even invalidating after a reload should not cause incorrect data to be returned... I think :thinking:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035498187
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
Review Comment:
This branch does not seem possible... The comparator always returns `1`, does it not?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2034632017
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
Review Comment:
IMO we can always move it elsewhere - it's currently only used here (and it's package-private).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035428776
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/FakeMetaStoreManager.java:
##########
@@ -0,0 +1,309 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static java.util.Collections.emptyList;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.*;
+import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
+import org.apache.polaris.core.persistence.dao.entity.*;
+import org.apache.polaris.core.storage.PolarisStorageActions;
+
+/**
+ * Build a fake meta store manager that returns a single catalog entity. Every time the catalog is
+ * returned, an incremented entity version id is used. this is in order to disambiguate the entity
+ * returned by the cache and verify whether the cache is thread safe.
+ *
+ * <p>Think of it as a poor-man's Mockito. It is not a real mock, but it is good enough for this
+ * test. More importantly, it is a lot faster to instantiate than Mockito. It allows the stress test
+ * to run up to 100x more iterations in the same amount of time.
+ *
+ * <p>The only implemented methods are `loadResolvedEntityById` and `loadResolvedEntityByName`. Any
+ * time they are invoked, regardless of their parameters, the same catalog is returned but with an
+ * increased entity version id.
+ */
+public class FakeMetaStoreManager implements PolarisMetaStoreManager {
+ public static final int CATALOG_ID = 42;
+ private final Supplier<ResolvedEntityResult> catalogSupplier;
+
+ public FakeMetaStoreManager() {
+ final AtomicInteger versionCounter = new AtomicInteger(1);
+ this.catalogSupplier =
+ () -> {
+ int version = versionCounter.getAndIncrement();
+ CatalogEntity catalog =
+ new CatalogEntity.Builder()
+ .setId(CATALOG_ID)
+ .setInternalProperties(Map.of())
+ .setProperties(Map.of())
+ .setName("test")
+ .setParentId(PolarisEntityConstants.getRootEntityId())
+ .setEntityVersion(version)
+ .build();
+ return new ResolvedEntityResult(catalog, version, emptyList());
+ };
+ }
+
+ /**
+ * Utility method that ensures that catalogs creation is thread safe.
+ *
+ * @return a catalog entity with an incremented version id
+ */
+ private synchronized ResolvedEntityResult nextResult() {
Review Comment:
I'm not sure it adds correctness even to the old cache test. How the cache works should not be a reason for synchronizing or not on the Meta Store impl (in principle).
The `synchronized` block will probably make it extremely likely for the entity that increments the version counter first to also be returned first, but it is not guaranteed, I think :thinking: ... at least the caller may not be able to process the returned values in the same order.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035443386
##########
gradle/libs.versions.toml:
##########
@@ -97,6 +97,7 @@ threeten-extra = { module = "org.threeten:threeten-extra", version = "1.8.0" }
[plugins]
jandex = { id = "org.kordamp.gradle.jandex", version = "2.1.0" }
+jcstress = { id = "io.github.reyerizo.gradle.jcstress", version = "0.8.15" }
Review Comment:
Sure, running jcstress in "tough" mode isn't good for CI, so I agree that long-running tests should be separately.
But jcstress tests provide quite some value and are IMHO useful even during "normal" CI. That's why I'm advocating to have those in the module that's being exercised. And with that, you'd need the Gradle things I mentioned above. I've [added some for the nosql work](https://github.com/snazy/polaris/tree/persistence-nosql/nosql/idgen/impl/src/jcstress/java/org/apache/polaris/ids/impl) to ensure those essential pieces are safe to be used in concurrent scenarios.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2796453952
Rebased on main and force-pushed as I did not get an errorprone error for a check that failed CI
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "dennishuo (via GitHub)" <gi...@apache.org>.
dennishuo commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2072301410
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
The most important part of this hinges on two things:
1. Reading entity/grant *versions* is "cheaper" than reading the entire entities and grant records
2. The defined interfaces permit batch-lookup of entity/grant versions
(2) could also be added for getting entire entities/grant-records in bulk, but the max size of such a batch would be more sensitive vs smaller uniform-sized entityVersions records.
At a high-level the architecture for this is more like the Iceberg "freshness-aware loading" semantic than more common caching patterns.
The alternatives are:
1. Staleness and cross-server decoherence tolerance (changes the semantics of the callsites)
2. Active invalidation across the distributed system (complicated to implement)
I could see active invalidation maybe being an option to pursue in the future as an alternative to this freshness-aware readthrough type of pattern.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073684376
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -20,194 +20,99 @@
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.collect.HashBiMap;
+import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.GuardedBy;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.config.BehaviorChangeConfiguration;
import org.apache.polaris.core.config.FeatureConfiguration;
import org.apache.polaris.core.config.PolarisConfiguration;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
-/** An in-memory entity cache with a limit of 100k entities and a 1h TTL. */
+/** The entity cache, can be private or shared */
public class InMemoryEntityCache implements EntityCache {
-
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ @GuardedBy("lock")
+ private final Cache<Long, ResolvedPolarisEntity> cache;
+
+ // Map of entity names to entity ids
+ @GuardedBy("lock")
+ private final HashBiMap<Long, EntityCacheByNameKey> nameToIdMap;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final ReentrantReadWriteLock lock;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public InMemoryEntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
+ // remember the meta store manager
+ this.polarisMetaStoreManager = polarisMetaStoreManager;
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
+ // enabled by default
+ this.cacheMode = EntityCacheMode.ENABLE;
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
+ this.nameToIdMap = HashBiMap.create();
+ this.lock = new ReentrantReadWriteLock();
long weigherTarget =
PolarisConfiguration.loadConfig(FeatureConfiguration.ENTITY_CACHE_WEIGHER_TARGET);
- Caffeine<Long, ResolvedPolarisEntity> byIdBuilder =
+ Caffeine<Long, ResolvedPolarisEntity> cacheBuilder =
Caffeine.newBuilder()
.maximumWeight(weigherTarget)
.weigher(EntityWeigher.asWeigher())
.expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener); // Set the removal listener
+ // Add a removal listener so that the name-to-id mapping is also purged after every
+ // cache
+ // replacement, invalidation or expiration . Configure a direct executor so that the
+ // removal
+ // listener is invoked by the same thread that is updating the cache.
Review Comment:
You may need to call cleanUp() to ensure under your locks to ensure eviction happens under it. The write buffer, thread context switches, races could lead to an eviction happening afterwards since eviction uses a single lock. Caffeine uses ring buffers in a pub/sub fashion so that the shared policy state doesn’t require synchronization of all methods.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035420893
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
I think we're overall getting into a chicken-egg-problem here (with that check in general).
The caller provides the `entityMinVersion` and `entityGrantRecordsMinVersion`, but to have the "currently valid" values for those, it would have had hit the backend database first. However, that means, it would have bypassed the cache, which then raises the question why the cache's queried, if the caller (assuming it hit the database) already has the most up-to-date version.
Assuming the called did not hit the database first, it's unclear to me how cache-coherency across multiple Polaris instances is handled.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035455298
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
+
+ ResolvedPolarisEntity entity =
+ this.cache.get(
+ new IdKey(entityId),
+ () -> {
+ cacheHit.set(false);
Review Comment:
I know, my questions/concerns are about the side effects in combination with the various call sites/paths. Also considering concurrent writes to the same entities (plural) (like concurrent/conflicting renames/moves with concurrent/conflicting updates and such), which result in different functions being called (in different orders?) on `EntityCache`. And wrt to [my other comment](https://github.com/apache/polaris/pull/1339#discussion_r2035420893).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-5164260663
@MonkeyCanCode ultimately this contribution was rejected and I did not keep up with the other code changes regarding the entity cache. Closing this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2810172689
> where the changes made to the id-to-name index are made visible before cache operations complete.
I think you could mask that by using retry loops and versioning so that its treated like an optimistic read with a recheck condition. Then while you can make it internally visible prematurely but externally not. You could wrap the `Set<K>` keys by an `Index` type that also includes extra metadata, e.g. the value to perform an identity check and re-read if a stale traversal. If you want to avoid races causing redundant loads then there's no way except through an exclusive lock (or hiding that latency by returning a future if the caller can do other work in the meantime).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033879574
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
Review Comment:
fwiw, I don't care about attribution; you can treat the examples as public domain imho
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033787597
##########
gradle/libs.versions.toml:
##########
@@ -97,6 +97,7 @@ threeten-extra = { module = "org.threeten:threeten-extra", version = "1.8.0" }
[plugins]
jandex = { id = "org.kordamp.gradle.jandex", version = "2.1.0" }
+jcstress = { id = "io.github.reyerizo.gradle.jcstress", version = "0.8.15" }
Review Comment:
You probably also want in `[libraries]`
```
jcstress-core = { module = "org.openjdk.jcstress:jcstress-core", version = "0.16" }
```
+
```
tasks.named("jcstressJar") { dependsOn("jandex") }
tasks.named("compileJcstressJava") { dependsOn("jandex") }
tasks.named("check") { dependsOn("jcstress") }
jcstress { jcstressDependency = libs.jcstress.core.get().toString() }
```
where jcstress is being used
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
Review Comment:
Need the "magic" `CODE_COPIED_TO_POLARIS` in this file + a mention in `/LICENSE` for this file and the source project.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
Review Comment:
Nit: `final` is syntactic sugar.
Could just be
```suggestion
var cacheHit = new AtomicBoolean(true);
```
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
+
+ ResolvedPolarisEntity entity =
+ this.cache.get(
+ new IdKey(entityId),
+ () -> {
+ cacheHit.set(false);
Review Comment:
I think this needs to be guarded via `this.locks` as well, otherwise it can race with `getAndRefreshIfNeeded`. (Then we don't need the loader-function and force a `synchronized` lock in CHM.)
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
Review Comment:
Is this being used?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
Does this block make sense - mean, does the `getEntityById()` yield a concurrently loaded result often?
Not a major thing, just asking.
##########
bom/build.gradle.kts:
##########
@@ -50,5 +50,6 @@ dependencies {
api(project(":polaris-quarkus-spark-tests"))
api(project(":polaris-tests"))
+ api(project(":polaris-jcstress-tests"))
Review Comment:
Why not add the jcstress tests into the project that implements the cache?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
Review Comment:
100k entries here ;)
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
+ // the cache, once indexed by its identifier and once indexed by its name.
+ this.cache =
+ new IndexedCache.Builder<CacheKey, ResolvedPolarisEntity>()
+ .primaryKey(e -> new IdKey(e.getEntity().getId()))
+ .addSecondaryKey(e -> new NameKey(new EntityCacheByNameKey(e.getEntity())))
+ .expireAfterWrite(Duration.ofMinutes(5))
+ .maximumSize(10_000)
+ .build();
+ this.locks = Striped.lock(STRIPES);
}
/**
- * Remove the specified cache entry from the cache
+ * Remove the specified cache entry from the cache. This applies both to the cache entry indexed
+ * by its id and by its name.
*
* @param cacheEntry cache entry to remove
*/
public void removeCacheEntry(@Nonnull ResolvedPolarisEntity cacheEntry) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(cacheEntry.getEntity());
-
- // remove this old entry, this will immediately remove the named entry
- this.byId.asMap().remove(cacheEntry.getEntity().getId(), cacheEntry);
-
- // remove it from the name key
- this.byName.remove(nameKey, cacheEntry);
- }
-
- /**
- * Cache new entry
- *
- * @param cacheEntry new cache entry
- */
- private void cacheNewEntry(@Nonnull ResolvedPolarisEntity cacheEntry) {
-
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(cacheEntry.getEntity());
-
- // get old value if one exist
- ResolvedPolarisEntity oldCacheEntry = this.byId.getIfPresent(cacheEntry.getEntity().getId());
-
- // put new entry, only if really newer one
- this.byId
- .asMap()
- .merge(
- cacheEntry.getEntity().getId(),
- cacheEntry,
- (oldValue, newValue) -> this.isNewer(newValue, oldValue) ? newValue : oldValue);
-
- // only update the name key if this entity was not dropped
- if (!cacheEntry.getEntity().isDropped()) {
- // here we don't really care about concurrent update to the key. Basically if we are
- // pointing to the wrong entry, we will detect this and fix the issue
- this.byName.put(nameKey, cacheEntry);
- }
-
- // remove old name if it has changed
- if (oldCacheEntry != null) {
- // old name
- EntityCacheByNameKey oldNameKey = new EntityCacheByNameKey(oldCacheEntry.getEntity());
- if (!oldNameKey.equals(nameKey)) {
- this.byName.remove(oldNameKey, oldCacheEntry);
- }
- }
- }
-
- /**
- * Determine if the newer value is really newer
- *
- * @param newValue new cache entry
- * @param oldValue old cache entry
- * @return true if the newer cache entry
- */
- private boolean isNewer(ResolvedPolarisEntity newValue, ResolvedPolarisEntity oldValue) {
- return (newValue.getEntity().getEntityVersion() > oldValue.getEntity().getEntityVersion()
- || newValue.getEntity().getGrantRecordsVersion()
- > oldValue.getEntity().getGrantRecordsVersion());
- }
-
- /**
- * Replace an old entry with a new one
- *
- * @param oldCacheEntry old entry
- * @param newCacheEntry new entry
- */
- private void replaceCacheEntry(
- @Nullable ResolvedPolarisEntity oldCacheEntry, @Nonnull ResolvedPolarisEntity newCacheEntry) {
-
- // need to remove old?
- if (oldCacheEntry != null) {
- // only replace if there is a difference
- if (this.entityNameKeyMismatch(oldCacheEntry.getEntity(), newCacheEntry.getEntity())
- || oldCacheEntry.getEntity().getEntityVersion()
- < newCacheEntry.getEntity().getEntityVersion()
- || oldCacheEntry.getEntity().getGrantRecordsVersion()
- < newCacheEntry.getEntity().getGrantRecordsVersion()) {
- // write new one
- this.cacheNewEntry(newCacheEntry);
-
- // delete the old one assuming it has not been replaced by the above new entry
- this.removeCacheEntry(oldCacheEntry);
- }
- } else {
- // write new one
- this.cacheNewEntry(newCacheEntry);
- }
- }
-
- /**
- * Check if two entities have different cache keys (either by id or by name)
- *
- * @param entity the entity
- * @param otherEntity the other entity
- * @return true if there is a mismatch
- */
- private boolean entityNameKeyMismatch(
- @Nonnull PolarisBaseEntity entity, @Nonnull PolarisBaseEntity otherEntity) {
- return entity.getId() != otherEntity.getId()
- || entity.getParentId() != otherEntity.getParentId()
- || !entity.getName().equals(otherEntity.getName())
- || entity.getTypeCode() != otherEntity.getTypeCode();
+ IdKey key = new IdKey(cacheEntry.getEntity().getId());
+ this.cache.invalidate(key);
Review Comment:
This probably also needs to be guarded via `this.locks`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035456985
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
Review Comment:
Nope. That's why it's a "nit".
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033763472
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
+ // the cache, once indexed by its identifier and once indexed by its name.
+ this.cache =
+ new IndexedCache.Builder<CacheKey, ResolvedPolarisEntity>()
+ .primaryKey(e -> new IdKey(e.getEntity().getId()))
+ .addSecondaryKey(e -> new NameKey(new EntityCacheByNameKey(e.getEntity())))
+ .expireAfterWrite(Duration.ofMinutes(5))
+ .maximumSize(10_000)
Review Comment:
looks like mistaken copy-paste from the example; probably meant to add `expireAfterAccess`, et al.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2846778173
Merged `main` so that this includes the "EntityCache is an interface" change
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035750733
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ @VisibleForTesting
+ ConcurrentMap<K, LinkedHashSet<K>> getIndexes() {
+ return indexes;
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ requireNonNull(value);
+ var index = buildIndex(value);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue1) -> {
+ if (oldValue1 != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return value;
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.keySet().removeAll(index);
Review Comment:
I think you need to re-read the index in case it changes.
> indexes.keySet().removeAll(indexes.get(index.getFirst()));
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2034662023
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
+ }
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.keySet().removeAll(indexes.get(key));
Review Comment:
👍 Thanks, fixing that
##########
gradle/libs.versions.toml:
##########
@@ -97,6 +97,7 @@ threeten-extra = { module = "org.threeten:threeten-extra", version = "1.8.0" }
[plugins]
jandex = { id = "org.kordamp.gradle.jandex", version = "2.1.0" }
+jcstress = { id = "io.github.reyerizo.gradle.jcstress", version = "0.8.15" }
Review Comment:
There are three asks in this comment.
**1 - Explicitly add jcstress-core as a library**
Wouldn't this be over-engineering? AFAICT this is only in preparation of a hypothetical need to use a different jcstress version than the default one used by the gradle plugin.
**2 - Add dependency between jcstress compilation tasks and jandex**
I am not sure what these are for. The jcstress tests are working without those. Can you elaborate a bit?
**3 - Run jcstress tests with the `check` phrase**
I would be very careful about the implications of this ask. This can substantially increase the duration of the builds. As I wrote in another comment, stress tests are good for proving that issues exist and give good confidence that they are fixed. I don't think they should be executed against every commit.
More about this: before submitting this PR, I ran the jcstress tests with the `tough` mode, which took 15 minutes at 100% CPU usage on all 16 cores of my machine. No issue was found. I think it is better to work that way (i.e. run long tests before submitting a PR) than to enforce expensive tests which will find nothing 99.9% of the time.
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.apache.polaris.core.persistence.cache.FakeMetaStoreManager.CATALOG_ID;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.LL_Result;
+
+public class EntityCacheCoherenceTest {
+ /** The cache key associated with the catalog that is returned by the fake meta store manager. */
+ private static final EntityCacheByNameKey KEY = new EntityCacheByNameKey(CATALOG, "test");
+
+ @JCStressTest
+ @Description(
+ "Tests that the two caches inside EntityCache are coherent with one another. In this test, two"
+ + " actors are calling getOrLoadById and getOrLoadByName. The entities received by the"
+ + " actors are not checked as part of this test. Instead, an arbiter runs after the"
+ + " actors have performed their calls and checks the version of the entity that are in"
+ + " each of the two caches using the getter methods getEntityById and getEntityByName. "
+ + " Expected behaviour is that the two caches return the same entity version. Any"
+ + " discrepancy indicates that the caches are out of sync.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "The caches are out of sync"),
Review Comment:
Let me add that outcome to be comprehensive. Really, `1, 2` is just another "The caches are out of sync" case and is already caught by the `expect = UNKNOWN` outcome. Any unknown outcome results in the JCStress test to fail. But it is better to be thorough 👍.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
Review Comment:
It is not... It is a leftover from a tentative rewrite of `getAndRefreshIfNeeded`. Removing...
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
+ // We are the first to act upon this entity id, invalidate it
+ this.cache.invalidate(new IdKey(entityId));
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.getOrLoadEntityById(
Review Comment:
The goal of the EntityCache is not to be up to date 100% of the time. The `getAndRefreshIfNeeded` method is the only one that provides means to require an entity to be _sufficiently up to date_. The lock protects the `read-then-write` aspect of the operations (1) get the entity, (2) reload it if it is stale.
See my response to Robert a couple of lines above this one for more.
To be clear, it is possible that there are still unidentified race conditions in the code. The fact that the cache has two different ways of accessing the same entity is a very tricky design.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
+ // the cache, once indexed by its identifier and once indexed by its name.
+ this.cache =
+ new IndexedCache.Builder<CacheKey, ResolvedPolarisEntity>()
+ .primaryKey(e -> new IdKey(e.getEntity().getId()))
+ .addSecondaryKey(e -> new NameKey(new EntityCacheByNameKey(e.getEntity())))
+ .expireAfterWrite(Duration.ofMinutes(5))
+ .maximumSize(10_000)
Review Comment:
Good point. I did not look closely enough. I will add `expireAfterAccess` to the IndexedCache Builder class and leverage it.
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/FakeMetaStoreManager.java:
##########
@@ -0,0 +1,309 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static java.util.Collections.emptyList;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.*;
+import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
+import org.apache.polaris.core.persistence.dao.entity.*;
+import org.apache.polaris.core.storage.PolarisStorageActions;
+
+/**
+ * Build a fake meta store manager that returns a single catalog entity. Every time the catalog is
+ * returned, an incremented entity version id is used. this is in order to disambiguate the entity
+ * returned by the cache and verify whether the cache is thread safe.
+ *
+ * <p>Think of it as a poor-man's Mockito. It is not a real mock, but it is good enough for this
+ * test. More importantly, it is a lot faster to instantiate than Mockito. It allows the stress test
+ * to run up to 100x more iterations in the same amount of time.
+ *
+ * <p>The only implemented methods are `loadResolvedEntityById` and `loadResolvedEntityByName`. Any
+ * time they are invoked, regardless of their parameters, the same catalog is returned but with an
+ * increased entity version id.
+ */
+public class FakeMetaStoreManager implements PolarisMetaStoreManager {
+ public static final int CATALOG_ID = 42;
+ private final Supplier<ResolvedEntityResult> catalogSupplier;
+
+ public FakeMetaStoreManager() {
+ final AtomicInteger versionCounter = new AtomicInteger(1);
+ this.catalogSupplier =
+ () -> {
+ int version = versionCounter.getAndIncrement();
+ CatalogEntity catalog =
+ new CatalogEntity.Builder()
+ .setId(CATALOG_ID)
+ .setInternalProperties(Map.of())
+ .setProperties(Map.of())
+ .setName("test")
+ .setParentId(PolarisEntityConstants.getRootEntityId())
+ .setEntityVersion(version)
+ .build();
+ return new ResolvedEntityResult(catalog, version, emptyList());
+ };
+ }
+
+ /**
+ * Utility method that ensures that catalogs creation is thread safe.
+ *
+ * @return a catalog entity with an incremented version id
+ */
+ private synchronized ResolvedEntityResult nextResult() {
Review Comment:
With the previous implementation, it was possible that multiple calls to the `PolarisMetaStoreManager` were issued simultaneously for the entity. So synchronization was necessary to ensure that the returned entities were themselves correct with total ordering.
Now, with the IndexedCache based implementation, I think that this is not needed anymore. I believe that the cache first gets an internal lock for the key it is about to load **before** loading the associated entity from the `PolarisMetaStoreManager`. So a critical section might be superfluous. But I think it is good to keep it in case anybody wants to run additional tests against the old `EntityCache`.
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheGetAndRefreshIfNeededTest.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.PolarisBaseEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.II_Result;
+
+@JCStressTest
+@Description(
+ "Tests getAndRefreshIfNeeded is thread-safe. In this test, two actors are calling"
+ + " getAndRefreshIfNeeded twice on the same key. Each actor returns the version of the"
+ + " entity returned by the two calls to getAndRefreshIfNeeded. The method is invoked using"
+ + " a minimum entity version equal to 2. Expected behaviour is that the two actors get"
+ + " the same object twice, or for an object to be updated to a newer version between"
+ + " reads. But the cache should never go backward and server a stale version after a newer"
Review Comment:
oops
##########
bom/build.gradle.kts:
##########
@@ -50,5 +50,6 @@ dependencies {
api(project(":polaris-quarkus-spark-tests"))
api(project(":polaris-tests"))
+ api(project(":polaris-jcstress-tests"))
Review Comment:
It could be a valid option too. It would colocate the stress tests with the code that they stress. I did not choose that approach for a couple of reasons:
1. There is an `integration-tests` module under the root directory, and stress tests are just another form of testing that is very different from unit testing.
2. Stress tests should not be executed in every build. They should be used to prove out that issues exists, and give reasonable confidence that issues are fixed. So they have a different lifecycle.
3. As I was not sure they would be accepted in the project, because of jcstress GPL, I did not want to have invasive code modifications to existing modules
If you really want the stress tests to be colocated with their associated module, I can do that.
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.apache.polaris.core.persistence.cache.FakeMetaStoreManager.CATALOG_ID;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.LL_Result;
+
+public class EntityCacheCoherenceTest {
+ /** The cache key associated with the catalog that is returned by the fake meta store manager. */
+ private static final EntityCacheByNameKey KEY = new EntityCacheByNameKey(CATALOG, "test");
+
+ @JCStressTest
+ @Description(
+ "Tests that the two caches inside EntityCache are coherent with one another. In this test, two"
+ + " actors are calling getOrLoadById and getOrLoadByName. The entities received by the"
+ + " actors are not checked as part of this test. Instead, an arbiter runs after the"
+ + " actors have performed their calls and checks the version of the entity that are in"
+ + " each of the two caches using the getter methods getEntityById and getEntityByName. "
+ + " Expected behaviour is that the two caches return the same entity version. Any"
+ + " discrepancy indicates that the caches are out of sync.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "The caches are out of sync"),
+ @Outcome(expect = UNKNOWN, desc = "Not sure what happened"),
+ })
+ @State()
+ public static class UsingGetters {
+ private final PolarisCallContext context;
+ private final EntityCache entityCache;
+
+ public UsingGetters() {
+ context = new PolarisCallContext(new FakeBasePersistence(), new FakePolarisDiagnostics());
+ entityCache = new EntityCache(new FakeMetaStoreManager());
+ }
+
+ @Actor
+ public void actor1() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+
+ @Actor
+ public void actor2() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
Review Comment:
For the old EntityCache implementation, calling the getters in the reverse order was actuall _nicer_ to the code than calling them in the same order. So I went for the hardest code path upfront.
For the new implementation, it does not really matter. No matter which getter is executed first (by name or by ID), once the entity is fetched from the underlying database, the cache will be populated by ID first. And a lock based on the ID will be used to protect the operation. So both orders resolve to the same thing.
Do you want me to add an additional case here?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
Review Comment:
It is not... It is a leftover from a tentative rewrite of `getAndRefreshIfNeeded`. Removing...
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
+
+ ResolvedPolarisEntity entity =
+ this.cache.get(
+ new IdKey(entityId),
+ () -> {
+ cacheHit.set(false);
Review Comment:
It can race with `getAndRefreshIfNeeded`, indeed. But those races only result in
* the cache being populated earlier, if `getOrLoadEntityById` goes first
* the cache being populated twice, if `getOrLoadEntityById` goes first while the entity was updated by another process
* the cache being populated with a fresh-enough entity if `getAndRefreshIfNeeded` goes first
It would be possible to remove all race conditions by using a lock over the entire cache. Typically, a `ReentrantReadWriteLock`. But depending on the cache update rate, this could have serious performance implications.
So, back to the more fundamental question. And really this is all about the guarantees that `EntityCache` currently provides.
The `EntityCache` does not have any guarantee about the staleness of entities returned by `getOrLoadEntityBy...`. The only guarantees it provides now are that if an entry exists in the database, it can be fetched using its id or name. At no time should those methods return `null` if an entity exists.
However, it guarantees that entities returned by `getAndRefreshIfNeeded` will be invalidated and reloaded from the underlying database if the requested version is higher than the currently cached version. And that is the behaviour that is allowed by the current code.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
Review Comment:
Done
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -365,50 +230,46 @@ && isNewer(existingCacheEntry, existingCacheEntryByName)) {
long entityCatalogId,
long entityId,
PolarisEntityType entityType) {
-
- // if it exists, we are set
- ResolvedPolarisEntity entry = this.getEntityById(entityId);
- final boolean cacheHit;
-
- // we need to load it if it does not exist
- if (entry == null) {
- // this is a miss
- cacheHit = false;
-
- // load it
- ResolvedEntityResult result =
- polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
-
- // not found, exit
- if (!result.isSuccess()) {
- return null;
- }
-
- // if found, setup entry
- callContext.getDiagServices().checkNotNull(result.getEntity(), "entity_should_loaded");
- callContext
- .getDiagServices()
- .checkNotNull(result.getEntityGrantRecords(), "entity_grant_records_should_loaded");
- entry =
- new ResolvedPolarisEntity(
- callContext.getDiagServices(),
- result.getEntity(),
- result.getEntityGrantRecords(),
- result.getGrantRecordsVersion());
-
- // the above loading could take a long time so check again if the entry exists and only
- this.cacheNewEntry(entry);
+ final AtomicBoolean cacheHit = new AtomicBoolean(true);
Review Comment:
Is there strong preference for `var` in the Polaris codebase?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
+ Comparator.nullsLast(
+ Comparator.<ResolvedPolarisEntity>comparingInt(rpe -> rpe.getEntity().getEntityVersion())
+ .thenComparingInt(rpe -> rpe.getEntity().getGrantRecordsVersion()));
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
+ // the cache, once indexed by its identifier and once indexed by its name.
+ this.cache =
+ new IndexedCache.Builder<CacheKey, ResolvedPolarisEntity>()
+ .primaryKey(e -> new IdKey(e.getEntity().getId()))
+ .addSecondaryKey(e -> new NameKey(new EntityCacheByNameKey(e.getEntity())))
+ .expireAfterWrite(Duration.ofMinutes(5))
+ .maximumSize(10_000)
+ .build();
+ this.locks = Striped.lock(STRIPES);
}
/**
- * Remove the specified cache entry from the cache
+ * Remove the specified cache entry from the cache. This applies both to the cache entry indexed
+ * by its id and by its name.
*
* @param cacheEntry cache entry to remove
*/
public void removeCacheEntry(@Nonnull ResolvedPolarisEntity cacheEntry) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(cacheEntry.getEntity());
-
- // remove this old entry, this will immediately remove the named entry
- this.byId.asMap().remove(cacheEntry.getEntity().getId(), cacheEntry);
-
- // remove it from the name key
- this.byName.remove(nameKey, cacheEntry);
- }
-
- /**
- * Cache new entry
- *
- * @param cacheEntry new cache entry
- */
- private void cacheNewEntry(@Nonnull ResolvedPolarisEntity cacheEntry) {
-
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(cacheEntry.getEntity());
-
- // get old value if one exist
- ResolvedPolarisEntity oldCacheEntry = this.byId.getIfPresent(cacheEntry.getEntity().getId());
-
- // put new entry, only if really newer one
- this.byId
- .asMap()
- .merge(
- cacheEntry.getEntity().getId(),
- cacheEntry,
- (oldValue, newValue) -> this.isNewer(newValue, oldValue) ? newValue : oldValue);
-
- // only update the name key if this entity was not dropped
- if (!cacheEntry.getEntity().isDropped()) {
- // here we don't really care about concurrent update to the key. Basically if we are
- // pointing to the wrong entry, we will detect this and fix the issue
- this.byName.put(nameKey, cacheEntry);
- }
-
- // remove old name if it has changed
- if (oldCacheEntry != null) {
- // old name
- EntityCacheByNameKey oldNameKey = new EntityCacheByNameKey(oldCacheEntry.getEntity());
- if (!oldNameKey.equals(nameKey)) {
- this.byName.remove(oldNameKey, oldCacheEntry);
- }
- }
- }
-
- /**
- * Determine if the newer value is really newer
- *
- * @param newValue new cache entry
- * @param oldValue old cache entry
- * @return true if the newer cache entry
- */
- private boolean isNewer(ResolvedPolarisEntity newValue, ResolvedPolarisEntity oldValue) {
- return (newValue.getEntity().getEntityVersion() > oldValue.getEntity().getEntityVersion()
- || newValue.getEntity().getGrantRecordsVersion()
- > oldValue.getEntity().getGrantRecordsVersion());
- }
-
- /**
- * Replace an old entry with a new one
- *
- * @param oldCacheEntry old entry
- * @param newCacheEntry new entry
- */
- private void replaceCacheEntry(
- @Nullable ResolvedPolarisEntity oldCacheEntry, @Nonnull ResolvedPolarisEntity newCacheEntry) {
-
- // need to remove old?
- if (oldCacheEntry != null) {
- // only replace if there is a difference
- if (this.entityNameKeyMismatch(oldCacheEntry.getEntity(), newCacheEntry.getEntity())
- || oldCacheEntry.getEntity().getEntityVersion()
- < newCacheEntry.getEntity().getEntityVersion()
- || oldCacheEntry.getEntity().getGrantRecordsVersion()
- < newCacheEntry.getEntity().getGrantRecordsVersion()) {
- // write new one
- this.cacheNewEntry(newCacheEntry);
-
- // delete the old one assuming it has not been replaced by the above new entry
- this.removeCacheEntry(oldCacheEntry);
- }
- } else {
- // write new one
- this.cacheNewEntry(newCacheEntry);
- }
- }
-
- /**
- * Check if two entities have different cache keys (either by id or by name)
- *
- * @param entity the entity
- * @param otherEntity the other entity
- * @return true if there is a mismatch
- */
- private boolean entityNameKeyMismatch(
- @Nonnull PolarisBaseEntity entity, @Nonnull PolarisBaseEntity otherEntity) {
- return entity.getId() != otherEntity.getId()
- || entity.getParentId() != otherEntity.getParentId()
- || !entity.getName().equals(otherEntity.getName())
- || entity.getTypeCode() != otherEntity.getTypeCode();
+ IdKey key = new IdKey(cacheEntry.getEntity().getId());
+ this.cache.invalidate(key);
Review Comment:
I am not sure about this one. The `locks` field is used to protect the read-then-write section in `getAndRefreshIfNeeded()`. All the other accesses to the cache are done using the entity id and are thread-safe. Am I missing something?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
Yes, this block makes sense, but the "why" is far from trivial.
See this jcstress report without the duplicated `getEntityById() ... if refreshed, return` block you commented on.

The `3, 4` and `3, 5` cases are not that bad. They are just unnecessary calls to the database and should be marked as `Interesting`, really. But the `3, 2` case is definitely wrong. This race condition exists because of a combination of factors:
1. The `IndexedCache` instance can be accessed outside of the lock (by design)
2. Even though its two underlying data structures (Caffeine cache and `ConcurrentHashMap`) *are* thread safe, the combination of both is not. Thus it is possible to observe an updated `indexes` CHM before the cache itself has been updated.
The `locks` are there to protect the read-then-write requirement of `getAndRefreshIfNeeded`. It is the only place where such a pattern happens. That pattern is very tricky to handle properly (and should probably not exist, if you ask me). And the only way I could find to support it is to have a double-checked locking idiom.
An alternative could be to use much more coarse-grained locks but it would degrade performance by a lot. The `Indexed` cache could also expose its `locks` using methods `lock(id)` and `unlock(id)`, but then the caller would have to know exactly how to use it, at the risk of causing a full deadlock.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
Review Comment:
I am kind of -1 for moving it to a different package as it would mean having to make the cache and the cache key objects public. I guess it depends on the development practices of the project though.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035522063
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
@snazy To be honest, I am not sure about this design either. That being said there is an important nuance. The `getAndRefreshIfNeeded` method guarantees that if an entity is stale, it will be re-fetched. But it does **not** guarantee that the entity that will be returned has the right entity version, or even an entity version greater than the `entityMinVersion` and `entityGrantRecordsMinVersion` passed by the caller.
In other words, it would be possible to call `getAndRefreshIfNeeded` with `Integer.MAX_VALUE` for both minimum versions in order to force a round-trip to the database. I am not sure if that pattern is ever used in the codebase. But the code allows that to happen.
> Assuming the caller did not hit the database first, it's unclear to me how cache-coherency across multiple Polaris instances is handled.
This is a very good question. Like, one could imagine an event-based system where Polaris servers would be informed that a new version of an entity has been created. But then, why not just use a distributed cache altogether...?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2809480671
Just a heads up, I tried to rewrite the EntityCache using two distinct Caffeine caches but failed. The `getOrLoadEntityById` and `getOrLoadEntityByName` methods may fail to find the entity in the database, in case the entity has been deleted. In that case, it is impossible to determine the entity name that is associated with a particular id, or the id that is associated with a particular name. And the two caches will diverge once again.
Really it is the same issue than with the IndexedCache implementation where the changes made to the id-to-name index are made visible before cache operations complete.
I am starting to think that this design (an entity that has two primary keys and that should be available via both) cannot be implemented in a fully thread-safe manner...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2047332444
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ @VisibleForTesting
+ ConcurrentMap<K, LinkedHashSet<K>> getIndexes() {
+ return indexes;
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ requireNonNull(value);
+ var index = buildIndex(value);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue1) -> {
+ if (oldValue1 != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return value;
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.keySet().removeAll(index);
Review Comment:
@pingtimeout reminder ^
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035504254
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
+ }
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.remove(k);
Review Comment:
Why are we not removing `indexes` entries for the secondary keys? They will be pointing to a non-existing `store` entry after this call completes, it seems :thinking:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035407381
##########
bom/build.gradle.kts:
##########
@@ -50,5 +50,6 @@ dependencies {
api(project(":polaris-quarkus-spark-tests"))
api(project(":polaris-tests"))
+ api(project(":polaris-jcstress-tests"))
Review Comment:
For background: `integration-tests` are meant for reuse downstream, hence a separate module.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2815122531
Thanks for the help @ben-manes. I went back to the drawing board and have a better understanding of the kind of issues that can happen.
I have reimplemented the `EntityCache` using a plain `Cache` instance as well as a Guava `BiMap` to hold the bidirectional mapping between entities id and name. I also used a single `ReentrantReadWriteLock` to guard all modifications to the cache. This implementation :
* passes all the unit tests as well as the concurrency tests
* only issues the strict minimum number of calls to the database
* does not expose any internal desynchronization between the cache and the name-to-id mapping
I am going to push the code so that a CI run fully validates it.
In the meantime, I started working on a better version that would use a `Striped<ReadWriteLock>` as you did with the `IndexedCache`. But the main issue is that with such a lock, we get a false sense of security. Because entities can be "locked" twice: once using the id and once using the name as the key. This issue happens in the `EntityCache` as well as in my current code. A possible workaround that I can think of is to:
1. Acquire a striped lock using the same value for all entities retrieved by name (say `0L`)
2. Check if an entity with that name is in cache
3. If not, load it from the database and delegate the "add to cache" logic to the same logic that does this by the entity ID
4. This will, in turn, grab another striped lock based on the entity ID and do the rest as usual
I need to double check (and test) that no deadlock can happen with this double locking sequence. I will post updates here...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2815601540
😭 So no matter whether I rebase `main` and force-push or merge `main`, all reviews are gone.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073458495
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -267,104 +189,70 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
-
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
-
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ lock.writeLock().lock();
+ try {
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
+
+ // Either confirmed cache miss, or the entity is stale. Invalidate it just in case.
+ cache.invalidate(entityId);
+
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.maybeLoadEntityById(
Review Comment:
So, there is another caveat. In the initial `IndexedCache` implementation, indeed, a `Striped<Lock>` was used to have up to 1k different locks and improve write throughput. But the `getOrLoadEntityByName(...)` method prevents the use of such striped locks altogether as otherwise it could lead to a deadlock.
The logic is that in order to update the cache for a given entity, two write locks must be held: one for the entity ID and one for the entity name. Problem: such a sequence of event would prevent the dual-lock acquisition to be in a consistent order:
1. Thread A calls `getOrLoadEntityById()` for entity with id 123
2. Thread A acquires the write lock for entity 123
3. Thread A determines that this corresponds to entity with name `Foo`, but before the lock for that name is acquired...
4. Thread B calls `getOrLoadEntityByName()` for entity with name `Foo`
5. Thread B acquires the write lock for entity with name `Foo`
6. Thread B determines that this corresponds to entity with id 123
7. Thread A cannot acquire the lock for name `Foo`
8. Thread B cannot acquire the lock for id 123
Essentially, it would be trivial to solve this by imposing a lock order like "first get the lock by ID and then by name" (or the other way around). But that order cannot be enforced all the time.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073386340
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -267,104 +189,70 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
-
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
-
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ lock.writeLock().lock();
+ try {
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
+
+ // Either confirmed cache miss, or the entity is stale. Invalidate it just in case.
+ cache.invalidate(entityId);
+
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.maybeLoadEntityById(
+ callContext, entityToValidate.getCatalogId(), entityId, entityToValidate.getType());
+ if (cacheLookupResult == null) {
+ // Entity has been purged, and we have already cleaned the cache and the name-to-id mapping,
Review Comment:
> Does this already cleaned the cache and the name-to-id mapping refer to line 223 where we called cache.invalidate? Where does the by-name map get cleaned here?
Correct. When the `Caffeine` cache builder is constructed L77, a removal listener is added so that whenever an entry is removed for any reason (replaced, removed, evicted, GC'ed), the `this::remove` method is called. With the current design, any cache modification can only be performed while holding the write lock. I can add some comment block toward the beginning of the class to explain that:
* Any cache read require getting a read lock
* Any cache modification require getting a write lock
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout closed pull request #1339: Fix EntityCache correctness issues and leak
URL: https://github.com/apache/polaris/pull/1339
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2073684376
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/InMemoryEntityCache.java:
##########
@@ -20,194 +20,99 @@
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.collect.HashBiMap;
+import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.GuardedBy;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.config.BehaviorChangeConfiguration;
import org.apache.polaris.core.config.FeatureConfiguration;
import org.apache.polaris.core.config.PolarisConfiguration;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
-/** An in-memory entity cache with a limit of 100k entities and a 1h TTL. */
+/** The entity cache, can be private or shared */
public class InMemoryEntityCache implements EntityCache {
-
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ @GuardedBy("lock")
+ private final Cache<Long, ResolvedPolarisEntity> cache;
+
+ // Map of entity names to entity ids
+ @GuardedBy("lock")
+ private final HashBiMap<Long, EntityCacheByNameKey> nameToIdMap;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final ReentrantReadWriteLock lock;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public InMemoryEntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
+ // remember the meta store manager
+ this.polarisMetaStoreManager = polarisMetaStoreManager;
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
+ // enabled by default
+ this.cacheMode = EntityCacheMode.ENABLE;
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
+ this.nameToIdMap = HashBiMap.create();
+ this.lock = new ReentrantReadWriteLock();
long weigherTarget =
PolarisConfiguration.loadConfig(FeatureConfiguration.ENTITY_CACHE_WEIGHER_TARGET);
- Caffeine<Long, ResolvedPolarisEntity> byIdBuilder =
+ Caffeine<Long, ResolvedPolarisEntity> cacheBuilder =
Caffeine.newBuilder()
.maximumWeight(weigherTarget)
.weigher(EntityWeigher.asWeigher())
.expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener); // Set the removal listener
+ // Add a removal listener so that the name-to-id mapping is also purged after every
+ // cache
+ // replacement, invalidation or expiration . Configure a direct executor so that the
+ // removal
+ // listener is invoked by the same thread that is updating the cache.
Review Comment:
You may need to call cleanUp() to ensure under your locks to ensure eviction happens under it. The write buffer, thread context switches, races could lead to an eviction happening afterwards since eviction uses a single lock. Caffeine uses ring buffers in a pub/sub fashion so that the shared policy state doesn’t require synchronization of all methods. The cleanup might not be strong enough unless you coordinate above it correctly. I guess it’s to say the cache needs to promise the behavior, you can’t assume how it might work
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "ben-manes (via GitHub)" <gi...@apache.org>.
ben-manes commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033714293
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
+ }
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.keySet().removeAll(indexes.get(key));
Review Comment:
I had a small typo here, where this should be `index.iterator().next()` (or `k` if you prefer). Otherwise it exposes a very tiny race condition where the index changes while waiting for the entry's lock. The `computeIfPresent` ensures it is called when there is an entry and therefore an index, but if the secondary key is disassociated then `index.get(key)` could return null. It needs to lookup the current index but use the immutable primary key.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2033776337
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheGetByIdTest.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.II_Result;
+import org.openjdk.jcstress.infra.results.I_Result;
+
+public class EntityCacheGetByIdTest {
+
+ @JCStressTest
+ @Description(
+ "Tests getOrLoadById is thread-safe. In this test, two actors are calling getOrLoadById "
+ + "twice on the same key. Each actor returns the version of the entity returned by the "
+ + "two calls to getOrLoadById. Expected behaviour is that the two actors get the same "
+ + "object twice, or for an object to be updated to a newer version between reads. "
+ + "But the cache should never go backward and server a stale version after a newer one "
+ + "has been observed as it is not allowed by `cacheNewEntry`.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "Got the same object twice"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "Got the same object twice"),
+ @Outcome(id = "1, 2", expect = ACCEPTABLE_INTERESTING, desc = "Got updated object"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "Got stale object after update"),
+ @Outcome(expect = UNKNOWN, desc = "Not sure what happened"),
+ })
+ @State()
+ public static class WithoutArbiter {
+ private final PolarisCallContext context;
+ private final EntityCache entityCache;
+
+ public WithoutArbiter() {
+ context = new PolarisCallContext(new FakeBasePersistence(), new FakePolarisDiagnostics());
+ entityCache = new EntityCache(new FakeMetaStoreManager());
+ }
+
+ @Actor
+ public void actor1(II_Result result) {
+ result.r1 =
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ result.r2 =
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+
+ @Actor
+ public void actor2(II_Result result) {
+ result.r1 =
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ result.r2 =
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+ }
+
+ @JCStressTest
+ @Description(
+ "Tests getOrLoadById is thread-safe. In this test, two actors are calling getOrLoadById "
+ + "twice on the same key. The updates received by the actors are not checked as part of "
+ + "this test. Instead, an arbiter runs after the actors have performed their calls and "
+ + "checks the version of the entity that is in the cache. Expected behaviour is that "
+ + "at most two database calls happens. Thus only versions 1 and 2 are acceptable. Any "
+ + "other version indicates that the cache was updated even after both threads populated "
+ + "it with their own values.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1", expect = ACCEPTABLE, desc = "All cache calls happened in sequence"),
+ @Outcome(id = "2", expect = ACCEPTABLE_INTERESTING, desc = "Concurrent cache updates happened"),
+ @Outcome(expect = FORBIDDEN, desc = "Threads did not read their own writes"),
+ })
+ @State()
+ public static class WithArbiter {
+ private final PolarisCallContext context;
+ private final EntityCache entityCache;
+
+ public WithArbiter() {
+ context = new PolarisCallContext(new FakeBasePersistence(), new FakePolarisDiagnostics());
+ entityCache = new EntityCache(new FakeMetaStoreManager());
+ }
+
+ @Actor
+ public void actor1() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+
+ @Actor
+ public void actor2() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, FakeMetaStoreManager.CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
Review Comment:
Are these three calls necessary?
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheGetAndRefreshIfNeededTest.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.PolarisBaseEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.II_Result;
+
+@JCStressTest
+@Description(
+ "Tests getAndRefreshIfNeeded is thread-safe. In this test, two actors are calling"
+ + " getAndRefreshIfNeeded twice on the same key. Each actor returns the version of the"
+ + " entity returned by the two calls to getAndRefreshIfNeeded. The method is invoked using"
+ + " a minimum entity version equal to 2. Expected behaviour is that the two actors get"
+ + " the same object twice, or for an object to be updated to a newer version between"
+ + " reads. But the cache should never go backward and server a stale version after a newer"
Review Comment:
`server` -> `serve`?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
Review Comment:
Maybe move it to a dedicated package for clarity? e.g. `org.apache.polaris.caffeine`?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
Review Comment:
I believe this file need a `CODE_COPIED_TO_POLARIS` comment.
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
+ // We are the first to act upon this entity id, invalidate it
+ this.cache.invalidate(new IdKey(entityId));
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.getOrLoadEntityById(
Review Comment:
Parallel calls to `getOrLoadEntityById` are allowed without a lock... Why do we do this under a lock in this case?
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/FakeMetaStoreManager.java:
##########
@@ -0,0 +1,309 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static java.util.Collections.emptyList;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.*;
+import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
+import org.apache.polaris.core.persistence.dao.entity.*;
+import org.apache.polaris.core.storage.PolarisStorageActions;
+
+/**
+ * Build a fake meta store manager that returns a single catalog entity. Every time the catalog is
+ * returned, an incremented entity version id is used. this is in order to disambiguate the entity
+ * returned by the cache and verify whether the cache is thread safe.
+ *
+ * <p>Think of it as a poor-man's Mockito. It is not a real mock, but it is good enough for this
+ * test. More importantly, it is a lot faster to instantiate than Mockito. It allows the stress test
+ * to run up to 100x more iterations in the same amount of time.
+ *
+ * <p>The only implemented methods are `loadResolvedEntityById` and `loadResolvedEntityByName`. Any
+ * time they are invoked, regardless of their parameters, the same catalog is returned but with an
+ * increased entity version id.
+ */
+public class FakeMetaStoreManager implements PolarisMetaStoreManager {
+ public static final int CATALOG_ID = 42;
+ private final Supplier<ResolvedEntityResult> catalogSupplier;
+
+ public FakeMetaStoreManager() {
+ final AtomicInteger versionCounter = new AtomicInteger(1);
+ this.catalogSupplier =
+ () -> {
+ int version = versionCounter.getAndIncrement();
+ CatalogEntity catalog =
+ new CatalogEntity.Builder()
+ .setId(CATALOG_ID)
+ .setInternalProperties(Map.of())
+ .setProperties(Map.of())
+ .setName("test")
+ .setParentId(PolarisEntityConstants.getRootEntityId())
+ .setEntityVersion(version)
+ .build();
+ return new ResolvedEntityResult(catalog, version, emptyList());
+ };
+ }
+
+ /**
+ * Utility method that ensures that catalogs creation is thread safe.
+ *
+ * @return a catalog entity with an incremented version id
+ */
+ private synchronized ResolvedEntityResult nextResult() {
Review Comment:
Why does it need to be `synchronized`?
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,74 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final Comparator<ResolvedPolarisEntity> RESOLVED_POLARIS_ENTITY_COMPARATOR =
Review Comment:
Is it used?
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.apache.polaris.core.persistence.cache.FakeMetaStoreManager.CATALOG_ID;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.LL_Result;
+
+public class EntityCacheCoherenceTest {
+ /** The cache key associated with the catalog that is returned by the fake meta store manager. */
+ private static final EntityCacheByNameKey KEY = new EntityCacheByNameKey(CATALOG, "test");
+
+ @JCStressTest
+ @Description(
+ "Tests that the two caches inside EntityCache are coherent with one another. In this test, two"
+ + " actors are calling getOrLoadById and getOrLoadByName. The entities received by the"
+ + " actors are not checked as part of this test. Instead, an arbiter runs after the"
+ + " actors have performed their calls and checks the version of the entity that are in"
+ + " each of the two caches using the getter methods getEntityById and getEntityByName. "
+ + " Expected behaviour is that the two caches return the same entity version. Any"
+ + " discrepancy indicates that the caches are out of sync.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "The caches are out of sync"),
Review Comment:
What about `1, 2`?
##########
jcstress-tests/src/jcstress/java/org/apache/polaris/core/persistence/cache/EntityCacheCoherenceTest.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static org.apache.polaris.core.entity.PolarisEntityType.CATALOG;
+import static org.apache.polaris.core.persistence.cache.FakeMetaStoreManager.CATALOG_ID;
+import static org.openjdk.jcstress.annotations.Expect.*;
+
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.openjdk.jcstress.annotations.*;
+import org.openjdk.jcstress.infra.results.LL_Result;
+
+public class EntityCacheCoherenceTest {
+ /** The cache key associated with the catalog that is returned by the fake meta store manager. */
+ private static final EntityCacheByNameKey KEY = new EntityCacheByNameKey(CATALOG, "test");
+
+ @JCStressTest
+ @Description(
+ "Tests that the two caches inside EntityCache are coherent with one another. In this test, two"
+ + " actors are calling getOrLoadById and getOrLoadByName. The entities received by the"
+ + " actors are not checked as part of this test. Instead, an arbiter runs after the"
+ + " actors have performed their calls and checks the version of the entity that are in"
+ + " each of the two caches using the getter methods getEntityById and getEntityByName. "
+ + " Expected behaviour is that the two caches return the same entity version. Any"
+ + " discrepancy indicates that the caches are out of sync.")
+ @Outcome.Outcomes({
+ @Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 2", expect = ACCEPTABLE, desc = "The caches are in sync"),
+ @Outcome(id = "2, 1", expect = FORBIDDEN, desc = "The caches are out of sync"),
+ @Outcome(expect = UNKNOWN, desc = "Not sure what happened"),
+ })
+ @State()
+ public static class UsingGetters {
+ private final PolarisCallContext context;
+ private final EntityCache entityCache;
+
+ public UsingGetters() {
+ context = new PolarisCallContext(new FakeBasePersistence(), new FakePolarisDiagnostics());
+ entityCache = new EntityCache(new FakeMetaStoreManager());
+ }
+
+ @Actor
+ public void actor1() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ }
+
+ @Actor
+ public void actor2() {
+ entityCache
+ .getOrLoadEntityById(context, 0L, CATALOG_ID, CATALOG)
+ .getCacheEntry()
+ .getEntity()
+ .getEntityVersion();
+ entityCache
+ .getOrLoadEntityByName(context, KEY)
Review Comment:
Why not call the getters in the reverse order too?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2787112851
Note: I am having issues running the tests locally. My Docker setup does not seem right. Relying on CI for now...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035420893
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
Review Comment:
I think we're overall getting into a chicken-egg-problem here (with that check in general).
The caller provides the `entityMinVersion` and `entityGrantRecordsMinVersion`, but to have the "currently valid" values for those, it would have had hit the backend database first. However, that means, it would have bypassed the cache, which then raises the question why the cache's queried, if the caller (assuming it hit the database) already has the most up-to-date version.
Assuming the caller did not hit the database first, it's unclear to me how cache-coherency across multiple Polaris instances is handled.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "pingtimeout (via GitHub)" <gi...@apache.org>.
pingtimeout commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035693488
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
Review Comment:
My bad, another leftover from the attempt at moving the entity version comparison logic to the IndexedCache...
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Striped;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.LinkedHashSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// CODE_COPIED_TO_POLARIS
+// Source:
+// https://github.com/ben-manes/caffeine/blob/master/examples/indexable/src/main/java/com/github/benmanes/caffeine/examples/indexable/IndexedCache.java
+
+/**
+ * A cache abstraction that allows the entry to looked up by alternative keys. This approach mirrors
+ * a database table where a row is stored by its primary key, it contains all of the columns that
+ * identify it, and the unique indexes are additional mappings defined by the column mappings. This
+ * class similarly stores the in the value once in the cache by its primary key and maintains a
+ * secondary mapping for lookups by using indexing functions to derive the keys.
+ *
+ * @author ben.manes@gmail.com (Ben Manes)
+ */
+final class IndexedCache<K, V> {
+ private final ConcurrentMap<K, LinkedHashSet<K>> indexes;
+ private final LinkedHashSet<Function<V, K>> indexers;
+ private final Striped<Lock> locks;
+ private final Cache<K, V> store;
+
+ private IndexedCache(
+ Caffeine<Object, Object> cacheBuilder, LinkedHashSet<Function<V, K>> indexers) {
+ this.indexes = new ConcurrentHashMap<>();
+ this.locks = Striped.lock(1_024);
+ this.indexers = indexers;
+ this.store =
+ cacheBuilder
+ .evictionListener((key, value, cause) -> indexes.keySet().removeAll(indexes.get(key)))
+ .build();
+ }
+
+ /** Returns the value associated with the key or {@code null} if not found. */
+ V getIfPresent(K key) {
+ var index = indexes.get(key);
+ return (index == null) ? null : store.getIfPresent(index.iterator().next());
+ }
+
+ /**
+ * Returns the value associated with the key, obtaining that value from the {@code loader} if
+ * necessary. The entire method invocation is performed atomically, so the function is applied at
+ * most once per key. As the value may be looked up by alternative keys, those function
+ * invocations may be executed in parallel and will replace any existing mappings when completed.
+ */
+ V get(K key, Supplier<V> loader) {
+ var value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ var lock = locks.get(key);
+ lock.lock();
+ try {
+ value = getIfPresent(key);
+ if (value != null) {
+ return value;
+ }
+
+ value = loader.get();
+ if (value == null) {
+ return null;
+ }
+
+ put(value);
+ return value;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Associates the {@code value} with its keys, replacing the old value and keys if present. */
+ private void put(V value) {
+ putIfNewer(value, (oldValue, newValue) -> 1);
+ }
+
+ /**
+ * Associates the {@code newValue} with its keys if it is newer than the existing value according
+ * to the provided {@code comparator}. If the new value is added, the old value and its associated
+ * keys are replaced.
+ *
+ * @param newValue the new value to be added to the cache
+ * @param comparator a comparator to determine if the new value is newer than the existing value.
+ * The comparator must support `null` values in case no value exist in the cache prior to
+ * invocation.
+ */
+ private void putIfNewer(V newValue, Comparator<V> comparator) {
+ requireNonNull(newValue);
+ var index = buildIndex(newValue);
+ store
+ .asMap()
+ .compute(
+ index.iterator().next(),
+ (key, oldValue) -> {
+ if (comparator.compare(oldValue, newValue) > 0) {
+ if (oldValue != null) {
+ indexes
+ .keySet()
+ .removeAll(Sets.difference(indexes.get(index.iterator().next()), index));
+ }
+ for (var indexKey : index) {
+ indexes.put(indexKey, index);
+ }
+ return newValue;
+ } else {
+ return oldValue;
+ }
+ });
+ }
+
+ /** Discards any cached value and its keys. */
+ void invalidate(K key) {
+ var index = indexes.get(key);
+ if (index == null) {
+ return;
+ }
+
+ store
+ .asMap()
+ .computeIfPresent(
+ index.iterator().next(),
+ (k, v) -> {
+ indexes.remove(k);
Review Comment:
Ooh that one was nasty. You are right, the index for the secondary key was leaking. Which is ironical as the purpose of this PR was also to fix that very leak... I have added a test case and a fix for it.
To be clear, the IndexedCache still allows for race conditions internally. Like the following:
1. Get a value for id=1 and name=foo, miss
2. Enter the lock, fetch the value from the database
3. While in the `store.asMap().compute(...)` call, just after the line that added the index `name=foo <-> id=1` to the `indexes` data structure, and **before the call completes**:
4. Another caller get the value by `name=foo`, resolves to `id=1`
5. The second caller proceeds to trying to get the value from the cache, get `null`
6. Now the second caller has to wait for the `lock` to be released and try again
This is a benign race condition, though. But it illustrates that the visibility of some operations are visible becore the operations are completed. This makes the code hard to maintain. Although less hard than the current `EntityCache`...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035475655
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -255,104 +150,74 @@ public void setCacheMode(EntityCacheMode cacheMode) {
@Nonnull PolarisBaseEntity entityToValidate,
int entityMinVersion,
int entityGrantRecordsMinVersion) {
- long entityCatalogId = entityToValidate.getCatalogId();
long entityId = entityToValidate.getId();
- PolarisEntityType entityType = entityToValidate.getType();
- // first lookup the cache to find the existing cache entry
+ // First lookup the cache to find the existing cache entry
ResolvedPolarisEntity existingCacheEntry = this.getEntityById(entityId);
- // the caller's fetched entity may have come from a stale lookup byName; we should consider
- // the existingCacheEntry to be the older of the two for purposes of invalidation to make
- // sure when we replaceCacheEntry we're also removing the old name if it's no longer valid
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(entityToValidate);
- ResolvedPolarisEntity existingCacheEntryByName = this.getEntityByName(nameKey);
- if (existingCacheEntryByName != null
- && existingCacheEntry != null
- && isNewer(existingCacheEntry, existingCacheEntryByName)) {
- existingCacheEntry = existingCacheEntryByName;
+ // See if we need to load or refresh that entity
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date, nothing to do.
+ return existingCacheEntry;
}
- // the new one to be returned
- final ResolvedPolarisEntity newCacheEntry;
-
- // see if we need to load or refresh that entity
- if (existingCacheEntry == null
- || existingCacheEntry.getEntity().getEntityVersion() < entityMinVersion
- || existingCacheEntry.getEntity().getGrantRecordsVersion() < entityGrantRecordsMinVersion) {
+ // Either cache miss, dropped entity or stale entity. In either case, invalidate and reload it.
+ // Do the refresh in a critical section based on the entity ID to avoid race conditions.
+ Lock lock = this.locks.get(entityId);
+ try {
+ lock.lock();
+
+ // Lookup the cache again in case another thread has already invalidated it.
+ existingCacheEntry = this.getEntityById(entityId);
+
+ // See if the entity has been refreshed concurrently
+ if (existingCacheEntry != null
+ && existingCacheEntry.getEntity().getEntityVersion() >= entityMinVersion
+ && existingCacheEntry.getEntity().getGrantRecordsVersion()
+ >= entityGrantRecordsMinVersion) {
+ // Cache hit and cache entry is up to date now, exit
+ return existingCacheEntry;
+ }
- // the refreshed entity
- final ResolvedEntityResult refreshedCacheEntry;
+ // We are the first to act upon this entity id, invalidate it
+ this.cache.invalidate(new IdKey(entityId));
- // was not found in the cache?
- final PolarisBaseEntity entity;
- final List<PolarisGrantRecord> grantRecords;
- final int grantRecordsVersion;
- if (existingCacheEntry == null) {
- // try to load it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.loadResolvedEntityById(
- callContext, entityCatalogId, entityId, entityType);
- if (refreshedCacheEntry.isSuccess()) {
- entity = refreshedCacheEntry.getEntity();
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- return null;
- }
- } else {
- // refresh it
- refreshedCacheEntry =
- this.polarisMetaStoreManager.refreshResolvedEntity(
- callContext,
- existingCacheEntry.getEntity().getEntityVersion(),
- existingCacheEntry.getEntity().getGrantRecordsVersion(),
- entityType,
- entityCatalogId,
- entityId);
- if (refreshedCacheEntry.isSuccess()) {
- entity =
- (refreshedCacheEntry.getEntity() != null)
- ? refreshedCacheEntry.getEntity()
- : existingCacheEntry.getEntity();
- if (refreshedCacheEntry.getEntityGrantRecords() != null) {
- grantRecords = refreshedCacheEntry.getEntityGrantRecords();
- grantRecordsVersion = refreshedCacheEntry.getGrantRecordsVersion();
- } else {
- grantRecords = existingCacheEntry.getAllGrantRecords();
- grantRecordsVersion = existingCacheEntry.getEntity().getGrantRecordsVersion();
- }
- } else {
- // entity has been purged, remove it
- this.removeCacheEntry(existingCacheEntry);
- return null;
- }
+ // Get the entity from the cache or reload it now that it has been invalidated
+ EntityCacheLookupResult cacheLookupResult =
+ this.getOrLoadEntityById(
Review Comment:
I guess "write" means "invalidate"... yes, it makes sense :+1: Would you mind adding a bit on that to the comments? It was not apparent to me at first reading :facepalm: :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035467084
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java:
##########
@@ -18,185 +18,69 @@
*/
package org.apache.polaris.core.persistence.cache;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.google.common.util.concurrent.Striped;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
-import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
import org.apache.polaris.core.persistence.dao.entity.ResolvedEntityResult;
/** The entity cache, can be private or shared */
public class EntityCache {
+ private static final int STRIPES = 1_024;
// cache mode
private EntityCacheMode cacheMode;
// the meta store manager
private final PolarisMetaStoreManager polarisMetaStoreManager;
- // Caffeine cache to keep entries by id
- private final Cache<Long, ResolvedPolarisEntity> byId;
+ // Caffeine cache to keep entries
+ private final IndexedCache<CacheKey, ResolvedPolarisEntity> cache;
- // index by name
- private final AbstractMap<EntityCacheByNameKey, ResolvedPolarisEntity> byName;
+ // Locks to ensure that an entity can only be refreshed by one thread at a time
+ private final Striped<Lock> locks;
/**
* Constructor. Cache can be private or shared
*
* @param polarisMetaStoreManager the meta store manager implementation
*/
public EntityCache(@Nonnull PolarisMetaStoreManager polarisMetaStoreManager) {
-
- // by name cache
- this.byName = new ConcurrentHashMap<>();
-
- // When an entry is removed, we simply remove it from the byName map
- RemovalListener<Long, ResolvedPolarisEntity> removalListener =
- (key, value, cause) -> {
- if (value != null) {
- // compute name key
- EntityCacheByNameKey nameKey = new EntityCacheByNameKey(value.getEntity());
-
- // if it is still active, remove it from the name key
- this.byName.remove(nameKey, value);
- }
- };
-
- // use a Caffeine cache to purge entries when those have not been used for a long time.
- // Assuming 1KB per entry, 100K entries is about 100MB.
- this.byId =
- Caffeine.newBuilder()
- .maximumSize(100_000) // Set maximum size to 100,000 elements
- .expireAfterAccess(1, TimeUnit.HOURS) // Expire entries after 1 hour of no access
- .removalListener(removalListener) // Set the removal listener
- .build();
-
// remember the meta store manager
this.polarisMetaStoreManager = polarisMetaStoreManager;
// enabled by default
this.cacheMode = EntityCacheMode.ENABLE;
+
+ // Use a Caffeine cache to purge entries when those have not been used for a long time.
+ // Assuming 1KB per entry, 100K entries is about 100MB. Note that each entity is stored twice in
Review Comment:
TBH, I doubt the "1kB" assumption holds true. It might be a good estimate for "empty" entities, but given that users can add a good amount of arbitrary properties, I believe it's actually bigger. But this is a thing for a different issue/PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Entity cache with indexed cache [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #1339:
URL: https://github.com/apache/polaris/pull/1339#discussion_r2035481454
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/IndexedCache.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.persistence.cache;
Review Comment:
fair enough :+1:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-2982375115
This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EntityCache correctness issues and leak [polaris]
Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on PR #1339:
URL: https://github.com/apache/polaris/pull/1339#issuecomment-5153984012
@pingtimeout do we still need this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org