Copilot commented on code in PR #12404: URL: https://github.com/apache/gravitino/pull/12404#discussion_r3748769958
########## core/src/main/java/org/apache/gravitino/catalog/CatalogLease.java: ########## @@ -0,0 +1,93 @@ +/* + * 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.gravitino.catalog; + +import com.google.common.base.Preconditions; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper; +import org.apache.gravitino.connector.BaseCatalog; + +/** + * A lease on a {@link CatalogWrapper} held for the duration of one catalog operation. + * + * <p>While the lease is held, the wrapper's catalog instance and its {@link + * org.apache.gravitino.utils.IsolatedClassLoader} stay alive even if the catalog cache evicts the + * wrapper concurrently (expiry, explicit invalidation, or remote change-log invalidation). The + * resources are released once the wrapper is retired and its last lease is closed, so an operation + * can never observe a half-closed catalog. + * + * <p>Leases are obtained from {@link CatalogManager#acquireCatalogLease(org.apache.gravitino + * .NameIdentifier)} and must be closed exactly once, ideally with try-with-resources: Review Comment: This Javadoc `{@link ...}` is split across a newline, which typically breaks the link rendering (and can fail stricter Javadoc checks). Keep the fully-qualified type on the same line, e.g. `CatalogManager#acquireCatalogLease(org.apache.gravitino.NameIdentifier)`. ########## core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java: ########## @@ -182,6 +208,74 @@ public BaseCatalog catalog() { return catalog; } Review Comment: `catalog()` reads `catalog` without synchronization/volatile, while `cleanup()` mutates `catalog` (and `poolEntry`) outside of `leaseLock`. This is a Java memory-model data race and can lead to visibility issues or observing partially-updated state across threads. A concrete fix is to either (a) make the mutated/read fields (`catalog`, and potentially `poolEntry`/`classLoader`) `volatile`, and/or (b) move the state-nullification (`catalog = null`, `poolEntry = null`, etc.) into a `synchronized (leaseLock)` block after closing resources so publication is properly ordered. ########## core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java: ########## @@ -0,0 +1,326 @@ +/* + * 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.gravitino.catalog; + +import static org.awaitility.Awaitility.await; + +import com.google.common.collect.ImmutableMap; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.gravitino.Catalog; +import org.apache.gravitino.Config; +import org.apache.gravitino.Configs; +import org.apache.gravitino.GravitinoEnv; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.Namespace; +import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper; +import org.apache.gravitino.lock.LockManager; +import org.apache.gravitino.meta.AuditInfo; +import org.apache.gravitino.meta.BaseMetalake; +import org.apache.gravitino.meta.SchemaVersion; +import org.apache.gravitino.secret.SecretManager; +import org.apache.gravitino.storage.RandomIdGenerator; +import org.apache.gravitino.storage.memory.TestMemoryEntityStore; +import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore; +import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord; +import org.apache.gravitino.storage.relational.po.cache.OperateType; +import org.apache.gravitino.utils.ClassLoaderPool; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that a catalog wrapper evicted from the catalog cache is not torn down while an operation + * is still using it. Cache eviction (expiry, explicit invalidation, remote change-log invalidation, + * and drop) must only retire the wrapper; the catalog and the ClassLoader are cleaned up when the + * last lease is released, exactly once. + */ +public class TestCatalogWrapperLease { + + private static final String METALAKE = "metalake"; + private static final String PROVIDER = "test"; + private static final Map<String, String> PROPS = + ImmutableMap.of("key1", "value1", "key2", "value2", "key5-1", "value3"); + + private static Config config; + private static InMemoryEntityStore entityStore; + + private CatalogManager catalogManager; + + private static final BaseMetalake METALAKE_ENTITY = + BaseMetalake.builder() + .withId(1L) + .withName(METALAKE) + .withAuditInfo( + AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build()) + .withVersion(SchemaVersion.V_0_1) + .build(); + + @BeforeAll + public static void setUp() throws IOException, IllegalAccessException { + config = new Config(false) {}; + config.set(Configs.CATALOG_LOAD_ISOLATED, false); + + entityStore = new TestMemoryEntityStore.InMemoryEntityStore(); + entityStore.initialize(config); + entityStore.put(METALAKE_ENTITY, true); + + FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true); + } + + @AfterAll + public static void tearDown() throws IOException { + if (entityStore != null) { + entityStore.close(); + entityStore = null; + } + } + + @BeforeEach + public void beforeEach() { + catalogManager = + new CatalogManager(config, entityStore, new RandomIdGenerator(), new SecretManager(config)); + } + + @AfterEach + public void afterEach() throws IOException { + if (catalogManager != null) { + catalogManager.close(); + catalogManager = null; + } + entityStore.clear(); + entityStore.put(METALAKE_ENTITY, true); + } + + @Test + public void testCacheInvalidationDefersCleanupUntilLeaseIsReleased() throws Exception { + NameIdentifier ident = createCatalog("invalidate_with_lease"); + + CatalogLease lease = catalogManager.acquireCatalogLease(ident); + CatalogWrapper wrapper = lease.wrapper(); + Assertions.assertEquals(1, wrapper.activeOperations()); + + catalogManager.getCatalogCache().invalidate(ident); + // Caffeine runs the removal listener asynchronously, so wait for the retirement to land. + await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired); + + Assertions.assertTrue(wrapper.isRetired(), "eviction must retire the wrapper"); + Assertions.assertNotNull( + wrapper.catalog(), "a leased wrapper must not be closed by cache eviction"); + // The leased wrapper is still fully usable: this is the operation that used to fail with an + // NPE (or NoClassDefFoundError) once the removal listener closed the wrapper underneath it. + Assertions.assertDoesNotThrow( + () -> + wrapper.doWithSchemaOps(ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name())))); + + lease.close(); + // Closing the same lease twice must not double-release the active-operation count. + lease.close(); + + Assertions.assertEquals(0, wrapper.activeOperations()); + Assertions.assertNull(wrapper.catalog(), "the last lease release must clean up the catalog"); + } + + @Test + public void testCacheExpiryDefersCleanupUntilLeaseIsReleased() throws Exception { + Config expiringConfig = new Config(false) {}; + expiringConfig.set(Configs.CATALOG_LOAD_ISOLATED, false); + expiringConfig.set(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS, 1L); + + CatalogManager expiringManager = + new CatalogManager( + expiringConfig, entityStore, new RandomIdGenerator(), new SecretManager(config)); Review Comment: `expiringManager` is constructed with `expiringConfig`, but `SecretManager` is initialized with `config` instead of `expiringConfig`. This can make the test depend on unrelated global configuration and diverge from the intended setup. Initialize `SecretManager` with the same config instance used for `CatalogManager` 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
