Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/perf-review/references/posture.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ mechanism is certain or the severity is catastrophic.
toolkit primitive — no visible downside); or a change that **ships a benchmark/JFR**
(well-evidenced — recognize it). One line; a nudge, not a code-pattern finding.
- **Shipped core code is stricter — see the core performance rules in `AGENTS.md`.**
For changes to `dd-trace-core/src/main/` or `internal-api/src/main/`: a performance claim
For changes to `dd-trace-core/src/main/`, `internal-api/src/main/` or `components/toolbox/src/main/`: a performance claim
(in the title, description, or commits) without JMH before/after numbers is a finding, not
a soft nudge. Elsewhere, including those modules' tests, benchmarks and build files, keep
the softer posture above.
Expand Down
12 changes: 7 additions & 5 deletions .agents/skills/perf-review/references/remedies.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ see `../SKILL.md`) is unchanged.**

## Toolkit availability — cite only what exists

Available today: `Strings`, `SubSequence`, `HashingUtils`, `Hashtable`, `ChunkedBuffer`
Available today: `Strings`, `SubSequence`, `HashingUtils`, `Hashtable`, `FlatHashtable`,
`ConcurrentHashtable`, `StringIndex` (immutable string set/map), `ChunkedBuffer`
(+ `ChunkedStreamingBuffer` in `datadog.communication.serialization`),
`BenchmarkUtils.warmUpHashDispatch(Blackhole)` for JMH setup (all `datadog.trace.util` unless
noted), `RE2J` (`com.google.re2j`).
noted), `RE2J` (`com.google.re2j`). The `datadog.trace.util` primitives live in
`components/toolbox`, which has no dependencies, so standalone SDKs can shade them.

Coming (name as "coming", don't imply it's present): `ConcurrentHashtable`, `StringIndex`
(immutable string set/map), `UTF8BytesString.Cache` (recurring-string interner), wider
`IntegerCache` (http-status/port boxing), `DDCache` inlining.
Coming (name as "coming", don't imply it's present): `StringCanonicalizer` (per-parse string
sharing), `LruTable` (allocation-free bounded LRU), `UTF8BytesString.Cache` (recurring-string
interner), wider `IntegerCache` (http-status/port boxing), `DDCache` inlining.

## Routes

Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ docs/ Developer documentation (see below)

### Core performance rules

These rules are strict for shipped runtime code in `dd-trace-core/src/main/` and `internal-api/src/main/`. Elsewhere, including those modules' tests, benchmarks and build files, treat them as advice.
These rules are strict for shipped runtime code in `dd-trace-core/src/main/`, `internal-api/src/main/` and `components/toolbox/src/main/`. Elsewhere, including those modules' tests, benchmarks and build files, treat them as advice.

- **Measure performance claims.** A PR that claims to be faster or to allocate less must include JMH before/after results from the same machine, JDK, JVM flags and benchmark settings, with time and allocation (`-Pjmh.profilers=gc`). Without them, reviewers should flag the claim as unmeasured and the author should either add numbers or drop the claim.

Expand Down
13 changes: 13 additions & 0 deletions components/toolbox/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
plugins {
id("dd-trace-java.module.platform-component")
}

description = "Dependency-free performance primitives: flat hashtables, chunked buffers, hashing."

// The thresholds these classes had in internal-api, so moving them doesn't change what's enforced.
extra["minimumBranchCoverage"] = 0.7
extra["minimumInstructionCoverage"] = 0.8

dependencies {
testImplementation(libs.bundles.junit5)
}
75 changes: 75 additions & 0 deletions components/toolbox/gradle.lockfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
# To regenerate this file, run: ./gradlew :components:toolbox:dependencies --write-locks
ch.qos.logback:logback-classic:1.2.13=testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.2.13=testCompileClasspath,testRuntimeClasspath
com.github.javaparser:javaparser-core:3.25.6=codenarc
com.github.spotbugs:spotbugs-annotations:4.10.4=compileClasspath,spotbugs
com.github.spotbugs:spotbugs:4.10.4=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.code.findbugs:jsr305:3.0.2=compileClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath
com.google.code.gson:gson:2.14.0=spotbugs
com.google.errorprone:error_prone_annotations:2.48.0=spotbugs
com.thoughtworks.qdox:qdox:1.12.1=codenarc
commons-io:commons-io:2.21.0=spotbugs
de.thetaphi:forbiddenapis:3.11=compileClasspath
io.leangen.geantyref:geantyref:1.3.16=testRuntimeClasspath
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.12.8=testRuntimeClasspath
net.bytebuddy:byte-buddy:1.12.8=testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.10=spotbugs
org.apache.ant:ant-antlr:1.10.14=codenarc
org.apache.ant:ant-junit:1.10.14=codenarc
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.logging.log4j:log4j-api:2.26.1=spotbugs
org.apache.logging.log4j:log4j-core:2.26.1=spotbugs
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.codehaus.groovy:groovy-ant:3.0.23=codenarc
org.codehaus.groovy:groovy-docgenerator:3.0.23=codenarc
org.codehaus.groovy:groovy-groovydoc:3.0.23=codenarc
org.codehaus.groovy:groovy-json:3.0.23=codenarc
org.codehaus.groovy:groovy-json:3.0.25=testCompileClasspath,testRuntimeClasspath
org.codehaus.groovy:groovy-templates:3.0.23=codenarc
org.codehaus.groovy:groovy-xml:3.0.23=codenarc
org.codehaus.groovy:groovy:3.0.23=codenarc
org.codehaus.groovy:groovy:3.0.25=testCompileClasspath,testRuntimeClasspath
org.codenarc:CodeNarc:3.7.0=codenarc
org.dom4j:dom4j:2.2.0=spotbugs
org.gmetrics:GMetrics:2.1.0=codenarc
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.jacoco:org.jacoco.agent:0.8.15=jacocoAgent,jacocoAnt
org.jacoco:org.jacoco.ant:0.8.15=jacocoAnt
org.jacoco:org.jacoco.core:0.8.15=jacocoAnt
org.jacoco:org.jacoco.report:0.8.15=jacocoAnt
org.junit.jupiter:junit-jupiter-api:5.14.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:5.14.1=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:5.14.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:5.14.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:1.14.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:1.14.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-launcher:1.14.1=testRuntimeClasspath
org.junit:junit-bom:5.14.1=testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-core:4.4.0=testRuntimeClasspath
org.objenesis:objenesis:3.3=testCompileClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=jacocoAnt,spotbugs
org.ow2.asm:asm-tree:9.10.1=jacocoAnt,spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=jacocoAnt,spotbugs
org.slf4j:jcl-over-slf4j:1.7.30=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:1.7.30=testCompileClasspath,testRuntimeClasspath
org.slf4j:log4j-over-slf4j:1.7.30=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:1.7.32=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-api:2.0.18=spotbugs
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.spockframework:spock-bom:2.4-groovy-3.0=testCompileClasspath,testRuntimeClasspath
org.spockframework:spock-core:2.4-groovy-3.0=testCompileClasspath,testRuntimeClasspath
org.tabletest:tabletest-junit:1.2.2=testCompileClasspath,testRuntimeClasspath
org.tabletest:tabletest-parser:1.2.1=testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=spotbugs
empty=annotationProcessor,runtimeClasspath,spotbugsPlugins,testAnnotationProcessor
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ public abstract static class EntryStrategy<E, K>

/**
* {@link EntryStrategy} for {@code String} keys compared case-insensitively: seals {@link
* #hashKey} to {@link Strings#caseInsensitiveHashCode} (consistent with {@link
* #hashKey} to {@link HashingUtils#caseInsensitiveHashCode} (consistent with {@link
* String#equalsIgnoreCase}, which callers use in {@link #matches}). Callers still supply {@link
* #matches} (typically {@code key.equalsIgnoreCase(entry.key)}) and {@link #hashOf} (the same
* case-insensitive hash of the entry's key, or the cached {@link Entry#hash}).
Expand All @@ -646,7 +646,7 @@ public abstract static class EntryStrategy<E, K>
public abstract static class CaseInsensitiveStringStrategy<E> extends EntryStrategy<E, String> {
@Override
public final long hashKey(String key) {
return Strings.caseInsensitiveHashCode(key); // raw; the table spreads before masking
return HashingUtils.caseInsensitiveHashCode(key); // raw; the table spreads before masking
}
}

Expand Down
251 changes: 251 additions & 0 deletions components/toolbox/src/main/java/datadog/trace/util/FrozenMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
package datadog.trace.util;

import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
* A read-only {@link Map} built once and then only read, held in flat arrays instead of one node
* per entry.
*
* <p>Reach for it where many small maps are built once and retained, such as the objects of a
* parsed document: against a {@link java.util.HashMap} behind an unmodifiable wrapper, it drops the
* node per entry, the table and the wrapper, about 8 B per entry plus the arrays' headers instead
* of about 40 B per entry plus some 80 B per map. Unlike {@link Map#copyOf}, it keeps the iteration
* order of the map it copies, and {@code get(null)} misses instead of throwing.
*
* <p>Keys and values sit in two parallel arrays, in the source map's iteration order. Up to {@value
* #MAX_SCANNED} entries, a lookup scans the keys, with no hashing; a larger map adds an
* open-addressed {@code int[]} index into the arrays, at most half full.
*
* <p>The views ({@link #entrySet}, {@link #keySet}, {@link #values}) are created on each call and
* never cached, so a retained map holds no view objects (a {@code HashMap} keeps each view it has
* handed out). {@link #forEach} walks the arrays without allocating; prefer it to iterating {@link
* #entrySet}, which creates an entry per element.
*
* <p>Null keys are rejected; null values are allowed. Immutable, so safe to share across threads
* once published.
*
* @param <K> the key type
* @param <V> the value type
*/
public final class FrozenMap<K, V> extends AbstractMap<K, V> {
/**
* Up to this many entries, a lookup scans the keys instead of hashing. {@code
* FrozenMapScanBenchmark} puts the crossover here: scanning clearly wins up to 3 entries, ties at
* 4, where skipping the index saves its array, and loses from 6.
*/
public static final int MAX_SCANNED = 4;

private static final FrozenMap<?, ?> EMPTY = new FrozenMap<>(new Object[0], new Object[0], null);

private final Object[] keys;
private final Object[] values;
// Slots hold an entry's position plus one; zero is empty. Null for a scanned map.
@Nullable private final int[] index;

private FrozenMap(final Object[] keys, final Object[] values, @Nullable final int[] index) {
this.keys = keys;
this.values = values;
this.index = index;
}

/** Copies the entries of {@code source}, in its iteration order. */
@SuppressWarnings("unchecked")
@Nonnull
public static <K, V> FrozenMap<K, V> copyOf(@Nonnull final Map<? extends K, ? extends V> source) {
return copyOf(source, MAX_SCANNED);
}

/** {@link #copyOf(Map)} with a given scan threshold, for benchmarks. */
@SuppressWarnings("unchecked")
static <K, V> FrozenMap<K, V> copyOf(
final Map<? extends K, ? extends V> source, final int maxScanned) {
final int size = source.size();
if (size == 0) {
return (FrozenMap<K, V>) EMPTY;
}
final Object[] keys = new Object[size];
final Object[] values = new Object[size];
int i = 0;
for (final Map.Entry<? extends K, ? extends V> entry : source.entrySet()) {
keys[i] = Objects.requireNonNull(entry.getKey(), "null key");
values[i] = entry.getValue();
i++;
}
return new FrozenMap<>(keys, values, size > maxScanned ? index(keys) : null);
}

private static int[] index(final Object[] keys) {
final int[] index = new int[Integer.highestOneBit(keys.length) << 2];
final int mask = index.length - 1;
for (int i = 0; i < keys.length; i++) {
int slot = slot(keys[i].hashCode(), mask);
while (index[slot] != 0) {
slot = (slot + 1) & mask;
}
index[slot] = i + 1;
}
return index;
}

private static int slot(final int hash, final int mask) {
final int spread = hash * 0x9E3779B9;
return (spread ^ (spread >>> 15)) & mask;
}

private int find(@Nullable final Object key) {
if (key == null) {
return -1;
}
final int[] index = this.index;
if (index == null) {
final Object[] keys = this.keys;
for (int i = 0; i < keys.length; i++) {
if (keys[i].equals(key)) {
return i;
}
}
return -1;
}
final int mask = index.length - 1;
for (int slot = slot(key.hashCode(), mask); ; slot = (slot + 1) & mask) {
final int position = index[slot] - 1;
if (position < 0) {
return -1;
}
if (keys[position].equals(key)) {
return position;
}
}
}

@SuppressWarnings("unchecked")
@Override
public V get(@Nullable final Object key) {
final int i = find(key);
return i < 0 ? null : (V) values[i];
}

@Override
public boolean containsKey(@Nullable final Object key) {
return find(key) >= 0;
}

@Override
public int size() {
return keys.length;
}

@Override
public boolean isEmpty() {
return keys.length == 0;
}

@SuppressWarnings("unchecked")
@Override
public void forEach(@Nonnull final BiConsumer<? super K, ? super V> action) {
final Object[] keys = this.keys;
final Object[] values = this.values;
for (int i = 0; i < keys.length; i++) {
action.accept((K) keys[i], (V) values[i]);
}
}

@Override
public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override
public Iterator<Entry<K, V>> iterator() {
return new Positions<Entry<K, V>>() {
@SuppressWarnings("unchecked")
@Override
Entry<K, V> at(final int i) {
return new SimpleImmutableEntry<>((K) keys[i], (V) values[i]);
}
};
}

@Override
public int size() {
return keys.length;
}
};
}

@Override
public Set<K> keySet() {
return new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return new Positions<K>() {
@SuppressWarnings("unchecked")
@Override
K at(final int i) {
return (K) keys[i];
}
};
}

@Override
public boolean contains(final Object key) {
return containsKey(key);
}

@Override
public int size() {
return keys.length;
}
};
}

@Override
public Collection<V> values() {
return new AbstractCollection<V>() {
@Override
public Iterator<V> iterator() {
return new Positions<V>() {
@SuppressWarnings("unchecked")
@Override
V at(final int i) {
return (V) values[i];
}
};
}

@Override
public int size() {
return keys.length;
}
};
}

/** Walks the entries' positions in order; read-only. */
private abstract class Positions<T> implements Iterator<T> {
private int next;

abstract T at(int i);

@Override
public boolean hasNext() {
return next < keys.length;
}

@Override
public T next() {
if (next >= keys.length) {
throw new NoSuchElementException();
}
return at(next++);
}
}
}
Loading