You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "LuciferYang (via GitHub)" <gi...@apache.org> on 2026/08/11 13:08:44 UTC

[PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

LuciferYang opened a new pull request, #12423:
URL: https://github.com/apache/gravitino/pull/12423

   ### What changes were proposed in this pull request?
   
   `CredentialFactory.create` called `ServiceLoader.load(Credential.class)` on every invocation and iterated/instantiated every registered `Credential` implementation just to resolve one type -> class mapping. This caches the scan once into an immutable `type -> class` map (initialization-on-demand holder idiom) and turns `lookupCredential` into a single map get.
   
   Lookup stays case-insensitive and still throws `No credential found for: <type>` (preserving the caller's original casing) on a miss; duplicate-type detection moves to cache-build time.
   
   ### Why are the changes needed?
   
   `Credential` is a fixed, built-in SPI (custom credentials are added via `CredentialProvider`, not by registering new `Credential` services), so the `ServiceLoader` result is stable for the JVM lifetime and does not need to be rescanned — nor all providers re-instantiated — on every lookup.
   
   A JMH micro-benchmark shows the type lookup dropping from **~380 µs/op to ~64 ns/op**:
   
   ```
   Benchmark                                  Mode  Cnt       Score       Error  Units
   CredentialLookupBenchmark.newCachedLookup  avgt    3      64.064 ±     8.449  ns/op
   CredentialLookupBenchmark.oldPerCallScan   avgt    3  380491.264 ± 35292.735  ns/op
   ```
   
   <details>
   <summary>Benchmark used (not part of this PR — drop under <code>core/src/jmh/java/org/apache/gravitino/credential/</code> and run <code>./gradlew :core:jmh</code>)</summary>
   
   `oldPerCallScan` replays the previous `ServiceLoader.load` + stream-filter per call; `newCachedLookup` does a single `get` on the pre-built map. Only the type-lookup step is measured; the shared `newInstance` of the resolved credential is excluded, since it is unchanged by this PR.
   
   ```java
   package org.apache.gravitino.credential;
   
   import java.util.HashMap;
   import java.util.List;
   import java.util.Locale;
   import java.util.Map;
   import java.util.ServiceLoader;
   import java.util.concurrent.TimeUnit;
   import java.util.stream.Collectors;
   import java.util.stream.StreamSupport;
   import org.openjdk.jmh.annotations.Benchmark;
   import org.openjdk.jmh.annotations.BenchmarkMode;
   import org.openjdk.jmh.annotations.Mode;
   import org.openjdk.jmh.annotations.OutputTimeUnit;
   import org.openjdk.jmh.annotations.Scope;
   import org.openjdk.jmh.annotations.Setup;
   import org.openjdk.jmh.annotations.State;
   import org.openjdk.jmh.infra.Blackhole;
   
   @State(Scope.Benchmark)
   @BenchmarkMode(Mode.AverageTime)
   @OutputTimeUnit(TimeUnit.NANOSECONDS)
   public class CredentialLookupBenchmark {
   
     private Map<String, Class<? extends Credential>> cachedClasses;
     private String[] types;
   
     @Setup
     public void setup() {
       cachedClasses = new HashMap<>();
       for (Credential credential : ServiceLoader.load(Credential.class)) {
         cachedClasses.put(
             credential.credentialType().toLowerCase(Locale.ROOT), credential.getClass());
       }
       types = cachedClasses.keySet().toArray(new String[0]);
     }
   
     @Benchmark
     public void oldPerCallScan(Blackhole bh) {
       for (String type : types) {
         bh.consume(oldLookup(type));
       }
     }
   
     @Benchmark
     public void newCachedLookup(Blackhole bh) {
       for (String type : types) {
         bh.consume(cachedClasses.get(type.toLowerCase(Locale.ROOT)));
       }
     }
   
     private static Class<? extends Credential> oldLookup(String credentialType) {
       ServiceLoader<Credential> serviceLoader = ServiceLoader.load(Credential.class);
       List<Class<? extends Credential>> credentials =
           StreamSupport.stream(serviceLoader.spliterator(), false)
               .filter(credential -> credentialType.equalsIgnoreCase(credential.credentialType()))
               .map(Credential::getClass)
               .collect(Collectors.toList());
       return credentials.get(0);
     }
   }
   ```
   </details>
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. Internal factory optimization; lookup semantics (case-insensitive resolution, `No credential found for: <type>` on miss) are unchanged.
   
   ### How was this patch tested?
   
   Existing `TestCredentialFactory` cases plus new ones for unknown-type rejection (including that the error message preserves the original casing) and case-insensitive lookup. `./gradlew :common:test --tests "org.apache.gravitino.credential.TestCredentialFactory"` and spotless pass.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5265952337

   > It seems that the ROI of letting more SPI use cache is not high, so the current state is acceptable to me. We can continue to optimize it if needed in the future.
   
   fine for me


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5262404388

   The failures are unrelated to this PR. Could you please re-trigger https://github.com/apache/gravitino/actions/runs/31494527605/job/93794656690?pr=12423 if you have a moment? Thanks @yuqi1129 


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 merged PR #12423:
URL: https://github.com/apache/gravitino/pull/12423


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5266464459

   Thank you @yuqi1129 


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5265862653

   Thanks! I went through all ~16 other `ServiceLoader.load` sites. Grouped by whether the same refinement fits:
   
   **Init-once already (per-call caching adds nothing)** — scanned once at construction, a guarded singleton init, or a one-shot CLI command, not on a per-request path:
   - `LakehouseTableDelegatorFactory` — guarded static holder, memoized.
   - `FileSystemUtils` / `BaseGVFSOperations` — loaded once into an `ImmutableMap` field at catalog-ops init / ctor.
   - `KmsClientRegistry` — constructed once from the `GravitinoEnv` singleton.
   - `SqlSessionFactoryHelper` — double-checked `init()`, baked into the singleton `SqlSessionFactory`.
   - `WebIdentityTokenSources` — loaded once in the credential generator's `initialize`.
   - optimizer `ProviderUtils` / `InstanceLoaderUtils` — resolved in optimizer object ctors / short-lived CLI commands.
   
   **Per-classloader by design (a static type→impl cache would be *wrong*)** — they pass an isolated or thread-context classloader so different catalogs/plugins resolve different impls: `CatalogManager`, `BaseAuthorization`, `AuxiliaryServiceManager`, `CredentialProviderFactory` (resolves against the catalog's isolated CL that `IsolatedClassLoader.withClassLoader` installs), Trino's `GravitinoConnectorPluginManager` (fresh per-plugin `PluginClassLoader`), and `BuiltInJobTemplateEventListener` (a throwaway `URLClassLoader` that's *closed* right after — caching across it would be actively unsafe). A global cache would bind whichever impl loaded first.
   
   **The one genuine analog:** `GravitinoCatalogStore` (flink-connector) re-scans the Flink `Factory` SPI on every `storeCatalog`/`getCatalog`, no cache. It's cacheable, but it uses single-arg `ServiceLoader.load(Factory.class)` (thread-context CL, which Flink may swap to a user-code CL), so it'd want a per-classloader cache rather than a plain static map — and the win is smaller than the per-request credential path. Happy to do it as a separate follow-up if you think it's worth it.
   


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5255167703

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.4%|:green_circle:|
   |:-|:-|:-:|
   |Files changed|77.27%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|1.72%|:red_circle:|
   |api|49.31%|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |aws|42.04%|:green_circle:|
   |azure|2.47%|:red_circle:|
   |catalog-common|9.92%|:red_circle:|
   |catalog-fileset|79.77%|:green_circle:|
   |catalog-glue|68.95%|:green_circle:|
   |catalog-hive|79.4%|:green_circle:|
   |catalog-jdbc-common|45.7%|:green_circle:|
   |catalog-jdbc-doris|81.8%|:green_circle:|
   |catalog-jdbc-mysql|79.33%|:green_circle:|
   |catalog-jdbc-postgresql|83.39%|:green_circle:|
   |catalog-jdbc-starrocks|79.16%|:green_circle:|
   |catalog-kafka|77.01%|:green_circle:|
   |catalog-lakehouse-generic|59.18%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.93%|:green_circle:|
   |catalog-lakehouse-paimon|84.23%|:green_circle:|
   |catalog-model|77.72%|:green_circle:|
   |cli|44.48%|:green_circle:|
   |client-java|78.28%|:green_circle:|
   |common|52.8% **`+0.08%`**|:green_circle:|
   |core|83.34%|:green_circle:|
   |filesystem-hadoop3|77.28%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|48.68%|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|14.12%|:red_circle:|
   |hadoop-auth|68.0%|:green_circle:|
   |hadoop-common|12.7%|:red_circle:|
   |hive-metastore-common|53.4%|:green_circle:|
   |iceberg-aliyun-bundle|0.0%|:red_circle:|
   |iceberg-common|64.75%|:green_circle:|
   |iceberg-rest-server|75.03%|:green_circle:|
   |idp-basic|86.02%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|62.92%|:green_circle:|
   |lance-common|31.75%|:red_circle:|
   |lance-rest-server|63.47%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.17%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|85.76%|:green_circle:|
   |server-common|76.69%|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|45.89%|:green_circle:|
   |tencent|69.84%|:green_circle:|
   |trino-connector|40.29%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |common|[CredentialFactory.java](https://github.com/LuciferYang/gravitino/blob/645a3aed1d73b2467b309c4641df685bee333e47/common/src/main/java/org/apache/gravitino/credential/CredentialFactory.java)|77.27%|:green_circle:|
   
   </details>


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5263249018

   > A nice improvement. By the way, could you check if a similar refinement can be applied to other SPIs? I noticed that this mechanism is repeated several times in Gravititino.
   
   Good suggestion, let me check it.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5263220954

   A nice improvement. By the way,  could you check if a similar refinement can be applied to other SPIs? I noticed that this mechanism is repeated several times in Gravititino.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [MINOR] improvement(common): cache Credential ServiceLoader lookup in CredentialFactory [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #12423:
URL: https://github.com/apache/gravitino/pull/12423#issuecomment-5265925323

   > Thanks! I went through all ~16 other `ServiceLoader.load` sites. Grouped by whether the same refinement fits:
   > 
   > **Init-once already (per-call caching adds nothing)** — scanned once at construction, a guarded singleton init, or a one-shot CLI command, not on a per-request path:
   > 
   > * `LakehouseTableDelegatorFactory` — guarded static holder, memoized.
   > * `FileSystemUtils` / `BaseGVFSOperations` — loaded once into an `ImmutableMap` field at catalog-ops init / ctor.
   > * `KmsClientRegistry` — constructed once from the `GravitinoEnv` singleton.
   > * `SqlSessionFactoryHelper` — double-checked `init()`, baked into the singleton `SqlSessionFactory`.
   > * `WebIdentityTokenSources` — loaded once in the credential generator's `initialize`.
   > * optimizer `ProviderUtils` / `InstanceLoaderUtils` — resolved in optimizer object ctors / short-lived CLI commands.
   > 
   > **Per-classloader by design (a static type→impl cache would be _wrong_)** — they pass an isolated or thread-context classloader so different catalogs/plugins resolve different impls: `CatalogManager`, `BaseAuthorization`, `AuxiliaryServiceManager`, `CredentialProviderFactory` (resolves against the catalog's isolated CL that `IsolatedClassLoader.withClassLoader` installs), Trino's `GravitinoConnectorPluginManager` (fresh per-plugin `PluginClassLoader`), and `BuiltInJobTemplateEventListener` (a throwaway `URLClassLoader` that's _closed_ right after — caching across it would be actively unsafe). A global cache would bind whichever impl loaded first.
   > 
   > **The one genuine analog:** `GravitinoCatalogStore` (flink-connector) re-scans the Flink `Factory` SPI on every `storeCatalog`/`getCatalog`, no cache. It's cacheable, but it uses single-arg `ServiceLoader.load(Factory.class)` (thread-context CL, which Flink may swap to a user-code CL), so it'd want a per-classloader cache rather than a plain static map — and the win is smaller than the per-request credential path. Happy to do it as a separate follow-up if you think it's worth it.
   
   It seems that the ROI of letting more SPI use cache is not high, so the current state is acceptable to me.  We can continue to optimize it if needed in the future.  


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org