github-actions[bot] commented on code in PR #66633: URL: https://github.com/apache/doris/pull/66633#discussion_r3755233047
########## fe/fe-connector/fe-connector-cache/src/main/java/org/apache/doris/connector/cache/ScopedMetaCache.java: ########## @@ -0,0 +1,1134 @@ +// 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.doris.connector.cache; + +import org.apache.doris.connector.cache.ScopedMetaCacheRegistry.CacheAddress; +import org.apache.doris.connector.cache.ScopedMetaCacheRegistry.PublicationState; +import org.apache.doris.connector.cache.ScopedMetaCacheRegistry.ScopeLease; +import org.apache.doris.connector.cache.ScopedMetaCacheRegistry.ScopeSnapshot; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.RemovalCause; +import com.github.benmanes.caffeine.cache.RemovalListener; +import com.github.benmanes.caffeine.cache.Ticker; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.math.BigInteger; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashMap; +import java.util.Map; +import java.util.NavigableMap; +import java.util.Objects; +import java.util.OptionalLong; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.LongAdder; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * One physical Caffeine cache participating in a {@link ScopedMetaCacheRegistry}. + * + * <p>Every value is wrapped with both its hierarchical scope-state identities and an exact-key state. Hierarchical + * invalidation can therefore detach a whole catalog/database/table/partition subtree, while exact-key invalidation + * fences only one physical cache key. Removal listeners conditionally remove the exact wrapper from its original + * scope bucket and key node, so delayed callbacks cannot delete a replacement. + */ +public final class ScopedMetaCache<K, V> implements AutoCloseable { + private static final Logger LOG = LogManager.getLogger(ScopedMetaCache.class); + private static final Runnable NO_OP = () -> { + }; + + private final ScopedMetaCacheRegistry registry; + private final String name; + private final boolean effectiveEnabled; + private final Cache<K, VersionedValue<K, V>> data; + private final ConcurrentMap<K, KeyNode<K, V>> keyNodes = new ConcurrentHashMap<>(); + private final ConcurrentMap<LoadAddress<K>, CompletableFuture<V>> inFlightLoads = new ConcurrentHashMap<>(); + private final ConcurrentMap<K, VersionedValue<K, V>> refreshing = new ConcurrentHashMap<>(); + private final StripedPhaseGate bulkInvalidationGate = new StripedPhaseGate(); + private final Map<K, BigInteger> exactInvalidations = new HashMap<>(); + private final NavigableMap<BigInteger, Integer> activeBulkStarts = new TreeMap<>(); + private final AtomicBoolean closed = new AtomicBoolean(false); + private final LongAdder requestCount = new LongAdder(); + private final LongAdder hitCount = new LongAdder(); + private final LongAdder missCount = new LongAdder(); + private final LongAdder loadSuccessCount = new LongAdder(); + private final LongAdder loadFailureCount = new LongAdder(); + private final LongAdder totalLoadTimeNanos = new LongAdder(); + private final LongAdder evictionCount = new LongAdder(); + private final LongAdder invalidateCount = new LongAdder(); + private final AtomicReference<Long> lastLoadSuccessTimeMs = new AtomicReference<>(-1L); + private final AtomicReference<Long> lastLoadFailureTimeMs = new AtomicReference<>(-1L); + private final AtomicReference<String> lastError = new AtomicReference<>(""); + private final RemovalListener<K, V> beforeRemoval; + private final Ticker ticker; + private final long refreshAfterWriteNanos; + private final Executor refreshExecutor; + private final Runnable afterLoadElection; + private final Runnable afterBulkStage; + private final Runnable afterRefreshRegistration; + private final ThreadLocal<RemovalDeferral<K, V>> removalDeferrals = + ThreadLocal.withInitial(RemovalDeferral::new); + private BigInteger exactInvalidationSequence = BigInteger.ZERO; + + ScopedMetaCache( + ScopedMetaCacheRegistry registry, + String name, + CacheSpec cacheSpec, + Ticker ticker, + RemovalListener<K, V> beforeRemoval, + Duration refreshAfterWrite, + Executor refreshExecutor, + Runnable afterLoadElection, + Runnable afterBulkStage, + Runnable afterRefreshRegistration) { + this.registry = Objects.requireNonNull(registry, "registry can not be null"); + this.name = Objects.requireNonNull(name, "name can not be null"); + Objects.requireNonNull(cacheSpec, "cacheSpec can not be null"); + this.beforeRemoval = beforeRemoval; + this.ticker = ticker == null ? Ticker.systemTicker() : ticker; + this.refreshAfterWriteNanos = refreshAfterWrite == null ? 0L : refreshAfterWrite.toNanos(); + this.refreshExecutor = refreshExecutor; + this.afterLoadElection = + Objects.requireNonNull(afterLoadElection, "afterLoadElection can not be null"); + this.afterBulkStage = Objects.requireNonNull(afterBulkStage, "afterBulkStage can not be null"); + this.afterRefreshRegistration = Objects.requireNonNull( + afterRefreshRegistration, "afterRefreshRegistration can not be null"); + this.effectiveEnabled = CacheSpec.isCacheEnabled( + cacheSpec.isEnable(), cacheSpec.getTtlSecond(), cacheSpec.getCapacity()); + + Caffeine<Object, Object> builder = Caffeine.newBuilder() + .maximumSize(effectiveEnabled ? cacheSpec.getCapacity() : 0L) + .executor(Runnable::run) + .removalListener(this::onRemoval); + OptionalLong expiry = effectiveEnabled + ? CacheSpec.toExpireAfterAccess(cacheSpec.getTtlSecond()) + : OptionalLong.empty(); + if (expiry.isPresent()) { + builder.expireAfterAccess(Duration.ofSeconds(expiry.getAsLong())); + } + if (ticker != null) { + builder.ticker(this.ticker); + } + this.data = builder.build(); + } + + public String name() { + return name; + } + + public V get(K key, ScopePath path, Function<K, V> loader) { + return getWithPublicationAction(key, path, loader, + (loaded, commit) -> commit.accept(NO_OP)); + } + + public V getWithPublicationAction(K key, ScopePath path, Function<K, V> loader, + BiConsumer<V, Consumer<Runnable>> publicationCoordinator) { + Objects.requireNonNull(key, "key can not be null"); + Objects.requireNonNull(path, "path can not be null"); + Function<K, V> loadFunction = Objects.requireNonNull(loader, "loader can not be null"); + BiConsumer<V, Consumer<Runnable>> coordinator = Objects.requireNonNull( + publicationCoordinator, "publicationCoordinator can not be null"); + checkOpen(); + if (!effectiveEnabled) { + recordAccess(false); + V loaded = loadAndRecord(key, loadFunction); + if (loaded != null) { + AtomicBoolean commitInvoked = new AtomicBoolean(false); + coordinator.accept(loaded, beforePublication -> { + if (!commitInvoked.compareAndSet(false, true)) { + throw new IllegalStateException("Metadata cache publication callback was invoked twice"); + } + Objects.requireNonNull(beforePublication, "beforePublication can not be null").run(); + }); + if (!commitInvoked.get()) { + throw new IllegalStateException("Metadata cache publication callback was not invoked"); + } + } + return loaded; + } + + VersionedValue<K, V> presentVersioned = currentVersionedValue(key, path); + if (presentVersioned != null) { + recordAccess(true); + scheduleRefresh(key, path, loader, presentVersioned); + return presentVersioned.value; + } + recordAccess(false); + try (PublicationLease<K, V> lease = acquirePublicationLease(key, path, true)) { + LoadAddress<K> loadAddress = new LoadAddress<>(key, path, lease); + CompletableFuture<V> ownLoad = new CompletableFuture<>(); + CompletableFuture<V> existingLoad = inFlightLoads.putIfAbsent(loadAddress, ownLoad); + if (existingLoad != null) { + return awaitLoad(existingLoad); + } + try { + afterLoadElection.run(); + synchronized (lease.keyNode) { + VersionedValue<K, V> present = currentVersionedValue(key, path); + if (present != null) { + ownLoad.complete(present.value); + return present.value; + } + } + V loaded = loadAndRecord(key, loadFunction); + if (loaded != null) { + AtomicBoolean commitInvoked = new AtomicBoolean(false); + coordinator.accept(loaded, beforePublication -> { + if (!commitInvoked.compareAndSet(false, true)) { + throw new IllegalStateException("Metadata cache publication callback was invoked twice"); + } + commitLoaded(lease, key, loaded, beforePublication); + }); + if (!commitInvoked.get()) { + throw new IllegalStateException("Metadata cache publication callback was not invoked"); + } + } + ownLoad.complete(loaded); + return loaded; + } catch (RuntimeException | Error throwable) { + ownLoad.completeExceptionally(throwable); + throw throwable; + } finally { + inFlightLoads.remove(loadAddress, ownLoad); + } + } + } + + public V getIfPresent(K key, ScopePath path) { + Objects.requireNonNull(key, "key can not be null"); + Objects.requireNonNull(path, "path can not be null"); + checkOpen(); + if (!effectiveEnabled) { + recordAccess(false); + return null; + } + VersionedValue<K, V> versioned = currentVersionedValue(key, path); + recordAccess(versioned != null); + return versioned == null ? null : versioned.value; + } + + private VersionedValue<K, V> currentVersionedValue(K key, ScopePath path) { + VersionedValue<K, V> versioned = data.getIfPresent(key); + if (versioned == null) { + return null; + } + if (!versioned.scopeSnapshot.path().equals(path)) { + return null; + } + if (!versioned.isCurrent(registry, keyNodes)) { + data.asMap().remove(key, versioned); + return null; + } + return versioned; + } + + public void put(K key, ScopePath path, V value) { + Objects.requireNonNull(key, "key can not be null"); + Objects.requireNonNull(path, "path can not be null"); + Objects.requireNonNull(value, "value can not be null"); + checkOpen(); + if (!effectiveEnabled) { + return; + } + try (PublicationLease<K, V> lease = acquirePublicationLease(key, path, false)) { + synchronized (lease.keyNode) { + lease.keyNode.loadPublicationState.set(new Object()); + publishCommitted(lease, key, value); + } + } + } + + public boolean compareAndSet(K key, ScopePath path, V expectedValue, V updatedValue) { + Objects.requireNonNull(key, "key can not be null"); + Objects.requireNonNull(path, "path can not be null"); + checkOpen(); + if (!effectiveEnabled) { + return true; + } + try (PublicationLease<K, V> lease = acquirePublicationLease(key, path, false)) { + return guardedCommit(lease, () -> { + VersionedValue<K, V> current = currentVersionedValue(key, path); + V currentValue = current == null ? null : current.value; + if (currentValue != expectedValue) { + return false; + } + lease.keyNode.loadPublicationState.set(new Object()); + if (updatedValue == null) { + if (current != null) { + data.asMap().remove(key, current); + lease.keyNode.registration.compareAndSet(current, null); + } + } else { + publishCommitted(lease, key, updatedValue); Review Comment: [P2] Avoid removing an identity-preserving CAS value A retry from `FeMetaCacheEntry.computeAfterValidation` can reach this branch with `updatedValue == currentValue`. In the production database-register path, a names refresh can win the outer CAS after its first nested database update; the retry then republishes that same `ExternalDatabase`. Creating a new wrapper here makes Caffeine synchronously report the old wrapper as `REPLACED`, so the catalog removal listener calls `resetMetaToUninitialized()` on the exact object that the new wrapper still exposes. A lookup that initialized it between attempts loses its table caches/ID index and triggers downstream database invalidation. Please treat identity-preserving CAS as a no-op after advancing the load-publication fence, and add an outer-retry test with the synchronous removal listener. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
