Skip to content

Add experimental load-time fusion of simple stream pipelines - #13747

Draft
dougqh wants to merge 2 commits into
masterfrom
dougqh/stream-fusion
Draft

dougqh wants to merge 2 commits into
masterfrom
dougqh/stream-fusion

Conversation

@dougqh

@dougqh dougqh commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

What Does This Do

Adds an experimental, off-by-default load-time optimization: simple java.util.stream pipelines in application classes are fused into per-call-site code. Enable with DD_EXPERIMENTAL_STREAM_FUSION_ENABLED=true.

A pipeline such as list.stream().filter(p).map(f).collect(toList()) is rewritten in place, without moving any code:

  • stream() becomes a source check;
  • each intermediate operation becomes a hook at its original position, which keeps its argument on the stack;
  • the terminal becomes an invokedynamic linked to a class generated for that call site, which traverses the source with its own spliterator and calls the user's functions directly.

Supported today: sources Collection.stream() (trusted JDK collections) and String.chars(); operations filter, map, mapToInt/Long/Double/Obj; terminals collect(toList()/toSet()/joining()), anyMatch/allMatch/noneMatch, findFirst/findAny, forEach, int/long sum.

Layout:

  • agent-bootstrap: datadog.trace.bootstrap.jit.StreamFusion, the runtime support visible from every class loader.
  • agent-tooling: datadog.trace.agent.tooling.jit.stream, the transformer, the ASM dataflow matcher and rewriter, and the site-class generator.
  • AgentInstaller: registers a retransformation-incapable transformer when the setting is on.
  • ASM tree and analysis are compile-only dependencies; they already ship relocated in the agent's shared section.

Motivation

The JDK's stream library runs every pipeline in an application through one shared set of classes, so their type profiles are megamorphic and the JIT can't specialize or remove the pipeline objects. Per-site code restores per-pipeline specialization: each pipeline performs as if it were the only one in the program.

How it stays correct

The criterion is that every behavior of the rewritten program must already be a possible behavior of the original.

  • No code motion. Argument expressions run exactly when they did; each operation's null check happens at its original position.
  • Traversal is the source's own spliterator, called the same way the stream implementation calls it, so late binding, snapshotting and ConcurrentModificationException timing are unchanged by construction.
  • Only trusted JDK sources are fused: ArrayList, LinkedList, HashSet, LinkedHashSet, Arrays.asList, List.of/Set.of, and HashMap/LinkedHashMap key, value and entry views, plus String.chars(). Anything else (subclasses, user collections, wrappers such as Collections.unmodifiable*) runs the original stream calls at their original points.
  • A null source runs the original instruction, so the exception and its helpful message are unchanged.
  • Pipelines are only matched when each intermediate stream is consumed exactly once by the next call, which ASM dataflow analysis proves.
  • Class rewriting is conservative:
    • only methods that call a stream terminal are analyzed, and all others are copied byte for byte;
    • frames are recomputed only for rewritten methods, and a method is left unchanged if a type for its frames can't be resolved from class files;
    • the agent's own packages and JDK classes are never rewritten.
  • Linking is race-safe: concurrent bootstraps for one site link to the same class.
  • Class loaders are never retained: site state is per class loader in a weakly keyed map, and site classes are held through weak references.
  • One documented difference: a stack trace or stack walk taken inside a user lambda no longer shows the JDK's internal pipeline frames. User frames are unchanged. Those internal frames aren't specified and already differ between JDK releases.

Testing

  • StreamFusionTransformerTest: about 400 equivalence cases (10+ sources including map views and fallback sources; interference by add, grow, remove, clear, set and remove+add, also through a backing map; null sources, functions and elements; evaluation order of arguments; exceptions part-way through; nested and looped pipelines; non-ASCII strings). Each runs untransformed and transformed through the real transformer, comparing results, exception types and messages, side-effect logs and final source state.
    • The fused run is repeated 200 times so C2 compiles it.
    • 32 threads race the first calls to cold sites.
    • A direct check verifies that trusted sources are fused rather than wrapped.
    • Passes on JDK 8, 11, 17, 21 and 25.
  • End to end with the tracer (tracer alone vs tracer + fusion):
    • PetClinic: identical pages and the same instrumented classes, 82 classes fused.
    • PMD over 4,643 sources: byte-identical report, 17 classes fused.
    • All 21 Renaissance MIT benchmarks pass their own validation, 2–16 classes fused each.

Results

  • Renaissance mnemonics with the tracer: 2,152 → 1,723 ms median, +20% (+13% / +18% / +28% across rounds; noisy laptop).
  • In place, after polluting stream profiles with other pipeline shapes: the benchmark's hot method went from 102 to 59 ns per call (1.7x).
  • With a clean profile, the JIT already makes a stream nearly free, so the gain depends on how many distinct pipelines an application runs.
  • Startup (PetClinic, standalone prototype): about +180 ms of transform work, mostly analysis on about 400 candidate classes. Follow-ups below should reduce it.

Follow-ups (not in this PR)

  • Use the constant-pool sieve and needle table for the pre-check instead of a byte search.
  • Telemetry counters for sites fused, fallbacks and skipped rewrites.
  • A per-class exclusion setting, if needed beyond the kill switch.
  • Coverage: Stream.toList(), flatMap, array sources.
  • A JMH benchmark for the fallback path's per-execution overhead (one small allocation plus instanceof checks) on untrusted sources.

🤖 Generated with Claude Code

dougqh and others added 2 commits November 30, 2026 23:00
…l flag

With DD_EXPERIMENTAL_STREAM_FUSION_ENABLED=true, a retransformation-incapable
transformer rewrites pipelines such as list.stream().filter(p).map(f)
.collect(toList()) in application classes, in place and without moving any
code: stream() becomes a source check, each intermediate operation a hook at
its original position, and the terminal an invokedynamic linked to a class
generated for that call site. Each site gets its own class, so the user's
functions are called from code with per-site type profiles.

Trusted JDK sources are traversed with their own spliterator, so binding,
snapshot, and concurrent-modification behavior are unchanged; any other source
runs the original stream calls at their original points. Only methods that
call a stream terminal are analyzed, untouched methods are copied byte for
byte, and a method is left unchanged if its frames can't be computed without
guessing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Site classes and their generated bytes are now registered per class loader in
a weakly keyed map, and defined site classes are held through weak
references, so fused sites never keep an application class loader alive.
Registration stays lock-free; only defining a site class takes a per-loader
lock, so it can't deadlock with a loader's own lock during class loading.
Sites are registered only after the whole class rewrite has succeeded.

Also: trust the HashMap / LinkedHashMap key, value, and entry views as
sources, read each class file at most once when computing frames, derive the
terminal check from the Terminal enum, and drop unused counters and checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dougqh dougqh added type: feature Enhancements and improvements tag: performance Performance related changes tag: experimental Experimental changes comp: tooling Build & Tooling tag: ai generated Largely based on code generated by an AI or LLM labels Dec 1, 2026
@datadog-datadog-prod-us1

This comment has been minimized.

@dd-octo-sts

dd-octo-sts Bot commented Dec 1, 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.82 s 14.69 s [+0.2%; +1.7%] (maybe worse)
startup:insecure-bank:tracing:Agent 13.72 s 13.74 s [-1.0%; +0.6%] (no difference)
startup:petclinic:appsec:Agent 17.14 s 16.98 s [-0.1%; +2.0%] (no difference)
startup:petclinic:iast:Agent 16.52 s 16.70 s [-7.4%; +5.2%] (unstable)
startup:petclinic:profiling:Agent 16.73 s 16.73 s [-1.1%; +1.1%] (no difference)
startup:petclinic:sca:Agent 17.12 s 17.02 s [-0.3%; +1.4%] (no difference)
startup:petclinic:tracing:Agent 16.24 s 15.96 s [-2.4%; +5.9%] (no difference)

Commit: d0b77fa2 · 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.

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: experimental Experimental changes tag: performance Performance related changes type: feature Enhancements and improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant