Repository navigation
fix(skills): discover resources in executable JAR classpaths - #1896
zhangxiangnan wants to merge 1 commit into
Conversation
9ab18ae to
0f3d4e3
Compare
c891ae8 to
8c0f4a9
Compare
|
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. |
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| connection = | ||
| (JarURLConnection) | ||
| new URL(url, "jar:" + connection.getJarFileURL() + "!/").openConnection(); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| 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) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| * <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}. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Retained in def242214: the public class Javadoc contains only the concise loading description. The paragraph about protected methods remains removed.
| } | ||
|
|
||
| // ========================================================================= | ||
| // Packaged Resources & ClassLoader Compatibility |
There was a problem hiding this comment.
Could you add unit tests for the uncovered branches in ClassPathSkillSource?
- A missing or unreadable
jar:URL alongside a validfile:root (with the fix above) - A multi-release
jar:URL with#runtime - A non-
URLClassLoaderchild delegating to ajar:-backedURLClassLoaderparent (continueat line 225) getResourceAsStreamreturningnullfor a JAR-discovered resource (lines 210-212)- A
jar:URL whose handler returns a non-JarURLConnection(line 232;doesNotOpenUnsupportedProtocolRootsuses"custom:", which returns at line 229) - A
jar:subdirectory root without a trailing slash (lines 236-238)
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
Nit: existing tests in this file use testMethod_condition naming (e.g., testLoadResource_notFound). Could you match that style for the new tests?
There was a problem hiding this comment.
Retained in def242214: all added tests use the existing testMethod_condition naming convention and remain in ClassPathSkillSourceTest.
| assertThrows( | ||
| RuntimeException.class, () -> source.findSkillMdPath("conflicting-skill").blockingGet()); |
There was a problem hiding this comment.
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(...)).
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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. |
fca89c4 to
52a5884
Compare
|
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
left a comment
There was a problem hiding this comment.
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?
supplementJarResourcesno longer skips native names (testScan_differentFileAndJarRootsWithSameResourceConflictasserts 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))) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Could you add tests covering the cases above?
- Two
jar:roots in the sameURLClassLoadersharing a skill and a resource file file:///...vsjar:file:/...!/deduplication and a childURLClassLoaderinheriting the systemClassLoader#runtimevs plainjar:root deduplication across loaders
There was a problem hiding this comment.
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.
52a5884 to
5d8fb4f
Compare
|
@kvmilos Thanks for the thorough follow-up review! Updated the PR in a single commit (
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
5d8fb4f to
def2422
Compare
|
@kvmilos Updated this PR as a single commit ( 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:
Could you please take another look when convenient? I have left the review threads open for your confirmation. |
Problem
Closes #1895.
ClassPathSkillSourcefinds no skills in a Spring Boot executable JAR even when its classloader can read them: Guava scansfile:entries but skips Boot'sjar:roots. Ordinary JDKjar:file:...!/roots reproduce the failure.Change
Supplement Guava discovery with
JarURLConnectionenumeration. Resource reads remain lazy and enumeration handles are closed. No new dependency or Spring-specific runtime code is introduced.The implementation preserves three behaviors:
#runtime._/-skill names, and return distinct resource paths.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
ResourceInfoAPI 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 toClassPathSkillSourceand its existing test class../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.git diff --checkpassed.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+.