Repository navigation
Conversation
🟢 Java Benchmark SLOs — All performance SLOs passed
PR vs. master results
Commit: Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion. |
…out reflection An instrumentation that needs a library class's private state today uses reflection, or a context store filled by advice. FieldAccessors makes the class implement an accessor interface whose methods each return one of its fields, so agent code reads them with plain field reads. It's all or nothing: the interface and getters are added only if every field is declared, non-static and of exactly its getter's type; otherwise the class is left alone. The getters are synthetic. Instrumentations use it through TypeTransformer.installFieldAccessors(interface, getter, field, ...), from a WithStructuralChange instrumentation with the interface as its marker. It lives in agent-tooling, and is public, for a class loading reason: an InstrumenterModule loads in InstrumentationClassLoader and its nested classes in DatadogClassLoader, so a package-private visitor nested in an instrumentation can't be reached from it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Muzzle's bytecode scan can't see the fields a FieldAccessors reads: the getters are generated into the library class, not read by advice. The muzzle generator now records each module's type advice and adds a reference requiring every field an installFieldAccessors call reads, non-static and of its getter's type, on the instrumented type. Muzzle then checks them against every library version in range, and a version without them skips the module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A ForKnownTypes instrumenter's types are often alternatives (a class renamed across versions, classes from optional jars), and the accessors are installed on each that has the fields. One plain reference per type required every type to exist with the fields, so a module listing alternatives failed muzzle everywhere, method advice included. The generator now emits one reference with the other types as alternatives (OrReference), satisfied by any one of them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… directly Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
307f5f9 to
cb89960
Compare
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
Accessor interfaces inheriting covariant getters can pass validation but produce classes missing a required JVM method. Calls through the wider parent interface then throw AbstractMethodError.
🤖 Bits Code Review · Commit cb89960
| if (!method.isDefault() && !Modifier.isStatic(method.getModifiers())) { | ||
| declared.add(method.getName()); | ||
| } |
There was a problem hiding this comment.
Reject inherited covariant getters that require bridge methods
For interfaces A declaring Object get(), B declaring String get(), and C extending both, this name-only validation accepts a mapping to a String field. Reflection selects the String getter, so generation emits only get():String, leaving get():Object unimplemented. Calling through A then throws AbstractMethodError despite instanceof C succeeding. Reject this unsupported interface shape, as suggested, or generate the required bridge getter.
| if (!method.isDefault() && !Modifier.isStatic(method.getModifiers())) { | |
| declared.add(method.getName()); | |
| } | |
| if (!method.isDefault() && !Modifier.isStatic(method.getModifiers())) { | |
| if (method.getReturnType() | |
| != getter(accessorInterface, method.getName()).getReturnType()) { | |
| throw new IllegalArgumentException( | |
| accessorInterface + " has covariant getters requiring bridges: " + method.getName()); | |
| } | |
| declared.add(method.getName()); | |
| } |
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
… the marker Review fixes for FieldAccessors: - installFieldAccessors now injects the accessor interface into the instrumented class's loader as a helper, ahead of the accessors in the same advice stack, unless it's on the bootstrap class path or already a module helper. The interface can therefore live in the instrumentation module. - A Serializable class without a serialVersionUID keeps its original default value, pinned as a field, as the field-backed context stores do: adding an interface and methods would otherwise change it and break deserialization between processes with and without the agent. The context injector's SerialVersionUIDInjector moves to context.asm so both share it. - The muzzle generator fails the build when an instrumentation installs accessors without being a structural change marked by the accessor interface, which retransformation relies on. - The constructor rejects an abstract getter taking arguments, which would be left unimplemented (a covariant redeclaration is bridged by javac). - Docs: the fields gate the whole module through muzzle, so accessors belong in a module of their own; muzzle also accepts an inherited field, which the transformation doesn't; fieldAccessorReferences gets back its Javadoc, and eachOf, which builds an OrReference, is now anyOf. - Tests: SUID pinning, a generic class's signature, a class that already implements the interface, the overload and covariant cases, the marker check, and a forked test where the interface is invisible to the target's loader until injected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
The PR adds private-field accessors with muzzle checks; the update adds interface injection, preserves serialization UIDs, enforces structural markers, and rejects argument-taking overloads. Three issues remain: the earlier inherited-covariant-getter AbstractMethodError is unfixed, injected marker identity breaks retransformation, and inconsistent shading breaks accessor injection in shaded modules.
🤖 Bits Code Review · Commit eae06cd
| && !moduleHelperClassNames.contains(accessorInterface.getName())) { | ||
| advice.add( | ||
| new HelperTransformer( | ||
| useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName())); |
There was a problem hiding this comment.
Recognize injected accessor markers during retransformation
When a non-bootstrap accessor is injected into an isolated target loader, its Class differs from the interface returned by structuralChangeMarker(), as the new injection test explicitly expects. PreserveLoadedStructure compares those classes by identity, so a subsequent retransformation skips the accessor transformation. The resulting bytes omit the previously added interface and getters, causing JVM schema-change rejection. Structural-marker detection must recognize the target loader's injected interface; the injection test also needs retransformation coverage.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| && !moduleHelperClassNames.contains(accessorInterface.getName())) { | ||
| advice.add( | ||
| new HelperTransformer( | ||
| useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName())); |
There was a problem hiding this comment.
Keep automatically injected accessor names consistent with shading
For a module with adviceShading() enabled and an automatically injected datadog.* accessor, AdviceShader's helper mapping excludes the accessor because it contains only module.helperClassNames(). Its bytecode therefore retains its original name, while HelperInjector requests its uniqueHelper() name, causing a wrong-name linkage failure and preventing instrumentation. Register automatically injected accessors in the shader mapping and consistently shade the interface references emitted by FieldAccessors; this requires coordinated changes beyond this injection call.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
installFieldAccessors takes just the accessor interface. Each abstract method is a no-argument getter: $$DD$$__foo() returns field foo, and a @field annotation names a field the getter's name doesn't. The interface is the single place a getter and its field are declared, so the call site can't drift from it, and the pair-shape checks (odd counts, repeated or unbacked getter names) are gone. @field lives in internal-api, on the bootstrap class path, so it can be read whether the interface is there too or injected from a module: an annotation whose class the interface's loader can't see is silently dropped. Getters are sorted by name, so the generated methods and muzzle references don't depend on reflection order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
For module-local accessor interfaces, retransformation does not recognize the injected marker and can fail because it attempts to remove the previously added interface and getters.
🤖 Bits Code Review · Commit 1bd1c90
| && !moduleHelperClassNames.contains(accessorInterface.getName())) { | ||
| advice.add( | ||
| new HelperTransformer( | ||
| useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName())); |
There was a problem hiding this comment.
Recognize injected accessor markers during retransformation
Injecting a module-local accessor creates a different Class object from structuralChangeMarker(), as the new forked test explicitly expects. MatchRecorder.PreserveLoadedStructure compares those objects by identity, so retransformation skips the accessor transformation. The resulting bytes omit the previously added interface and getters, causing the JVM to reject the retransformation. Marker matching must recognize the target-loader copy while continuing to exclude classes loaded without the structural change.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| && !moduleHelperClassNames.contains(accessorInterface.getName())) { | ||
| advice.add( | ||
| new HelperTransformer( | ||
| useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName())); |
There was a problem hiding this comment.
Collect dependencies of automatically injected accessors
When a module-local accessor extends another module-local interface, injecting only the accessor cannot define it in a loader that cannot see its superinterface. The supported CovariantName extends ObjectName shape therefore fails injection with NoClassDefFoundError instead of installing getters. Enabling injectHelperDependencies() does not help: dependency expansion already ran over module.helperClassNames(), before this automatic helper was added. Include automatically registered accessors in dependency collection and inject their superinterfaces first.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| new HelperTransformer( | ||
| useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName())); | ||
| } | ||
| applyAdvice(new FieldAccessors(accessorInterface)); |
There was a problem hiding this comment.
Use consistent shaded names for accessor interfaces
For a module using adviceShading(), HelperInjector gives declared helpers unique shaded names, but FieldAccessors emits the accessor's original name. A declared accessor helper is therefore unavailable under the name the transformed library class implements, which can prevent that class from loading. Automatically added accessors also miss AdviceShader's helper mapping, making their injection keys inconsistent with their bytecode names. Helper registration, generated interface references, and structural marker matching need consistent shaded names.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| cv.visitMethod( | ||
| Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, | ||
| methods[i], | ||
| "()" + descriptors[i], |
There was a problem hiding this comment.
Reject getter collisions before modifying the class
A valid annotated getter can have the same name and descriptor as an existing target method. For example, @field("name") String name() collides with SerializableSample.name(). Existing methods are forwarded unchanged and this loop emits another identical signature, producing invalid bytecode and ClassFormatError when the class loads. Check collisions as part of the eligibility shared by appliesTo() and wrap(), leaving the class unchanged before adding any interface or getters.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
|
Could we consider the approach in In the end-to-end Java 17 benchmarks, both approaches delivered the same practical win over My main concern with a generic field accessor utility is the pattern it encourages. Adding interfaces and getter methods requires transforming the target class before the JVM defines it. That puts a deadline on transformation and makes it harder to move work off the startup path. A background transformer can lose the race to class loading, and delayed attach may find the class already loaded. The added interfaces and methods are also visible to reflection, serialization frameworks, and other agents. The lookup approach works on Java 8 and only changes a constructor body, so we can retransform an already-loaded If that direction sounds good, you could rebase #13600 onto |
@mcculls Can you elaborate on your concerns about "what this encourages"?
|
@dougqh by “what this encourages”, I mean making structural modification of library classes a routine way for instrumentations to access private fields. Each instrumentation using this utility would then need to install those accessors before the target class is defined. As adoption grows, that creates more places where we cannot defer transformation or enable the same optimization through retransformation. That matters because I want us to retain the flexibility to move instrumentation work off the startup path and handle classes that are already loaded. A fallback preserves correctness when we miss class loading, but the optimization would still depend on when the agent transforms the class. I understand the preference for avoiding MethodHandles and additional initialization state. Here, the cached handles read the live fields; we aren’t capturing or maintaining copies of individual headers’ state. Given the comparable results in the benchmarks I shared, I consider that a reasonable tradeoff for retaining retransformation support. I also agree that Muzzle integration is valuable, but it doesn’t resolve the class-loading constraint or the compatibility surface introduced by adding interfaces and methods to library classes. For those reasons, I don’t support merging the generic field-accessor utility for this use case. I’d like us to proceed with the Kafka-specific lookup approach and reconsider a shared utility if another concrete use case demonstrates a need that justifies those constraints. |
@mcculls While I understand and agree with the desire to move more instrumentation later, there are downsides to transformation after class load as well. And for simple transforms like this, I think I have a solution that addresses most of your concerns. For Datadog JIT, I'm experimenting with fast in-place replacements at class load time. And we do have to keep in mind that transformations after class loading have their own problems. Yes, this approach cannot solve classes that are already loaded or delayed attach. So the trade-off of moving away from class load time isn't as clear as it may first appear. |
|
I think we have enough evidence to move forward with the Kafka lookup change first. It addresses our only concrete use case with comparable performance in the benchmarks I shared, while preserving the ability to transform the class both at initial load and afterwards. Introducing structural changes would immediately rule out deferring this transformation while retaining the optimization. Faster matching could reduce the cost of doing that work at class load time, but it cannot remove the requirement to do it then. I don’t think we should accept that constraint when the current use case doesn’t require it. I’m happy to have a wider discussion about field access and transformation strategy, but I see a high bar for introducing a shared mechanism that adds interfaces and methods to library classes. We should have concrete use cases and demonstrated benefits that justify the restrictions it imposes. With one use case already handled by lookup at comparable performance, I don’t think this PR clears that bar. |
@mcculls I do understand the concern about structural modifications, and the desire to move in a direction where we can attach and modify late. And I do think it makes sense to have a fallback that doesn't require structural modification. I think the way we keep the high bar is by enumerating the pros and cons of both approaches. That's how I arrived at the
To aid in the discussion, I had Claude prepare a comparison table: Ways to read
|
| Field accessors (#13656) | Constructor lookup (mcculls/kafka-record-header-lookup) |
privateLookupIn (no advice) |
Combined: accessors at load, privateLookupIn otherwise |
|
|---|---|---|---|---|
| How it works | Adds an interface and synthetic getters to the class when it is defined | Constructor advice captures a Lookup from inside the class, then caches getter handles |
A helper in the class's loader calls MethodHandles.privateLookupIn and caches getter handles |
Accessors when the agent sees the class defined; privateLookupIn for a class that's already loaded |
| Changes the library class | Yes: one interface, one getter per field | Constructor body only | No | Only when the accessors apply |
| When the agent must act | Before the class is defined | Any time, but the handles exist only after a later constructor call | Any time | Any time |
| Class loaded before the agent (delayed attach) | Not covered: the existing copying path | Covered after retransforming the constructor and one new instance | Covered on 9+, no transformation | Covered on 9+, no transformation |
| Objects created before the agent acts | Not covered | Covered once the handles exist; needs a later construction to get them | Covered on 9+ | Covered on 9+ |
| Needs retransformation for late coverage | No (no late coverage) | Yes: a safepoint, deoptimization of code compiled against the class, then re-warmup; JDK 8 retransformation has been unstable in practice (live debugger) | No | No |
| Java versions | 8+ | 8+ | 9+ (8 keeps the copying path) | 8+ at load time; 9+ for late coverage |
| Library changes the fields | Muzzle fails, the module is skipped, and the build catches it | Runtime fallback to copying, no build failure (muzzle references could be added by hand) | Same as constructor lookup | Muzzle for the accessor part |
| Read on the hot path | A plain field read | invokeExact on handles that aren't compile-time constants (not measured on its own) |
Same as constructor lookup | A plain field read when the accessors apply |
| Cost when tracing doesn't read the header | None | A volatile read and a branch in every RecordHeader constructor |
None | None |
| Visible to reflection, serialization, other agents | Yes: the interface and synthetic getters (serialVersionUID pinned) |
No | No | Yes, when the accessors apply |
| Named modules | Not affected | Not affected | Needs the package opened to the helper (classpath classes are) | As each part |
| Adding the next class | Declare an interface; injection and muzzle references are generated | New capture advice, handles and fallback tests | New handle setup and fallback tests | Both mechanisms |
Notes:
privateLookupInwas checked standalone on JDK 11, 17 and 25 (a helper in the same loader as a classpath class read a private field of an object created before the helper loaded), not yet under the agent.- One JDK 8 consumer rep ran while the machine was heavily loaded; dropping it moves each median by less than 1%.
- Neither lookup variant's handle cost has been measured separately from the end-to-end runs below.
Kafka macrobenchmark, JDK 8 and 17
Consumer and enricher on a local single-node broker (broker on JDK 17), 10% of upstream traces sampled, 256m heap, 5 reps with the variant order rotating, median throughput. All three agents are built on the same base commit.
| workload | master | constructor lookup | field accessors | young GCs per 1M records (master → lookup / accessors) |
|---|---|---|---|---|
| consumer, JDK 8 | 168.6k/s | 173.1k/s (+2.7%) | 176.1k/s (+4.5%) | 43 → 36 / 36 |
| enricher, JDK 8 | 103.0k/s | 107.2k/s (+4.1%) | 108.2k/s (+5.1%) | 105 → 97 / 99 |
| consumer, JDK 17 | 210.6k/s | 211.4k/s (+0.4%) | 213.1k/s (+1.2%) | 37 → 32 / 32 |
| enricher, JDK 17 | 156.7k/s | 162.9k/s (+3.9%) | 166.6k/s (+6.4%) | too variable to compare: 65–138 per run for every variant |
Where the GC counts are stable, the two approaches give the same reduction. Their throughput ranges overlap on every workload (for example, enricher on JDK 17: lookup 160k–172k/s, accessors 164k–170k/s), matching the JDK 17 results shared earlier in this thread. Performance doesn't decide between them.
What Does This Do
Adds
FieldAccessorsto the instrumentation kit, so agent code can read a library class's private fields without reflection, and generates muzzle references for those fields so muzzle checks them across the library's version range.FieldAccessors(agent-tooling) makes an instrumented class implement an accessor interface whose methods each return one of its fields.TypeTransformer.installFieldAccessors(MyAccessor.class), from aWithStructuralChangeinstrumentation with the interface as its marker. The interface declares each getter and its field together:$$DD$$__foo()returns fieldfoo, and@Field("bar")names a field the getter's name doesn't.@Fieldlives in internal-api, on the bootstrap class path, so it's readable whether the interface is there too or injected from a module.installFieldAccessorscall into a reference requiring those fields on the instrumented type. It fails the build if that instrumentation isn'tWithStructuralChangewith the accessor interface as its marker, which retransformation relies on.installFieldAccessorsinjects it as a helper into the instrumented class's loader, ahead of the accessors in the same advice stack, so nothing has to be declared. An interface on the bootstrap class path is used as it is.Motivation
An instrumentation that needs a library object's private state today reads it with reflection, or has advice copy it into a context store. Both cost on hot paths. The first user is the Kafka consumer (#13600, stacked on this): it reads a fetched
RecordHeader's key and value buffers directly instead of callingkey()andvalue(), which decode and copy every header on every record.Additional Notes
@Fieldor its$$DD$$__prefix, or construction fails.serialVersionUID: adding an interface and methods changes aSerializableclass's default value, so a class that declares none gets its original value pinned as a field, as the field-backed context stores do. The context injector'sSerialVersionUIDInjectormoved tocontext.asmso both share it.InstrumenterModuleloads inInstrumentationClassLoader, but its nested classes load inDatadogClassLoader. So a package-private visitor nested in an instrumentation can't be reached from it. A first version did exactly that and failed at agent startup with anIllegalAccessError. Unit tests load both in one class loader and missed it; a standalone check against the built agent jar caught it.typeAdvicethe same wayAdviceScannerrecordsmethodAdvicefills that gap with no declaration needed. Muzzle then checks every library version in range, and a version without the fields skips the whole module, method advice included. So install accessors from a module of their own, as Read fetched Kafka headers without copying them first #13600 does; the Javadoc now says so. Muzzle also accepts a field the class inherits, which the transformation doesn't (it requires a declared field), so a version that moved a field to a superclass passes muzzle and is left without the accessor. OnlyForSingleTypeandForKnownTypesinstrumenters are covered, since a type hierarchy has no names to check. ForForKnownTypes, the fields are required on any one of the known types (a singleOrReference), so a module listing alternatives, such as a class renamed across versions, still passes muzzle.FieldAccessorsTestcovers getters of reference and primitive types, a missing field, a type mismatch, a static field, a class with no interfaces, a generic class's signature, a class that already implements the interface,serialVersionUIDpinning, bad declarations (a getter naming no field, no getters, a void getter, an overload taking arguments),@Fieldnames, a covariant redeclaration, and synthetic getters.FieldAccessorMuzzleReferencesTestchecks the generated references, including two known types where only one exists, and that a module that isn't a structural change fails the build.FieldAccessorInjectionForkedTestdefines the target class in a loader that can't see the interface, and checks it implements an injected copy.muzzletask passes across the whole Kafka range with the generated references.🤖 Generated with Claude Code