Skip to content
Draft
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
197 changes: 197 additions & 0 deletions components/toolbox/src/main/java/datadog/trace/util/CompactList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
package datadog.trace.util;

import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
* An immutable list stored at its exact size, for small lists held in long-lived state: one shared
* empty list, a single object for one element, and the object plus one exact-size array for more.
* Elements may be {@code null}.
*
* <p>Long-lived state, such as a parsed configuration, stays in the old generation and every
* marking cycle walks it. When most of its lists hold zero or one element, an {@code ArrayList} and
* its array each is mostly overhead.
*
* <p>Walking one allocates nothing, as long as the walk's objects are short-lived:
*
* <ul>
* <li>Use one list class for a whole structure. A loop that sees several list classes (say {@code
* emptyList}, {@code singletonList} and {@code ArrayList}) goes megamorphic, and escape
* analysis keeps its iterators.
* <li>The iterator, {@code forEach} and {@code isEmpty} are this class's own, not {@code
* AbstractList}'s. That code is shared by every {@code AbstractList} subclass, so in an
* application its calls go megamorphic and its iterator escapes.
* <li>{@link #iterator()} and {@link #cursor()} return a new object on every path, the empty list
* included. A shared one on any path would make the result a merged allocation, which escape
* analysis can't remove.
* </ul>
*
* <p>Use {@link #forEach} to visit every element, a for-each loop where an {@code Iterator} is
* needed, and {@link #cursor()} for a walk that stops early or carries state in locals.
*
* @param <E> the element type
*/
public final class CompactList<E> extends AbstractList<E> implements RandomAccess {
private static final Object[] NO_MORE = new Object[0];
// The only list whose `more` is null, so the size needs no field of its own.
private static final CompactList<Object> EMPTY = new CompactList<>(null, null);

private final E first;
// The elements after the first: null for the empty list, NO_MORE for one element.
private final Object[] more;

private CompactList(final E first, final Object[] more) {
this.first = first;
this.more = more;
}

/**
* Gets the empty list, which is shared.
*
* @param <E> the element type
* @return the empty list.
*/
@SuppressWarnings("unchecked")
@Nonnull
public static <E> CompactList<E> empty() {
return (CompactList<E>) EMPTY;
}

/**
* Copies a collection, in its iteration order, at its exact size.
*
* @param <E> the element type
* @param elements the elements; {@code null} elements are kept.
* @return a compact list of the elements, or the shared empty list.
*/
@SuppressWarnings("unchecked")
@Nonnull
public static <E> CompactList<E> copyOf(@Nonnull final Collection<? extends E> elements) {
if (elements instanceof CompactList) {
return (CompactList<E>) elements;
}
final Object[] all = elements.toArray();
switch (all.length) {
case 0:
return empty();
case 1:
return new CompactList<>((E) all[0], NO_MORE);
default:
final Object[] rest = new Object[all.length - 1];
System.arraycopy(all, 1, rest, 0, rest.length);
return new CompactList<>((E) all[0], rest);
}
}

@Override
@SuppressWarnings("unchecked")
public E get(final int index) {
final Object[] rest = more; // read once: it also gives the size
final int size = rest == null ? 0 : rest.length + 1;
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds for length " + size);
}
return index == 0 ? first : (E) rest[index - 1];
}

@Override
public int size() {
return more == null ? 0 : more.length + 1;
}

@Override
public boolean isEmpty() {
return more == null;
}

@Override
@Nonnull
public Iterator<E> iterator() {
return new Itr<>(this);
}

/**
* Walks the elements in order without an {@code Iterator}'s look-ahead. {@code null} marks the
* end, so use it only on a list without {@code null} elements.
*
* @return a new cursor over this list.
*/
@Nonnull
public Cursor<E> cursor() {
return new Cur<>(this);
}

@Override
@SuppressWarnings("unchecked")
public void forEach(@Nonnull final Consumer<? super E> action) {
final Object[] rest = more;
if (rest == null) {
return;
}
action.accept(first);
for (final Object element : rest) {
action.accept((E) element);
}
}

/** The index walk the iterator and the cursor share; the list is immutable, so no modCount. */
private abstract static class Walk<E> {
private final CompactList<E> list;
final int size;
int next;

Walk(final CompactList<E> list) {
this.list = list;
this.size = list.size();
}

@SuppressWarnings("unchecked")
final E elementAt(final int index) {
return index == 0 ? list.first : (E) list.more[index - 1];
}
}

private static final class Itr<E> extends Walk<E> implements Iterator<E> {
Itr(final CompactList<E> list) {
super(list);
}

@Override
public boolean hasNext() {
return next < size;
}

@Override
public E next() {
final int index = next;
if (index >= size) {
throw new NoSuchElementException();
}
next = index + 1;
return elementAt(index);
}
}

private static final class Cur<E> extends Walk<E> implements Cursor<E> {
Cur(final CompactList<E> list) {
super(list);
}

@Override
@Nullable
public E next() {
final int index = next;
if (index >= size) {
return null;
}
next = index + 1;
return elementAt(index);
}
}
}
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
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,51 @@ public static final int hash(Object[] objs) {
}
return result;
}

/**
* A {@code hashCode} consistent with {@link String#equalsIgnoreCase}: any two strings that are
* equal ignoring case produce the same value. Same polynomial as {@link String#hashCode} but over
* the case-folded characters, so it never allocates (no {@code toLowerCase} copy).
*
* <p>Uses the same two-way fold {@code String.equalsIgnoreCase} / {@code
* String.regionMatches(ignoreCase)} use ({@code toLowerCase(toUpperCase(c))}), so the two stay
* consistent for all inputs, not just ASCII — pairing a one-way fold here with {@code
* equalsIgnoreCase} would risk silent false misses on the Unicode characters where they diverge.
*
* <p>Folds by code point, not by {@code char} (UTF-16 unit). On JDK 9+, {@code equalsIgnoreCase}
* itself reconstructs supplementary code points before folding (e.g. it treats U+10400 and
* U+10428 as equal), so a per-{@code char} fold would make this hash inconsistent with it for
* such pairs -- a supplementary-plane analog of the same silent-false-miss risk called out above.
* A per-{@code char} fold matched {@code equalsIgnoreCase} only on JDK 8, where it did not
* reconstruct code points; folding by code point keeps the two consistent on every supported JDK.
* (On JDK 8, where {@code equalsIgnoreCase} still treats such pairs as distinct, folding them
* together here is merely an extra, harmless collision -- consistency only needs to hold in the
* equal-hash direction, not the reverse.)
*/
public static int caseInsensitiveHashCode(String s) {
int h = 0;
final int len = s.length();
for (int i = 0; i < len; ) {
final char c = s.charAt(i);
if (c < 0x80) {
// ASCII fast path: case folding is exactly A-Z -> a-z, and every ASCII char is its own
// code point, so this is equivalent to (and cheaper than) the code-point fold below.
h = 31 * h + ((c >= 'A' && c <= 'Z') ? (c + 32) : c);
++i;
continue;
}
final int cp = s.codePointAt(i);
final int folded = Character.toLowerCase(Character.toUpperCase(cp));
if (Character.isSupplementaryCodePoint(folded)) {
// Fold back into the two chars equalsIgnoreCase itself compares, so the polynomial stays
// over the same "characters" for both single- and multi-char inputs.
h = 31 * h + Character.highSurrogate(folded);
h = 31 * h + Character.lowSurrogate(folded);
} else {
h = 31 * h + folded;
}
i += Character.charCount(cp);
}
return h;
}
}
Loading