Skip to content

fix(skills): discover resources in executable JAR classpaths - #1896

Open
zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/skills-boot-classpath
Open

zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/skills-boot-classpath

Conversation

@zhangxiangnan

@zhangxiangnan zhangxiangnan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #1895.

ClassPathSkillSource finds no skills in a Spring Boot executable JAR even when its classloader can read them: Guava scans file: entries but skips Boot's jar: roots. Ordinary JDK jar:file:...!/ roots reproduce the failure.

Change

Supplement Guava discovery with JarURLConnection enumeration. Resource reads remain lazy and enumeration handles are closed. No new dependency or Spring-specific runtime code is introduced.

The implementation preserves three behaviors:

  • Failure isolation: skip network-backed and unreadable roots without hiding valid resources; reuse root connections and preserve #runtime.
  • Override/conflict semantics: deduplicate names within each loader, retain conflicts across distinct loader-owned roots and _/- skill names, and return distinct resource paths.
  • Archive identity: scan equivalent roots once, normalize root aliases, and mark a root scanned only after opening succeeds.

The main compatibility helper, fileClassPath, reconciles the native resources with the added JAR scan. It includes system classpaths, directories, and local Manifest dependencies because Guava already scans them. It preserves parent-first ownership and symlink-relative Manifest resolution so mixed roots do not introduce false conflicts or hide existing ones. This reconciliation is skipped when Guava found no matching native resources.

Guava's public ResourceInfo API does not expose the discovering loader or physical source file; url() performs a fresh loader lookup and may resolve an overriding resource instead. Separate per-loader or per-root scans also change the global explicit-path reservations used during Manifest traversal, so they cannot reliably reconstruct the original ownership. The helper therefore reconciles this metadata explicitly, without relying on Guava internals.

Both constructors, the AbstractSkillSource<ResourceInfo> superclass, and protected signatures remain unchanged. Protected methods retain Guava-only discovery; public operations use supplemented discovery and share parsing logic.

Validation

Single commit def242214; changes are confined to ClassPathSkillSource and its existing test class.

  • Full core: ./mvnw -o -Daether.syncContext.named.factory=noop -f core/pom.xml test — passed. Main suite: 4,236 tests, 0 failures/errors, 35 skips. Repeated default/basic executions are not counted twice. All configured variants passed; the Apigee variant has one skip.
  • SkillSource tests: 89 passed on Java 17 and 21: ClassPath 56, Local 22, InMemory 11. Coverage includes both review rounds and mixed-root/Manifest/alias regressions.
  • Integration: the ClassPathSkillSource discovers no skills in Spring Boot executable JARs #1895 fixture passed on the ordinary classpath and as a Spring Boot 4.0.2 executable JAR, covering discovery, instructions, resource listing/reads, and repeated source creation.
  • Google Java Format 1.27.0 and git diff --check passed.

Other Boot versions, vfs:/wsjar: containers, and arbitrary custom non-URL classloaders are outside the verified scope. Java 25 was not run locally; the SecurityManager regression is skipped on Java 24+.

@zhangxiangnan
zhangxiangnan marked this pull request as draft November 23, 2026 13:20
@zhangxiangnan
zhangxiangnan force-pushed the fix/skills-boot-classpath branch from 9ab18ae to 0f3d4e3 Compare November 23, 2026 13:41
@zhangxiangnan
zhangxiangnan marked this pull request as ready for review November 23, 2026 13:41
@zhangxiangnan
zhangxiangnan force-pushed the fix/skills-boot-classpath branch 2 times, most recently from c891ae8 to 8c0f4a9 Compare November 25, 2026 02:48
@hemasekhar-p hemasekhar-p self-assigned this Nov 25, 2026
@hemasekhar-p

Copy link
Copy Markdown
Contributor

Hi @zhangxiangnan, Thank you for your contribution and for taking the time to submit this pull request. Our team is currently reviewing your changes and we will reach out if we need any further information.

@kvmilos kvmilos left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix and the thorough tests. There are two issues to fix before we merge (details inline): an unreadable or remote jar: URL on the class loader now breaks valid file: roots, and multi-release jar: URLs with #runtime fail to parse. I also left a few test and cleanup notes inline.

(JarURLConnection)
new URL(url, "jar:" + connection.getJarFileURL() + "!/").openConnection();
connection.setUseCaches(false);
try (JarFile jar = connection.getJarFile()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the URLClassLoader (or a parent loader) has a missing, corrupt, non-JAR, or remote (jar:http(s)://...!/) jar: URL next to valid file: roots, connection.getJarFile() now throws (or downloads the remote JAR over the network). That aborts scanJarUrls, wraps into SkillSourceException (lines 196-199), and gets permanently cached by .cache() (line 103), breaking all public SkillSource calls even for file: roots that used to work. Guava's ClassPath ignores non-file: URLs and skips missing or non-JAR entries.

Please skip network inner protocols (http, https, ftp) and catch IOException per URL inside the loop so one bad root doesn't break the rest.

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in def242214. Network-backed inner protocols are rejected before opening handlers, and each JAR URL isolates IOException and SecurityException. Regressions cover a missing JAR beside a valid file root, a remote handler that must not be opened, and readable resources alongside roots denied by a security policy.

Comment on lines +240 to +242
connection =
(JarURLConnection)
new URL(url, "jar:" + connection.getJarFileURL() + "!/").openConnection();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multi-release jar: URLs with a #runtime fragment (like jar:file:/app.jar!/#runtime or jar:file:/app.jar!/BOOT-INF/classes/#runtime) fail here with MalformedURLException: no !/ in spec. OpenJDK's JarURLConnection#getJarFileURL() appends #runtime, so "jar:" + connection.getJarFileURL() + "!/" puts # before !/ and turns !/ into part of the fragment.

Also, when root.isEmpty() (the common case for BOOT-INF/lib/*.jar), connection already points at the archive root and doesn't need to be reopened. Could you reuse connection when root.isEmpty(), and otherwise slice url.getFile() through the last "!/" and re-append "#" + ref if present?

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retained in def242214: empty roots reuse their original JarURLConnection; subdirectory roots slice the original URL through the last !/ and restore the fragment. The BOOT-INF/classes/#runtime regression still passes. Additional dot-segment normalization preserves the original URL handler and fragment.

Comment on lines +193 to +201
Set<String> jarNames = new LinkedHashSet<>();
try {
scanJarUrls(baseResourcePath, classLoader, jarNames);
} catch (IOException e) {
throw new SkillSourceException(
"Failed to scan classpath under " + baseResourcePath, SKILL_LOAD_ERROR, e);
}
jarNames.removeAll(nativeNames);
for (String name : jarNames) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When parent and child jar: roots contain the same SKILL.md path, jarNames deduplicates it and silently picks the parent. With file: roots, the same layout throws "Conflicting SKILL.md" (as tested in retainsNativeDuplicateNameConflictsAcrossLoaders). Could both root types handle duplicates the same way, or could you add a brief comment explaining why they differ?

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 52a5884. Distinct JAR roots now preserve duplicate resource names, so they report the same Conflicting SKILL.md error as file roots. Exact duplicate classpath roots and the same archive exposed as both file: and root-level jar: are scanned only once. Added regression tests for all three cases.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using an ArrayList for jarNames without per-loader deduplication breaks same-loader overrides. If two jar: roots in the same URLClassLoader (e.g., BOOT-INF/classes/ overriding BOOT-INF/lib/dep.jar) share a skill or resource name, listFrontmatters() now throws Conflicting SKILL.md and listResources() returns duplicate paths.

For file: roots, Guava's ClassPath.from deduplicates by (resourceName, loader) in an ImmutableSet, so same-loader overrides work while cross-loader duplicates still conflict. Could you deduplicate discovered names per ClassLoader in scanJarUrls (keeping cross-loader and a_b/a-b conflicts) and add .distinct() in ResourceSource.listResources?

@zhangxiangnan zhangxiangnan Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in def242214. Names are deduplicated per discovering ClassLoader (HashSet membership; URL/enumeration order still determines the first resource), including mixed file/JAR roots. Distinct-loader and _/- conflicts remain errors, and listResources retains .distinct(). Added regressions for mixed-root ordering and Manifest dependencies whose ownership changes when a child declares an explicit root; ownership is now recorded across the complete hierarchy rather than inferred from separate parent scans.

Comment on lines +56 to +58
* <p>The protected {@link ResourceInfo}-based methods retain the original Guava discovery behavior.
* The public {@link SkillSource} methods additionally discover JAR roots, including executable JARs
* whose URL handlers implement {@link JarURLConnection}.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: ClassPathSkillSource is final, so external callers can't use the protected ResourceInfo methods. I'd drop this second paragraph from the public Javadoc and keep just the first sentence.

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retained in def242214: the public class Javadoc contains only the concise loading description. The paragraph about protected methods remains removed.

}

// =========================================================================
// Packaged Resources & ClassLoader Compatibility

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add unit tests for the uncovered branches in ClassPathSkillSource?

  • A missing or unreadable jar: URL alongside a valid file: root (with the fix above)
  • A multi-release jar: URL with #runtime
  • A non-URLClassLoader child delegating to a jar:-backed URLClassLoader parent (continue at line 225)
  • getResourceAsStream returning null for a JAR-discovered resource (lines 210-212)
  • A jar: URL whose handler returns a non-JarURLConnection (line 232; doesNotOpenUnsupportedProtocolRoots uses "custom:", which returns at line 229)
  • A jar: subdirectory root without a trailing slash (lines 236-238)

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All six requested branches remain covered in ClassPathSkillSourceTest on def242214: unreadable JAR beside a valid file root, subdirectory #runtime, non-URL child delegation, null resource stream, a jar: handler returning a non-JarURLConnection, and a subdirectory root without a trailing slash. The final class has 56 tests; all pass locally on Java 17 and 21.

// =========================================================================

@Test
public void ordinaryJarWithoutDirectoryEntries() throws Exception {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: existing tests in this file use testMethod_condition naming (e.g., testLoadResource_notFound). Could you match that style for the new tests?

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retained in def242214: all added tests use the existing testMethod_condition naming convention and remain in ClassPathSkillSourceTest.

Comment on lines +333 to +334
assertThrows(
RuntimeException.class, () -> source.findSkillMdPath("conflicting-skill").blockingGet());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assertThrows(RuntimeException.class, ...) doesn't check the cause, error code, or message, so an unrelated RuntimeException (or SKILL_NOT_FOUND) would still pass. Please assert SkillSourceException with SKILL_LOAD_ERROR and "Conflicting SKILL.md" on both assertions (or use RxJava's .test().assertError(...)).

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retained in def242214: conflict assertions verify a SkillSourceException cause, SKILL_LOAD_ERROR, and the Conflicting SKILL.md message through assertSkillLoadError, so unrelated runtime failures or missing-skill errors do not satisfy the regression.

}

private static URL jarRoot(Path jar, String prefix) throws IOException {
return new URL("jar:" + jar.toUri().toURL() + "!/" + prefix);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: new URL(String) is deprecated since Java 20. Because jarRoot doesn't need a custom URLStreamHandler, URI.create("jar:" + jar.toUri() + "!/" + prefix).toURL() avoids deprecation warnings across Java 17, 21, and 25.

@zhangxiangnan zhangxiangnan Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retained in def242214: the jarRoot fixture uses URI.create(...).toURL(). Context-based URL constructors in production preserve the supplied URL handler when reconstructing or resolving JAR roots.

@kvmilos kvmilos added the waiting on author Awaiting response from author. Failing that, maintainers will eventually closed it as stale. label Nov 30, 2026
@zhangxiangnan

zhangxiangnan commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. I addressed all requested changes in 52a5884, including per-URL failure isolation, pre-open network protocol filtering, #runtime URL reconstruction, consistent duplicate handling, and the requested test coverage. The updated ClassPathSkillSourceTest passes all 36 tests.

@zhangxiangnan
zhangxiangnan force-pushed the fix/skills-boot-classpath branch 2 times, most recently from fca89c4 to 52a5884 Compare December 1, 2026 02:47
@zhangxiangnan

Copy link
Copy Markdown
Contributor Author

Hi @kvmilos, all requested changes have been addressed in the latest single commit, and each review thread has an implementation note. The targeted ClassPathSkillSourceTest suite passes all 36 tests. When you have a chance, could you please take another look? Thanks.

@kvmilos kvmilos left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates. The unreadable/remote jar: handling, #runtime fix, test naming, and extra branch tests all look good.

The duplicate-handling rewrite still has a few edge cases to fix before merging (details on the existing duplicate thread and inline below).

Also, could you update three stale statements in the PR description?

  • supplementJarResources no longer skips native names (testScan_differentFileAndJarRootsWithSameResourceConflict asserts a conflict).
  • Drop "This boundary is documented on the class", since that Javadoc paragraph was removed.
  • The diff adds 20 tests (36 total), not 11 (27 total).

}
// A root-level file: URL is already covered by Guava. Subdirectory roots remain
// distinct because they remap archive entries to different classpath resource names.
if (root.isEmpty() && fileRoots.contains(withoutFragment(jarFileUrl))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If Guava already scanned a JAR via the Java 9+ system ClassLoader (java.class.path) or a differently formatted file: URL (such as file:///tmp/a.jar vs file:/tmp/a.jar or unencoded spaces), exposing it as jar:file:...!/ scans it twice and throws Conflicting SKILL.md.

Guava parses java.class.path for ClassLoader.getSystemClassLoader() and normalizes file: URLs to File, whereas fileClassPathRoots skips non-URLClassLoader parents and line 240 compares raw URL.toExternalForm() strings. Could you include java.class.path when loader.equals(ClassLoader.getSystemClassLoader()) and normalize file: URLs to a canonical Path before comparing?

@zhangxiangnan zhangxiangnan Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in def242214. Native-root reconciliation includes Java 9+ system java.class.path entries and canonical file identities, including URI spelling and space variants. It also follows local Manifest dependencies with Guava's parent-first visitation rules while resolving relative paths from the original alias location. The system-loader subprocess, URL-form deduplication, and Manifest/symlink regressions pass.

continue;
}
for (URL url : urlLoader.getURLs()) {
String rootKey = url.toExternalForm();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scannedRoots keys on raw url.toExternalForm() before stripping fragments and normalizing trailing slashes. If the same jar: root appears across loaders with and without #runtime (or with and without a trailing / on a subdirectory), it gets scanned twice and throws Conflicting SKILL.md.

Could you key scannedRoots on the normalized jarFileUrl (canonical Path for file: URLs, withoutFragment otherwise) paired with the normalized root?

@zhangxiangnan zhangxiangnan Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in def242214. The key remains JarRoot(archiveIdentity, root), with canonical file identity and normalized roots; it is recorded only after getJarFile() succeeds. Tests cover failed-alias fallback, #runtime/plain and trailing-slash aliases across loaders, and dot-segment aliases. Encoded dots remain literal entry names.

// Packaged Resources & ClassLoader Compatibility
// =========================================================================

@Test

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add tests covering the cases above?

  • Two jar: roots in the same URLClassLoader sharing a skill and a resource file
  • file:///... vs jar:file:/...!/ deduplication and a child URLClassLoader inheriting the system ClassLoader
  • #runtime vs plain jar: root deduplication across loaders

@zhangxiangnan zhangxiangnan Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The requested same-loader override, file/JAR URL-form, system-classloader, and cross-loader #runtime cases remain covered in def242214, along with failed-alias fallback. Additional regressions cover mixed roots, Manifest/symlink ownership, dot segments, and restricted directory scanning. Final counts: 56 ClassPath tests, 22 Local tests, and 11 InMemory tests (89 total), passing on Java 17 and 21. Full core and the Boot 4.0.2 executable-JAR fixture also pass; the PR description now records the final validation results.

@zhangxiangnan
zhangxiangnan force-pushed the fix/skills-boot-classpath branch from 52a5884 to 5d8fb4f Compare December 2, 2026 04:05
@zhangxiangnan

Copy link
Copy Markdown
Contributor Author

@kvmilos Thanks for the thorough follow-up review! Updated the PR in a single commit (5d8fb4f31) addressing all four points:

  • Per-loader JAR resource deduplication and .distinct() in listResources, while keeping cross-loader and _/- conflict detection
  • Java 9+ system ClassLoader (java.class.path) coverage and canonical file: archive identity matching
  • Normalized JarRoot(archiveIdentity, root) deduplication recorded only after opening the JarFile succeeds
  • Five new regression tests in ClassPathSkillSourceTest (41 tests total; all 74 tests across ClassPathSkillSourceTest, LocalSkillSourceTest, and InMemorySkillSourceTest pass locally)

Also refreshed the PR description to match the latest commit. Ready for another look when you have time.

Supplement Guava scanning with JarURLConnection roots without adding a Spring runtime dependency. Preserve ordinary classpath behavior, per-loader deduplication, canonical archive/root deduplication across loaders and java.class.path, and cover JAR subdirectories, parent loaders, malformed roots, and multi-release URLs.

Fixes google#1895
@zhangxiangnan
zhangxiangnan force-pushed the fix/skills-boot-classpath branch from 5d8fb4f to def2422 Compare December 2, 2026 11:21
@zhangxiangnan

Copy link
Copy Markdown
Contributor Author

@kvmilos Updated this PR as a single commit (def242214) and refreshed the implementation notes in the review threads.

The follow-up fixes retain per-loader override/conflict behavior across mixed roots and Manifest dependencies, normalize JAR-root aliases, and isolate unreadable roots without creating a classloader for directory scans. The PR description now matches the final implementation and validation.

Validation on the final source tree:

  • 89 SkillSource tests pass on Java 17 and 21 (56 ClassPath, 22 Local, 11 InMemory).
  • Full core Maven test command passes, including all configured variants. The main suite has 4,236 tests with 35 skips and no failures or errors; repeated Maven executions are not counted as additional tests.
  • The Spring Boot 4.0.2 executable-JAR fixture passes for discovery and resource reads, as does the ordinary classpath fixture.

Could you please take another look when convenient? I have left the review threads open for your confirmation.

@kvmilos kvmilos added ready to pull and removed needs review waiting on author Awaiting response from author. Failing that, maintainers will eventually closed it as stale. labels Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClassPathSkillSource discovers no skills in Spring Boot executable JARs

3 participants