Repository navigation
fix: the shaded agent recorded nothing, the shaded JAR shipped unloadable entries, and its ClassFile API bridge was unreachable - #19
Merged
Conversation
…18) Run as -javaagent, the shaded JAR transformed nothing and recorded nothing. Every transformation failed with: java.lang.IllegalStateException: Reflection-based injection is not available on the current VM at AgentBuilder$InjectionStrategy$UsingReflection.resolve at AgentBuilder$InitializationStrategy$SelfInjection$Split$Dispatcher.register MethodDelegation with @supercall generates auxiliary classes that must be injected into the instrumented class's loader. AgentBuilder's default InjectionStrategy does that reflectively, which a modern JVM refuses, and AgentBuilder's default listener is a no-op, so the failure was silent: the agent attached, matched types, and dropped every transformation on the floor. Byte Buddy 1.18's remaining injection strategies do not help. Unsafe is disabled from Java 25, and JNA would add a dependency to a toolkit whose whole premise is having none. Advice inlines the instrumentation into the target method instead, so there are no auxiliary classes and no injection. It also drops the per-call Callable that @supercall allocated, which the hot path was never supposed to pay for. Also: - Surface transformation failures on System.err instead of swallowing them. Errors only by default; -Dnanometer.agent.debug=true for the full stream. Silence is what made this cost a debugging session rather than a glance. - Add nanometer.sampling/profiling/trace to the agent's self-ignore list. They are reached from the inlined advice, so instrumenting them would recurse. AutoMetricInterceptor keeps intercept(Method, Callable) unchanged, so its public surface and existing tests still hold. Both it and the new advice hooks funnel into enterSpan/exitSpan, so the span bookkeeping and sampling decision exist once rather than drifting apart. Parent/child correlation moves from two ThreadLocal Longs to a per-thread long[] stack, pre-sized to 64 frames and reused, because Advice cannot carry more than one value from enter to exit. Verified: - ShadedAgentIT forks a JVM with -javaagent:<shaded jar> and asserts spans are recorded, that a nested call inherits its caller's trace id and points at the caller's span, and that a throwing method records its exception type. - Reverting this commit's transform back to MethodDelegation turns all three red (recordsSpans, correlatesNestedSpans, recordsExceptionType); with Advice they pass. The unit suite passes either way, which is the gap that let this ship. - Full mvn clean verify: BUILD SUCCESS, 45 unit tests and 7 integration tests. VibeTags: no new annotations. @AIMemoryBudget(ZERO_ALLOCATION) was considered for enterSpan/exitSpan and rejected as untrue, since exitSpan allocates a RelationalMetricEvent whenever the sampler keeps a span. The existing @AIperformance moves with the hot-path logic to exitSpan; the regenerated rule files reflect that. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
…#17) maven-shade-plugin rewrites the bytecode inside META-INF/versions/N/ entries to the relocated package but cannot rewrite their entry paths. The uber-JAR therefore shipped 31 entries whose path disagreed with the class inside: META-INF/versions/24/net/bytebuddy/jar/asmjdkbridge/AsmAttribute.class declares nanometer/shaded/bytebuddy/jar/asmjdkbridge/AsmAttribute Loading one raises NoClassDefFoundError "wrong name". Nothing loaded them only because the shaded manifest carries no Multi-Release attribute, so the JVM ignores META-INF/versions entirely. The JAR was correct by accident of an absent manifest attribute, and anyone adding Multi-Release later, or swapping in a transformer that preserved Byte Buddy's own manifest, would have turned 31 dead entries into load failures with no obvious link to the change that caused them. This uber-JAR is deliberately not multi-release, so the versioned entries are dead weight. Excluding them removes bytes the JVM already ignored rather than changing behaviour. The filter covers every artifact, not just the relocated ones: org.jspecify also contributes a META-INF/versions/9 module-info and OSGi metadata that an uber-JAR cannot use. This predates the Byte Buddy bump. It already applied to the relocated org.sqlite entries under META-INF/versions/9 before that change. Adds maven-failsafe-plugin to nanometer-api so integration tests run after package and can inspect the artifact that actually ships. The surefire suite only ever sees the unshaded module classpath, which is why both this and the agent defect in the previous commit were invisible. ShadedJarLayoutIT pins four invariants: - every class entry's path matches the class it declares, read back with ASM - no META-INF/versions entries, and no Multi-Release manifest attribute, so the two stay consistent - no unrelocated net/bytebuddy or org/sqlite classes, which is the zero-classpath-pollution guarantee - the Premain-Class, Agent-Class and retransform manifest entries survive shading Verified by removing the filter and rebuilding: classPathsMatchDeclaredNames and carriesNoMultiReleaseEntries both go red and name all 31 offending entries. With the filter, mvn clean verify is BUILD SUCCESS with 45 unit tests and 7 integration tests. The instrumented IT subject lives in nanometer.it.subject rather than nanometer.it.target: .gitignore's first line is target/, which matches a directory of that name at any depth and would silently keep the file out of the commit while the build stayed green locally. Also ignores dependency-reduced-pom.xml, which shade regenerates on every package and which was previously left untracked in the working tree. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
… on (#18) Advice inlines its body into the instrumented method, so the instrumented class ends up holding a direct reference to nanometer.agent.AutoMetricInterceptor. That resolves only if the interceptor is visible from the instrumented class's own loader. ShadedAgentIT previously drove classes off the system class path, where visibility is trivially satisfied, so it proved the fix for the easiest case only. Nanometer is meant to sit inside applications that load their own classes in a child loader, Spring Boot fat JARs and servlet containers among them. That is the deployment shape worth pinning. ChildLoaderDriver defines nanometer.it.subject.AgentTarget in a child-first loader rather than delegating for it, so the class really is defined by the child while the agent classes still come from the parent. It asserts the target was defined by that loader before doing anything else, so the test cannot quietly degrade into re-testing the system class path. Verified by deliberate breakage: reverting the agent's transform to MethodDelegation turns all four ShadedAgentIT tests red, the new one included. With Advice all four pass. mvn clean verify: BUILD SUCCESS, 45 unit tests and 8 integration tests. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
main moved to maven-surefire-plugin 3.6.0 while this branch introduced maven-failsafe-plugin pinned separately at 3.2.5. The two share a codebase and are released together, so two literal versions in two files is a pair that drifts: dependabot bumps one, nobody notices the other, and the mismatch shows up as a confusing test-runner bug rather than as a version problem. Introduces a surefire.version property, used by both, and declares failsafe in the root pluginManagement alongside surefire so the module pom carries no version of its own. This matches how jacoco.version is already handled here. Verified: failsafe now resolves to 3.6.0, the version surefire is on, and mvn clean verify is BUILD SUCCESS with 45 unit tests and 8 integration tests actually executed rather than skipped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
…est task The new *IT classes turned all three Gradle jobs red: Shaded JAR works as a Java agent > initializationError FAILED Shaded JAR layout > initializationError FAILED Execution failed for task ':nanometer-api:test' Maven keeps them out of surefire by naming convention and runs them under failsafe after package, where the shaded artifact exists and the nanometer.shaded.jar property points at it. Gradle's test task scans every test class in the source set, so it ran them with no artifact to point at and they failed on the missing property. This build performs no shading at all, so it has no artifact for these tests to inspect and excluding them costs no coverage. They are excluded rather than taught to skip when the property is absent. Under Maven these have to fail loudly if the artifact or the property goes missing: a gate that quietly skips when its subject is absent is exactly the kind of green that let the two defects they cover reach a release in the first place. Verified locally with a full Gradle build, not just Maven: BUILD SUCCESSFUL, all seven module test tasks executed, zero IT classes run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
) Byte Buddy ships its JDK ClassFile API bridge only under META-INF/versions/24, and uses it in place of its bundled ASM on JDK 24 and newer. The shaded JAR could not reach it. #17 excluded the versioned entries because shade rewrites their bytecode to the relocated package but leaves their paths alone, so they declared one class and lived at another's path. Excluding them was correct while that mismatch stood, but it made the fallback to bundled ASM permanent. Staying on bundled ASM means every new class file version needs a Byte Buddy upgrade before it can even be read, which is exactly the failure that produced #16: shade 3.5.2's ASM 9.6 could not read Byte Buddy's own major-68 classes. The paths can be relocated after all. maven-shade-plugin has no dedicated support for multi-release entries, but its relocator matches on path prefix, so naming the versioned prefix as a relocation pattern of its own moves the entry: META-INF.versions.24.net.bytebuddy -> META-INF.versions.24.nanometer.shaded.bytebuddy META-INF.versions.9.org.sqlite -> META-INF.versions.9.nanometer.shaded.sqlite Those patterns never match a class reference in bytecode, so they change only entry paths; the existing net.bytebuddy and org.sqlite relocations keep doing the content rewriting. With the paths in agreement, Multi-Release: true becomes safe to declare and the versioned classes become loadable. Both artifacts' versioned entries are additive rather than overriding: neither net/bytebuddy/jar/asmjdkbridge nor org/sqlite/nativeimage exists in its base JAR, so enabling multi-release adds classes rather than swapping an implementation underneath the base one. module-info and OSGi metadata stay excluded. An uber-JAR merges packages from many modules, so a module descriptor cannot be correct, and OSGi metadata describes a bundle this artifact is not. Tests, replacing the inverted invariant from #17: - isACoherentMultiReleaseJar asserts the flag and the entries agree in both directions, so neither can be introduced without the other. - exposesTheClassFileApiBridgeOnSupportedRuntimes asserts the bridge resolves on JDK 24+ and is correctly invisible below it. It asserts both branches rather than skipping under 24, so it proves something on every JDK in the matrix instead of going quiet on one third of it. - relocationIsComplete now strips the version prefix before checking, so a relocation covering only the base JAR no longer slips past it. - classPathsMatchDeclaredNames is unchanged and now covers the versioned entries too, which is what makes enabling Multi-Release safe. Verified by deliberate breakage: - Removing Multi-Release: true turns isACoherentMultiReleaseJar and the bridge test red. - Removing the two versioned relocations turns classPathsMatchDeclaredNames, relocationIsComplete and the bridge test red, naming all 31 entries. - Confirmed the relocated bridge class loads from the shaded JAR on JDK 26, and that all four agent ITs still pass with multi-release enabled, which is the real risk: Byte Buddy may now take the ClassFile API path when transforming. Verified on both build systems and both ends of the JDK range: mvn clean verify BUILD SUCCESS on JDK 26 and on JDK 21, 45 unit tests and 9 integration tests; gradle build BUILD SUCCESSFUL. The JDK 21 run also hits a pre-existing failure in nanometer-example's dynamic self-attach test that reproduces on the unmodified commit on this machine and passes in CI, so it is a local JDK issue and not from this change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #18. Fixes #17. Fixes #20.
Follows #16, which is already merged. That PR unblocked the Byte Buddy 1.18.13 bump and filed these two defects it exposed; this PR fixes them.
#18 — the shaded agent transformed classes but recorded nothing
The hypothesis in the issue was wrong. There was no second copy of
AutoMetricInterceptor.interceptwas never invoked at all: every transformation failed, and the failure was swallowed.Adding a listener surfaced it:
MethodDelegationwith@SuperCallgenerates auxiliary classes that must be injected into the instrumented class's loader.AgentBuilder's defaultInjectionStrategydoes that reflectively, which a modern JVM refuses, and its default listener is a no-op. The agent attached, matched types, generated the transformed bytecode, and discarded it silently.None of Byte Buddy 1.18's other injection strategies is a general answer:
UsingUnsafeis disabled from Java 25 onward, andUsingJnawould add a dependency to a toolkit whose premise is having none.Fix: instrument with
Advice. It inlines into the target method, so there are no auxiliary classes and no injection at all. It also removes the per-callCallablethat@SuperCallallocated on a hot path documented as zero-allocation.AutoMetricInterceptor.intercept(Method, Callable)is unchanged, so its public surface and existing unit tests still hold. It and the new advice hooks both funnel intoenterSpan/exitSpan, so the span bookkeeping and sampling decision exist once rather than drifting apart. Parent/child correlation moves from twoThreadLocal<Long>fields to a per-threadlong[]stack, pre-sized to 64 frames and reused, becauseAdvicecan carry only one value from enter to exit.NanometerAgentnow reports failed transformations onSystem.errrather than swallowing them: errors only by default, the full stream under-Dnanometer.agent.debug=true. The silence is what turned a one-line diagnosis into a debugging session.#17 — unloadable multi-release entries
Shade rewrites the bytecode inside
META-INF/versions/N/entries to the relocated package but cannot rewrite their entry paths, so the JAR shipped 31 entries whose path disagreed with the class inside:Loading one raises
NoClassDefFoundError "wrong name". Nothing loaded them only because the shaded manifest carries noMulti-Releaseattribute, so the JVM ignoresMETA-INF/versionsentirely. The JAR was correct by accident of an absent manifest attribute.Fix: exclude those entries. Since the JVM already ignored them, this removes bytes that could never execute rather than changing behaviour, and removes the trap that enabling
Multi-Releaselater would have sprung. Option 2 from the issue, relocating the paths properly, is not reachable with stock shade.The filter covers every artifact, not only the relocated ones:
org.jspecifyalso contributes aMETA-INF/versions/9module-info.classand OSGi metadata an uber-JAR cannot use.This predates the Byte Buddy bump; it already applied to the relocated
org.sqliteentries underMETA-INF/versions/9.Why neither defect was caught
The surefire suite only ever sees the unshaded module classpath, and
AutoMetricInterceptorTestcallsinterceptdirectly, so it passes whether or not the agent wires anything up.This adds
maven-failsafe-pluginso integration tests run afterpackage, against the artifact that actually ships.ShadedAgentITforks a JVM with-javaagent:<shaded jar>and asserts spans are recorded, that a nested call inherits its caller's trace id and points at the caller's span, that a throwing method records its exception type, and that a class defined by a child class loader is instrumented too. That last case matters becauseAdviceinlines a direct reference toAutoMetricInterceptorinto the instrumented class, which only resolves if the interceptor is visible from that class's loader; Spring Boot fat JARs and servlet containers are the deployment shape that exercises it.ShadedJarLayoutITasserts every class entry's path matches the class it declares (read back with ASM), that there are no versioned entries and noMulti-Releaseattribute so the two cannot drift into the dangerous combination, that no unrelocatednet/bytebuddyororg/sqliteclasses leak, and that the agent manifest entries survive shading.Verified by deliberate breakage, not just by passing
MethodDelegationturns all fourShadedAgentITtests red. WithAdvice, all four pass.mvn clean verify: BUILD SUCCESS on JDK 26 and JDK 21, 45 unit tests and 9 integration tests.gradle build: BUILD SUCCESSFUL.Also in this PR
mainmoved to surefire 3.6.0 while this branch introduced failsafe. They share a codebase and are released together, so both now resolve from onesurefire.versionproperty, declared in the rootpluginManagementthe wayjacoco.versionalready is. Two literal versions in two files is a pair that drifts.#20 - the JDK ClassFile API bridge, restored
Excluding the versioned entries made Byte Buddy's fallback to bundled ASM permanent. That is worth avoiding: it means every new class file version needs a Byte Buddy upgrade before it can even be read, which is precisely the failure that produced #16 (shade 3.5.2's ASM 9.6 could not read Byte Buddy's own major-68 classes).
The paths turn out to be relocatable. Shade has no dedicated multi-release support, but its relocator matches on path prefix, so naming the versioned prefix as a relocation pattern of its own moves the entry:
Those patterns never match a class reference in bytecode, so they change only entry paths; the existing
net.bytebuddyandorg.sqliterelocations keep doing the content rewriting. With paths and declared names in agreement,Multi-Release: truebecomes safe to declare and the versioned classes become loadable.Both artifacts' versioned entries are additive, not overriding: neither
net/bytebuddy/jar/asmjdkbridgenororg/sqlite/nativeimageexists in its base JAR, so this adds classes rather than swapping an implementation underneath the base one.module-infoand OSGi metadata stay excluded, since an uber-JAR merges packages from many modules and cannot carry a correct descriptor.ShadedJarLayoutIT's multi-release assertion is inverted accordingly: it now requires the flag and the entries to agree in both directions, so neither can be introduced without the other. A new test asserts the bridge resolves on JDK 24+ and is correctly invisible below it, both branches rather than a skip under 24, so it proves something on every JDK in the matrix instead of going quiet on a third of it.relocationIsCompletenow strips the version prefix, so a relocation covering only the base JAR no longer slips past.Verified by deliberate breakage: removing
Multi-Release: trueturns two tests red; removing the two versioned relocations turns three red, naming all 31 entries. Also confirmed the relocated bridge class loads from the shaded JAR on JDK 26, and that all four agent ITs still pass with multi-release on, which is the real risk since Byte Buddy may now take the ClassFile API path when transforming.VibeTags
No new annotations.
@AIMemoryBudget(ZERO_ALLOCATION)was considered forenterSpan/exitSpanand rejected as untrue:exitSpanallocates aRelationalMetricEventwhenever the sampler keeps a span, so the annotation would have read as protection that is not there. The existing@AIPerformancemoves with the hot-path logic toexitSpan; the regenerated rule files reflect that.🤖 Generated with Claude Code
https://claude.ai/code/session_01V84rqTx2rsorFLrGWHk4B4