Skip to content
Merged
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
43 changes: 43 additions & 0 deletions microbench/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,49 @@ Checking what benchmarks match the pattern:
java -jar microbench/build/libs/microbench-*-benchmarks.jar ".*BenchmarkName.*" -lp
```

### Redelivery tracker

`InMemoryRedeliveryTrackerBenchmark` measures the tracker shared by consumers of one subscription.
The `readOnly` workload covers empty trackers, hits, and misses. The `mixed` workload updates existing
positions at a fixed operation ratio, without resizing either map. The `acknowledge` workload measures
normal empty-tracker reads interleaved with `removeBatch`, including acknowledgements when no entry
has been redelivered. Positions and acknowledgement batches are allocated during setup.

Build a separate benchmark JAR from each tracker implementation being compared, using the same
benchmark source, JDK, heap, GC, and CPU allocation. The benchmark calls the tracker from that build;
it does not contain copies of alternative production implementations. All worker threads share one
tracker. For example, on JDK 21:

```bash
./gradlew :microbench:shadowJar

redelivery_jmh_args=(-f 2 -wi 3 -w 1s -i 5 -r 1s -prof gc -rf json
-jvmArgs "-Xms512m -Xmx512m -XX:+UseZGC -XX:+ZGenerational")

for redelivery_threads in 1 8; do
java -jar microbench/build/libs/microbench-*-benchmarks.jar \
'InMemoryRedeliveryTrackerBenchmark.readOnly$' "${redelivery_jmh_args[@]}" \
-t "$redelivery_threads" -p lookup=empty,hit \
-rff "redelivery-read-t${redelivery_threads}.json"
done

java -jar microbench/build/libs/microbench-*-benchmarks.jar \
'InMemoryRedeliveryTrackerBenchmark.mixed$' "${redelivery_jmh_args[@]}" \
-t 8 -p writePercent=1,10 -rff redelivery-mixed.json

java -jar microbench/build/libs/microbench-*-benchmarks.jar \
'InMemoryRedeliveryTrackerBenchmark.acknowledge$' "${redelivery_jmh_args[@]}" \
-t 8 -p batchSize=1,100 -rff redelivery-acknowledge.json
```

Save results separately for each implementation. `writePercent` counts write operations, rather
than writer threads. In `acknowledge`, each thread performs `batchSize` lookups followed by one batch
acknowledgement. One measured operation is a lookup or a batch acknowledgement, so compare results
at the same batch size. These are tracker microbenchmarks; use the concurrent regression tests for
map-resize correctness and a broker workload for end-to-end throughput and latency.

### Profiling with async-profiler

Profiling benchmarks with [async-profiler](https://github.com/async-profiler/async-profiler):

Set `LIBASYNCPROFILER_PATH` to the path of the async-profiler library.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.mledger.Position;
import org.apache.bookkeeper.mledger.PositionFactory;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

/**
* Measures the tracker used once per dispatched entry, including when no entry has been redelivered.
*
* <p>Run the same benchmark against each tracker implementation, with {@code -t 1}, {@code -t 4},
* and {@code -t 8}; all threads share one tracker, as consumers of one subscription do. Use
* {@code -prof gc} to measure allocation as well as throughput. For example:
* <pre>{@code
* ./gradlew :microbench:shadowJar
* java -jar microbench/build/libs/microbench-*-benchmarks.jar \
* InMemoryRedeliveryTrackerBenchmark.readOnly -t 8 -prof gc
* }</pre>
*
* <p>The mixed workload updates existing positions, so it does not resize either map or allocate
* positions during measurement. Its write percentages are operation ratios, rather than ratios of
* reader and writer threads. Map expansion correctness belongs in the concurrent regression tests;
* the original optimistic implementation is unsafe during structural changes.
*
* <p>The acknowledge workload interleaves an empty-tracker lookup for every entry with one
* {@code removeBatch} for every {@code batchSize} entries. This includes the normal acknowledgement
* path even when there are no redeliveries. One measured operation is either a lookup or a batch
* acknowledgement, so compare throughput only at the same batch size.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(3)
public class InMemoryRedeliveryTrackerBenchmark {
private static final int LEDGERS = 16;
private static final int ENTRIES_PER_LEDGER = 256;
private static final int POSITIONS = LEDGERS * ENTRIES_PER_LEDGER;

@State(Scope.Benchmark)
public static class ReadState {
@Param({"empty", "hit", "innerMiss", "outerMiss"})
public String lookup;

private InMemoryRedeliveryTracker tracker;
private long[] ledgerIds;
private long[] entryIds;

@Setup
public void setup() {
tracker = new InMemoryRedeliveryTracker();
Position[] positions = positions();
ledgerIds = new long[POSITIONS];
entryIds = new long[POSITIONS];
for (int i = 0; i < POSITIONS; i++) {
Position position = positions[i];
if (!"empty".equals(lookup)) {
tracker.incrementAndGetRedeliveryCount(position);
}
ledgerIds[i] = position.getLedgerId() + ("outerMiss".equals(lookup) ? LEDGERS : 0);
entryIds[i] = position.getEntryId() + ("innerMiss".equals(lookup) ? ENTRIES_PER_LEDGER : 0);
}
}
}

@State(Scope.Benchmark)
public static class MixedState {
@Param({"1", "10"})
public int writePercent;

private InMemoryRedeliveryTracker tracker;
private Position[] positions;

@Setup
public void setup() {
tracker = new InMemoryRedeliveryTracker();
positions = positions();
for (Position position : positions) {
tracker.incrementAndGetRedeliveryCount(position);
}
}
}

@State(Scope.Benchmark)
public static class AckState {
@Param({"1", "100"})
public int batchSize;

private InMemoryRedeliveryTracker tracker;
private Position[] positions;
private List<Position> ackBatch;

@Setup
public void setup() {
tracker = new InMemoryRedeliveryTracker();
positions = positions();
ackBatch = List.copyOf(Arrays.asList(positions).subList(0, batchSize));
}
}

@State(Scope.Thread)
public static class Cursor {
private int index;
private int operation;

int next() {
return index++ & (POSITIONS - 1);
}

boolean write(int percent) {
// Spread writes across each 100 operations rather than emitting them in a burst.
operation += percent;
if (operation >= 100) {
operation -= 100;
return true;
}
return false;
}

boolean acknowledge(int batchSize) {
if (++operation > batchSize) {
operation = 0;
return true;
}
return false;
}
}

@Benchmark
public int readOnly(ReadState state, Cursor cursor) {
int index = cursor.next();
return state.tracker.getRedeliveryCount(state.ledgerIds[index], state.entryIds[index]);
}

@Benchmark
public int mixed(MixedState state, Cursor cursor) {
Position position = state.positions[cursor.next()];
if (cursor.write(state.writePercent)) {
return state.tracker.incrementAndGetRedeliveryCount(position);
}
return state.tracker.getRedeliveryCount(position.getLedgerId(), position.getEntryId());
}

@Benchmark
public int acknowledge(AckState state, Cursor cursor) {
if (cursor.acknowledge(state.batchSize)) {
state.tracker.removeBatch(state.ackBatch);
return 0;
}
Position position = state.positions[cursor.next()];
return state.tracker.getRedeliveryCount(position.getLedgerId(), position.getEntryId());
}

private static Position[] positions() {
Position[] positions = new Position[POSITIONS];
for (int i = 0; i < positions.length; i++) {
positions[i] = PositionFactory.create(i / ENTRIES_PER_LEDGER, i % ENTRIES_PER_LEDGER);
}
return positions;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,13 @@ public int incrementAndGetRedeliveryCount(Position position) {

@Override
public int getRedeliveryCount(long ledgerId, long entryId) {
long stamp = rwLock.tryOptimisticRead();
Long2IntMap entryMap = trackerCache.get(ledgerId);
int count = entryMap != null ? entryMap.get(entryId) : 0;
if (!rwLock.validate(stamp)) {
stamp = rwLock.readLock();
try {
entryMap = trackerCache.get(ledgerId);
count = entryMap != null ? entryMap.get(entryId) : 0;
} finally {
rwLock.unlockRead(stamp);
}
long stamp = rwLock.readLock();
try {
Long2IntMap entryMap = trackerCache.get(ledgerId);
return entryMap != null ? entryMap.get(entryId) : 0;
} finally {
rwLock.unlockRead(stamp);
}
return count;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.service;

import static org.assertj.core.api.Assertions.assertThat;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.bookkeeper.mledger.Position;
import org.apache.bookkeeper.mledger.PositionFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@Test(groups = "broker")
public class InMemoryRedeliveryTrackerTest {

@DataProvider(name = "firstKey")
public Object[][] firstKey() {
// Cover both fastutil's special zero-key slot and its regular hash lookup path.
return new Object[][] {{0L}, {1L}};
}

@Test(dataProvider = "firstKey", timeOut = 30000)
Comment thread
lhotari marked this conversation as resolved.
Resolved
public void testReadDuringInnerMapExpansion(long firstKey) throws Exception {
assertReadDuringExpansion(false, firstKey);
}

@Test(dataProvider = "firstKey", timeOut = 30000)
public void testReadDuringOuterMapExpansion(long firstKey) throws Exception {
assertReadDuringExpansion(true, firstKey);
}

private static void assertReadDuringExpansion(boolean expandOuterMap, long firstKey) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2, new DefaultThreadFactory("redelivery-tracker-test"));
try {
for (int round = 0; round < 500; round++) {
InMemoryRedeliveryTracker tracker = new InMemoryRedeliveryTracker();
// Fill the default table to its first resize threshold using only normal tracker operations.
for (int key = 0; key < 24; key++) {
tracker.incrementAndGetRedeliveryCount(position(expandOuterMap, firstKey + key));
}
CyclicBarrier start = new CyclicBarrier(2);
AtomicBoolean writerDone = new AtomicBoolean();
Future<?> writer = executor.submit(() -> {
try {
start.await(10, TimeUnit.SECONDS);
for (int key = 24; key < 128; key++) {
tracker.incrementAndGetRedeliveryCount(position(expandOuterMap, firstKey + key));
}
} finally {
writerDone.set(true);
}
return null;
});
Future<?> reader = executor.submit(() -> {
start.await(10, TimeUnit.SECONDS);
Position existing = position(expandOuterMap, firstKey);
int reads = 0;
// Keep reading a position the writer never changes until all insertions are done.
do {
assertThat(tracker.getRedeliveryCount(existing.getLedgerId(), existing.getEntryId()))
.isEqualTo(1);
} while (++reads < 256 || !writerDone.get());
return null;
});
writer.get(10, TimeUnit.SECONDS);
reader.get(10, TimeUnit.SECONDS);
for (int key = 0; key < 128; key++) {
Position existing = position(expandOuterMap, firstKey + key);
assertThat(tracker.getRedeliveryCount(existing.getLedgerId(), existing.getEntryId()))
.isEqualTo(1);
}
}
} finally {
executor.shutdownNow();
assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
}
}

private static Position position(boolean expandOuterMap, long key) {
return expandOuterMap ? PositionFactory.create(key, 0) : PositionFactory.create(7, key);
}
}
Loading