Skip to content

Add FieldAccessors to read a library class's private fields without reflection - #13656

Open
dougqh wants to merge 6 commits into
masterfrom
dougqh/field-accessors
Open

dougqh wants to merge 6 commits into
masterfrom
dougqh/field-accessors

Conversation

@dougqh

@dougqh dougqh commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

Adds FieldAccessors to 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.
  • Instrumentations use it through TypeTransformer.installFieldAccessors(MyAccessor.class), from a WithStructuralChange instrumentation with the interface as its marker. The interface declares each getter and its field together: $$DD$$__foo() returns field foo, and @Field("bar") names a field the getter's name doesn't. @Field lives in internal-api, on the bootstrap class path, so it's readable whether the interface is there too or injected from a module.
  • The muzzle generator records each module's type advice and turns every installFieldAccessors call into a reference requiring those fields on the instrumented type. It fails the build if that instrumentation isn't WithStructuralChange with the accessor interface as its marker, which retransformation relies on.
  • The accessor interface can live in the instrumentation module: installFieldAccessors injects 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 calling key() and value(), which decode and copy every header on every record.

Additional Notes

  • 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, and the instrumentation falls back to its other path. Every abstract method must be a no-argument getter whose field is named by @Field or its $$DD$$__ prefix, or construction fails.
  • The getters are synthetic, so tooling that filters synthetic members passes over them.
  • serialVersionUID: adding an interface and methods changes a Serializable class'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's SerialVersionUIDInjector moved to context.asm so both share it.
  • Getter shape: every abstract method of the interface must be a no-argument getter backed by a field. An overload taking arguments is rejected, since it would be left unimplemented; a covariant redeclaration is fine, because javac bridges it with a default method.
  • Why it lives in agent-tooling, and is public: an InstrumenterModule loads in InstrumentationClassLoader, but its nested classes load in DatadogClassLoader. 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 an IllegalAccessError. Unit tests load both in one class loader and missed it; a standalone check against the built agent jar caught it.
  • Muzzle: its bytecode scan can't see these fields, because the getters are generated into the library class rather than read by advice. Recording typeAdvice the same way AdviceScanner records methodAdvice fills 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. Only ForSingleType and ForKnownTypes instrumenters are covered, since a type hierarchy has no names to check. For ForKnownTypes, the fields are required on any one of the known types (a single OrReference), so a module listing alternatives, such as a class renamed across versions, still passes muzzle.
  • Tests:
    • FieldAccessorsTest covers 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, serialVersionUID pinning, bad declarations (a getter naming no field, no getters, a void getter, an overload taking arguments), @Field names, a covariant redeclaration, and synthetic getters.
    • FieldAccessorMuzzleReferencesTest checks the generated references, including two known types where only one exists, and that a module that isn't a structural change fails the build.
    • FieldAccessorInjectionForkedTest defines the target class in a loader that can't see the interface, and checks it implements an injected copy.
    • Read fetched Kafka headers without copying them first #13600's Kafka muzzle task passes across the whole Kafka range with the generated references.

🤖 Generated with Claude Code

@dougqh dougqh added type: feature Enhancements and improvements tag: no release notes Changes to exclude from release notes comp: tooling Build & Tooling tag: ai generated Largely based on code generated by an AI or LLM labels Nov 23, 2026
@datadog-prod-us1-5

datadog-prod-us1-5 Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🎯 Code Coverage (details)
• Patch Coverage: 0.00%
• Overall Coverage: 59.35% (-1.68%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 1bd1c90 | Docs | Give us feedback!

@dd-octo-sts

dd-octo-sts Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.04 s 14.00 s [-0.3%; +1.0%] (no difference)
startup:insecure-bank:tracing:Agent 13.00 s 13.03 s [-1.0%; +0.5%] (no difference)
startup:petclinic:appsec:Agent 17.32 s 17.16 s [-0.1%; +1.9%] (no difference)
startup:petclinic:iast:Agent 17.09 s 17.23 s [-1.6%; -0.0%] (maybe better)
startup:petclinic:profiling:Agent 16.70 s 16.26 s [-1.7%; +7.1%] (no difference)
startup:petclinic:sca:Agent 17.29 s 17.08 s [+0.4%; +2.1%] (maybe worse)
startup:petclinic:tracing:Agent 16.18 s 16.45 s [-2.5%; -0.7%] (maybe better)

Commit: 1bd1c90e · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

dougqh and others added 4 commits November 23, 2026 21:32
…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>
@dougqh
dougqh force-pushed the dougqh/field-accessors branch from 307f5f9 to cb89960 Compare November 24, 2026 02:33
@dougqh
dougqh marked this pull request as ready for review November 24, 2026 19:43
@dougqh
dougqh requested a review from a team as a code owner November 24, 2026 19:43
@dougqh
dougqh requested review from amarziali and mcculls and removed request for a team November 24, 2026 19:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T19:49:23.071447Z cb89960 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@dougqh

dougqh commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@datadog-prod-us1-5 datadog-prod-us1-5 Bot 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.

Bits Code Review: FAIL

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.

Open Bits AI session

🤖 Bits Code Review · Commit cb89960

Comment on lines +80 to +82
if (!method.isDefault() && !Modifier.isStatic(method.getModifiers())) {
declared.add(method.getName());
}

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.

P2 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.

Suggested change
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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: cb89960ae8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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>

@datadog-prod-us1-5 datadog-prod-us1-5 Bot 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.

Bits Code Review: FAIL

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.

Open Bits AI session

🤖 Bits Code Review · Commit eae06cd

&& !moduleHelperClassNames.contains(accessorInterface.getName())) {
advice.add(
new HelperTransformer(
useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName()));

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.

P2 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()));

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.

P2 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>
@dougqh
dougqh requested review from a team as code owners November 24, 2026 21:00

@datadog-prod-us1-5 datadog-prod-us1-5 Bot 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.

Bits Code Review: FAIL

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.

Open Bits AI session

🤖 Bits Code Review · Commit 1bd1c90

&& !moduleHelperClassNames.contains(accessorInterface.getName())) {
advice.add(
new HelperTransformer(
useAgentCodeSource, adviceShader, requestingName, accessorInterface.getName()));

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.

P1 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()));

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.

P1 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));

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.

P1 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],

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.

P1 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

@mcculls

mcculls commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Could we consider the approach in mcculls/kafka-record-header-lookup for Kafka and revisit the need for a generic field accessor utility if another use case comes up? The lookup branch adds advice to Kafka’s RecordHeader constructor that captures a MethodHandles.Lookup from inside the class and caches getter handles for the private header buffers. Tracing can then read the buffers directly, before Kafka’s public accessors materialize them.

In the end-to-end Java 17 benchmarks, both approaches delivered the same practical win over master. Consumer throughput rose from about 228k to 237–238k records/s, and enricher throughput rose from about 160k to 162–163k records/s. Both cut consumer young GCs from about 35 to 30 per million records. The throughput gap between the two approaches was within run-to-run variation in both workloads.

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 RecordHeader. With comparable throughput and GC gains, I’d prefer the Kafka-specific lookup and keep the flexibility to transform the class after it loads.

If that direction sounds good, you could rebase #13600 onto master and cherry-pick the lookup commit in place of the current field-accessor changes, keeping the rest of the Kafka work in that PR.

@dougqh

dougqh commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Could we consider the approach in mcculls/kafka-record-header-lookup for Kafka and revisit the need for a generic field accessor utility if another use case comes up? The lookup branch adds advice to Kafka’s RecordHeader constructor that captures a MethodHandles.Lookup from inside the class and caches getter handles for the private header buffers. Tracing can then read the buffers directly, before Kafka’s public accessors materialize them.

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.

@mcculls Can you elaborate on your concerns about "what this encourages"?
I much prefer this approach to the MethodHandle approach because...

  • I prefer to avoid reflection whenever possible (including MethodHandle)
  • I prefer to not to introduce additional state capture
  • I like that this solution is integrated with Muzzle

@mcculls

mcculls commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Could we consider the approach in mcculls/kafka-record-header-lookup for Kafka and revisit the need for a generic field accessor utility if another use case comes up? The lookup branch adds advice to Kafka’s RecordHeader constructor that captures a MethodHandles.Lookup from inside the class and caches getter handles for the private header buffers. Tracing can then read the buffers directly, before Kafka’s public accessors materialize them.

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.

@mcculls Can you elaborate on your concerns about "what this encourages"? I much prefer this approach to the MethodHandle approach because...

  • I prefer to avoid reflection whenever possible (including MethodHandle)
  • I prefer to not to introduce additional state capture
  • I like that this solution is integrated with Muzzle

@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.

@dougqh

dougqh commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Could we consider the approach in mcculls/kafka-record-header-lookup for Kafka and revisit the need for a generic field accessor utility if another use case comes up? The lookup branch adds advice to Kafka’s RecordHeader constructor that captures a MethodHandles.Lookup from inside the class and caches getter handles for the private header buffers. Tracing can then read the buffers directly, before Kafka’s public accessors materialize them.

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.

@mcculls Can you elaborate on your concerns about "what this encourages"? I much prefer this approach to the MethodHandle approach because...

  • I prefer to avoid reflection whenever possible (including MethodHandle)
  • I prefer to not to introduce additional state capture
  • I like that this solution is integrated with Muzzle

@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.
That approach should work well for any simple transform.
The main trick is just a faster matching & indexing scheme.
That same approach can be extended to other parts of matching, too.

And we do have to keep in mind that transformations after class loading have their own problems.
First, we know from live debugger that post load transforms cause crashes on earlier revisions of Java 8.
Second, transforming a method used in a compilation requires a stop-the-world deoptimization pause.
Which in turn leads to the JVM compiling again and an additional mini-warmup phase.

Yes, this approach cannot solve classes that are already loaded or delayed attach.
By necessity, we already have the precedent of handling JDK classes differently.
And we can always create an abstraction layer that gives us the best approach available for the circumstances -- as you've already done with field injection.

So the trade-off of moving away from class load time isn't as clear as it may first appear.
I'd like to see the options explored and discussed as a group before we pick a path -- and there may not be just one path.

@mcculls

mcculls commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

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.

@dougqh

dougqh commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

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
Yes, I agree that the lookup approach could work in this case.
Maybe with one simplification: I think we can drop the constructor capture needed for JDK 8 and just use MethodHandles.privateLookupIn on 9+. JDK 8 can use the existing code path.
I also agree that we should maintain a high bar on the instrumentation mechanisms that we add.

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 privateLookupIn suggestion.
I did my best to answer the concerns with early modification in my prior reply. I would like my concerns with late transformation to be addressed as well:

  • JDK 8 instability
  • deoptimization and re-warmup

To aid in the discussion, I had Claude prepare a comparison table:

Ways to read RecordHeader's private buffers

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:

  • privateLookupIn was 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.

@mcculls

mcculls commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Thanks @dougqh - I opened #13737 which includes an additional improvement to use MutableCallSite.

This branch has not been deployed

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

Labels

comp: tooling Build & Tooling tag: ai generated Largely based on code generated by an AI or LLM tag: no release notes Changes to exclude from release notes type: feature Enhancements and improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants