This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new aa5854a475 [#13989] fix(core): avoid retaining catalog context loaders
in isolated classloaders (#13990)
aa5854a475 is described below
commit aa5854a475437685e4c74e93dd060eeb80a53a08
Author: kamisama0002 <[email protected]>
AuthorDate: Wed Nov 11 18:05:04 2026 +0800
[#13989] fix(core): avoid retaining catalog context loaders in isolated
classloaders (#13990)
### What changes were proposed in this pull request?
Unwrap Gravitino's isolated context loaders to their shared base and use
that captured base as the new loader's parent. Preserve ordinary custom
context loaders and fall back to Gravitino's defining loader for a null
TCCL.
Add tests with a generated fixture JAR for nested loaders, closed
contexts, provider isolation, different pool keys, custom contexts and
null contexts.
### Why are the changes needed?
A new loader can retain another catalog loader as its base or parent.
After that catalog closes, the surviving loader may reuse its provider
class and fail when a method first resolves an unloaded dependency. This
reproduces with `OSSFileSystemProvider` and `AliyunOSSFileSystem`,
including when full pool cleanup runs.
Fix: #13989
### Does this PR introduce _any_ user-facing change?
Nested loaders can resolve their dependencies after the original context
owner closes. No API or configuration changes.
### How was this patch tested?
Tested on CentOS Stream 10, JDK 17.0.19 and Gradle 8.2:
```bash
./gradlew :core:coreUnitTest :core:jar :catalogs:catalog-common:test
:core:spotlessCheck -PskipITs --configure-on-demand
```
- Core: 2,453 passed, 2 existing disabled tests skipped, 0 failures.
Catalog common: 40 passed. Spotless and Error Prone passed.
- `TestIsolatedClassLoader`: 6 of 12 cases fail with the original
implementation; all 12 pass with this patch.
- Separate OSS reproduction with the built core JAR, real OSS provider
and Hadoop 3.3.6: 4 of 8 cases fail before the fix; all 8 pass after it.
This includes releasing a different pool key through full cleanup.
Synthetic credentials and a local endpoint are sufficient; no bucket
operations are performed.
Co-authored-by: Qi Yu <[email protected]>
---
.../gravitino/utils/IsolatedClassLoader.java | 16 +-
.../gravitino/utils/TestIsolatedClassLoader.java | 229 ++++++++++++++++++++-
2 files changed, 238 insertions(+), 7 deletions(-)
diff --git
a/core/src/main/java/org/apache/gravitino/utils/IsolatedClassLoader.java
b/core/src/main/java/org/apache/gravitino/utils/IsolatedClassLoader.java
index ef83295720..e7d06e016b 100644
--- a/core/src/main/java/org/apache/gravitino/utils/IsolatedClassLoader.java
+++ b/core/src/main/java/org/apache/gravitino/utils/IsolatedClassLoader.java
@@ -28,6 +28,7 @@ import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
@@ -68,7 +69,7 @@ public class IsolatedClassLoader implements Closeable {
this.execJars = execJars;
this.sharedClasses = sharedClasses;
this.barrierClasses = barrierClasses;
- this.baseClassLoader = Thread.currentThread().getContextClassLoader();
+ this.baseClassLoader =
getBaseClassLoader(Thread.currentThread().getContextClassLoader());
}
/**
@@ -253,12 +254,21 @@ public class IsolatedClassLoader implements Closeable {
return classLoader;
}
- ClassLoader parent = Thread.currentThread().getContextClassLoader();
this.classLoader =
- new CustomURLClassLoader(execJars.toArray(new URL[0]), parent,
baseClassLoader);
+ new CustomURLClassLoader(execJars.toArray(new URL[0]),
baseClassLoader, baseClassLoader);
return classLoader;
}
+ private static ClassLoader getBaseClassLoader(@Nullable ClassLoader
contextClassLoader) {
+ // Catalog loaders have independent lifecycles. Retaining one as a shared
base or parent
+ // would reuse its provider classes even after its JARs have been closed.
+ ClassLoader base = contextClassLoader;
+ while (base instanceof CustomURLClassLoader) {
+ base = ((CustomURLClassLoader) base).baseClassLoader;
+ }
+ return base == null ? IsolatedClassLoader.class.getClassLoader() : base;
+ }
+
/**
* Checks if a given class name belongs to a shared class.
*
diff --git
a/core/src/test/java/org/apache/gravitino/utils/TestIsolatedClassLoader.java
b/core/src/test/java/org/apache/gravitino/utils/TestIsolatedClassLoader.java
index 7dc55b1343..c5bd455f5a 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestIsolatedClassLoader.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestIsolatedClassLoader.java
@@ -19,17 +19,95 @@
package org.apache.gravitino.utils;
+import java.io.IOException;
import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Collections;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+/** Tests class isolation and shared-class visibility across
context-classloader changes. */
public class TestIsolatedClassLoader {
+ private static final String PROVIDER =
"org.apache.gravitino.oss.fixture.LazyProvider";
+ private static final String EXTERNAL_CLASS =
"org.example.classloader.ExternalClass";
+
+ @TempDir private static Path tempDir;
+
+ private static URL fixtureJar;
+
private IsolatedClassLoader classLoader;
private Method isCatalogClassMethod;
+ /** Builds classes outside the application classpath, including a lazily
resolved dependency. */
+ @BeforeAll
+ public static void createFixtureJar() throws IOException {
+ Path sources = Files.createDirectories(tempDir.resolve("sources"));
+ Path classes = Files.createDirectories(tempDir.resolve("classes"));
+ Path provider = sources.resolve("LazyProvider.java");
+ Path dependency = sources.resolve("LazyDependency.java");
+ Path external = sources.resolve("ExternalClass.java");
+ Files.write(
+ provider,
+ ("package org.apache.gravitino.oss.fixture;"
+ + "public class LazyProvider {"
+ + " public String value() { return LazyDependency.value(); }"
+ + "}")
+ .getBytes(StandardCharsets.UTF_8));
+ Files.write(
+ dependency,
+ ("package org.apache.gravitino.oss.fixture;"
+ + "public class LazyDependency {"
+ + " public static String value() { return \"loaded\"; }"
+ + "}")
+ .getBytes(StandardCharsets.UTF_8));
+ Files.write(
+ external,
+ ("package org.example.classloader;"
+ + "public class ExternalClass {"
+ + " public static String value() { return \"external\"; }"
+ + "}")
+ .getBytes(StandardCharsets.UTF_8));
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ Assertions.assertNotNull(compiler, "The classloader tests require a JDK");
+ Assertions.assertEquals(
+ 0,
+ compiler.run(
+ null,
+ null,
+ null,
+ "-proc:none",
+ "-d",
+ classes.toString(),
+ provider.toString(),
+ dependency.toString(),
+ external.toString()));
+ Path jarPath = tempDir.resolve("classloader-fixture.jar");
+ try (Stream<Path> files = Files.walk(classes);
+ JarOutputStream jar = new
JarOutputStream(Files.newOutputStream(jarPath))) {
+ for (Path file :
files.filter(Files::isRegularFile).collect(Collectors.toList())) {
+ jar.putNextEntry(new
JarEntry(classes.relativize(file).toString().replace('\\', '/')));
+ Files.copy(file, jar);
+ jar.closeEntry();
+ }
+ }
+ fixtureJar = jarPath.toUri().toURL();
+ }
+
@BeforeEach
public void setUp() throws Exception {
classLoader =
@@ -40,10 +118,6 @@ public class TestIsolatedClassLoader {
isCatalogClassMethod.setAccessible(true);
}
- private boolean isCatalogClass(String name) throws Exception {
- return (boolean) isCatalogClassMethod.invoke(classLoader, name);
- }
-
@Test
public void testClassNotFoundExceptionDoesNotWrapProbeMiss() {
// Probe-driven callers such as Janino expect a plain
ClassNotFoundException for misses
@@ -100,4 +174,151 @@ public class TestIsolatedClassLoader {
Assertions.assertFalse(isCatalogClass("java.lang.String"));
Assertions.assertFalse(isCatalogClass("org.slf4j.Logger"));
}
+
+ /** A nested loader must keep its cold dependencies loadable after the
context owner closes. */
+ @Test
+ public void testNestedLoaderSurvivesContextLoaderClose() throws Exception {
+ IsolatedClassLoader nested;
+ try (IsolatedClassLoader first = newFixtureLoader()) {
+ loadProvider(first);
+ nested = first.withClassLoader(ignored -> newFixtureLoader());
+ }
+ try (IsolatedClassLoader second = nested) {
+ Assertions.assertEquals("loaded", loadValue(second));
+ }
+ }
+
+ /** Independent isolated loaders must not reuse provider classes from an
open context owner. */
+ @Test
+ public void testNestedLoaderDoesNotReuseContextProvider() throws Exception {
+ try (IsolatedClassLoader first = newFixtureLoader()) {
+ Class<?> firstProvider = loadProvider(first);
+ try (IsolatedClassLoader second = first.withClassLoader(ignored ->
newFixtureLoader())) {
+ Class<?> secondProvider = first.withClassLoader(ignored ->
loadProvider(second));
+ Assertions.assertNotSame(firstProvider, secondProvider);
+ Assertions.assertEquals("loaded", loadValue(second));
+ }
+ }
+ }
+
+ /** A later context switch must not change the parent of a loader created on
a clean thread. */
+ @Test
+ public void testFirstUseIgnoresClosedContextLoader() throws Exception {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader closedContext;
+ try (IsolatedClassLoader first = newFixtureLoader()) {
+ closedContext = first.withClassLoader(cl ->
cl.loadClass(PROVIDER).getClassLoader());
+ }
+ try (IsolatedClassLoader second = newFixtureLoader()) {
+ Thread.currentThread().setContextClassLoader(closedContext);
+ Assertions.assertEquals("loaded", loadValue(second));
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ /** A thread still carrying a closed catalog loader must be able to
initialize another catalog. */
+ @Test
+ public void testConstructionIgnoresClosedContextLoader() throws Exception {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader closedContext;
+ try (IsolatedClassLoader first = newFixtureLoader()) {
+ closedContext = first.withClassLoader(cl ->
cl.loadClass(PROVIDER).getClassLoader());
+ }
+ try {
+ Thread.currentThread().setContextClassLoader(closedContext);
+ try (IsolatedClassLoader second = newFixtureLoader()) {
+ Assertions.assertEquals("loaded", loadValue(second));
+ }
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ /** Explicit noncatalog context loaders continue to supply their shared
application classes. */
+ @Test
+ public void testCustomContextLoaderRemainsVisible() throws Exception {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ try (URLClassLoader custom = new URLClassLoader(new URL[] {fixtureJar},
original)) {
+ Thread.currentThread().setContextClassLoader(custom);
+ try (IsolatedClassLoader isolated =
+ new IsolatedClassLoader(
+ Collections.emptyList(), Collections.emptyList(),
Collections.emptyList())) {
+ Thread.currentThread().setContextClassLoader(original);
+ Object value =
+ isolated.withClassLoader(
+ cl ->
cl.loadClass(EXTERNAL_CLASS).getMethod("value").invoke(null));
+ Assertions.assertEquals("external", value);
+ }
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ /** A context cleared during resource cleanup falls back to the Gravitino
application loader. */
+ @Test
+ public void testNullContextLoaderCanLoadSharedClasses() throws Exception {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ try {
+ Thread.currentThread().setContextClassLoader(null);
+ try (IsolatedClassLoader isolated = newFixtureLoader()) {
+ Assertions.assertSame(
+ ThrowableFunction.class,
+ isolated.withClassLoader(cl ->
cl.loadClass(ThrowableFunction.class.getName())));
+ }
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ /**
+ * Releasing a different pool key must not make the surviving entry's cold
classes unavailable.
+ */
+ @Test
+ public void testNestedPoolEntrySurvivesDifferentKeyRelease() throws
Exception {
+ try (ClassLoaderPool pool = new ClassLoaderPool()) {
+ PooledClassLoaderEntry first =
+ pool.acquire(
+ new ClassLoaderKey("fileset", Map.of("fs.defaultFS",
"file:///first")),
+ this::newFixtureLoader);
+ loadProvider(first.classLoader());
+ PooledClassLoaderEntry second =
+ first
+ .classLoader()
+ .withClassLoader(
+ ignored ->
+ pool.acquire(
+ new ClassLoaderKey("fileset", Map.of("fs.defaultFS",
"file:///second")),
+ this::newFixtureLoader));
+ pool.release(first);
+ try {
+ Assertions.assertEquals("loaded", loadValue(second.classLoader()));
+ } finally {
+ pool.release(second);
+ }
+ }
+ }
+
+ private boolean isCatalogClass(String name) throws Exception {
+ return (boolean) isCatalogClassMethod.invoke(classLoader, name);
+ }
+
+ private IsolatedClassLoader newFixtureLoader() {
+ return new IsolatedClassLoader(
+ Collections.singletonList(fixtureJar), Collections.emptyList(),
Collections.emptyList());
+ }
+
+ private Class<?> loadProvider(IsolatedClassLoader loader) throws Exception {
+ return loader.withClassLoader(cl -> cl.loadClass(PROVIDER));
+ }
+
+ private Object loadValue(IsolatedClassLoader loader) throws Exception {
+ return loader.withClassLoader(
+ cl -> {
+ Class<?> provider = cl.loadClass(PROVIDER);
+ return provider
+ .getMethod("value")
+ .invoke(provider.getDeclaredConstructor().newInstance());
+ });
+ }
}