Skip to content

Shaded agent transforms classes but records no metrics into the ring buffer #18

Closed

Description

@PIsberg

What is wrong

Running the shaded nanometer-api-*-all.jar as a -javaagent transforms the target classes, but no events reach AutoMetricInterceptor's ring buffer.

Reproduction

Build the shaded JAR, then against this class:

package app;
public class Demo {
    public int work(int n) { return n * 2; }
    public static void main(String[] a) throws Exception {
        Class<?> ic = Class.forName("nanometer.agent.AutoMetricInterceptor");
        Object buf = ic.getMethod("getBuffer").invoke(null);
        Demo d = new Demo();
        for (int i = 0; i < 5; i++) d.work(i);
        System.out.println("size_after=" + buf.getClass().getMethod("size").invoke(buf));
        System.out.println("same_buffer=" + (buf == ic.getMethod("getBuffer").invoke(null)));
    }
}
java -javaagent:nanometer-api-0.1.0-all.jar=app -cp classes app.Demo

Observed on JDK 26:

size_after=0
same_buffer=true

Expected size_after to be at least 5. getDroppedCount() also reports 0, so the events are not being shed by a full buffer, and the default AdaptiveSampler sample rate is 1.0 so shouldSample returns true unconditionally.

What was ruled out

  • Transformation is happening. With -Dnanometer.shaded.bytebuddy.dump=<dir> the agent dumps app.Demo, app.Demo-original and four auxiliary classes.
  • Delegation is wired correctly. javap -c on the dumped app.Demo shows invokestatic nanometer/agent/AutoMetricInterceptor.intercept:(Ljava/lang/reflect/Method;Ljava/util/concurrent/Callable;)Ljava/lang/Object; in the transformed method bodies.
  • Relocation of the self-ignore matcher is correct. Shade rewrote the "net.bytebuddy." string constant in NanometerAgent.install to "nanometer.shaded.bytebuddy.", so the agent is not excluding the wrong packages.
  • Not caused by the Byte Buddy bump. Identical output (size_after=0, same_buffer=0 → true) from a main build with Byte Buddy 1.14.12 / shade 3.5.2 and from the PR fix: unblock Byte Buddy 1.18.13 in CI, and fix the shaded agent and JAR defects it exposed #16 build with 1.18.13 / shade 3.6.2. This is pre-existing.
  • Not a stale buffer reference. same_buffer=true shows the app-visible static is not being swapped out between the calls.

Leading hypothesis, not yet confirmed

Two copies of nanometer.agent.AutoMetricInterceptor may be reachable: the one the test resolves through the app class loader, and another that Byte Buddy injected for visibility from the instrumented class. The delegation would then write to a different static buffer than the one the test reads. This was not verified and should not be treated as the answer.

Why this matters

The existing test suite covers AutoMetricInterceptor against the unshaded classpath, where it passes. Nothing exercises the shaded artifact, which is what actually ships. If this reproduces for real users, the shipped agent JAR instruments code and collects nothing, and no test in the repo would notice.

What it would take

Confirm or refute the class-loader hypothesis, then add a test that runs the packaged shaded JAR as a real -javaagent in a forked JVM and asserts that events are recorded. That check has to run against the package output rather than the module's test classpath, which is why it does not fit the current surefire setup as-is.

Why it was not done in #16

#16 unblocks the Byte Buddy bump in CI. This defect is pre-existing, reproduces identically before and after that bump, and needs its own investigation.

Activity

  1. PIsberg commented on Sep 11, 2026

    @PIsberg
    OwnerAuthor

    Root cause found and fixed in fix/shade-plugin-mrjar-bytebuddy (PR #16).

    The leading hypothesis in the issue description was wrong. There are not two copies of AutoMetricInterceptor. intercept was never invoked at all, because every transformation failed and the failure was swallowed.

    Adding AgentBuilder.Listener.StreamWriting.toSystemError() surfaced it:

    [Byte Buddy] ERROR app.Demo [jdk.internal.loader.ClassLoaders$AppClassLoader, ...]
    java.lang.IllegalStateException: Reflection-based injection is not available on the current VM
    	at ...AgentBuilder$InjectionStrategy$UsingReflection.resolve(AgentBuilder.java:4480)
    	at ...AgentBuilder$InitializationStrategy$SelfInjection$Split$Dispatcher.register(AgentBuilder.java:4282)
    	at ...AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:12825)
    

    MethodDelegation with @SuperCall generates auxiliary classes that have to be injected into the instrumented class's loader. AgentBuilder's default InjectionStrategy does 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 then discarded it silently. The dumped class in the original report was real output from Byte Buddy that never reached the JVM.

    None of Byte Buddy 1.18's other injection strategies is a general answer: UsingUnsafe is disabled from Java 25 onward, and UsingJna would add a dependency to a toolkit whose premise is having none.

    Fix: instrument with Advice instead. It inlines into the target method, so there are no auxiliary classes and no injection at all. It also removes the per-call Callable that @SuperCall allocated on the hot path.

    AutoMetricInterceptor.intercept(Method, Callable) is unchanged, so the public surface and the existing unit tests still hold. It and the new advice hooks both funnel into enterSpan/exitSpan, so the recording logic is not duplicated.

    NanometerAgent now reports failed transformations on System.err rather than swallowing them, errors only by default and the full stream under -Dnanometer.agent.debug=true. The silence is what turned a one-line diagnosis into a debugging session.

    Test: 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 the transform to MethodDelegation turns all three red; the unit suite passes either way, which is precisely the gap that let this ship.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions