kevin-wu24 commented on code in PR #22669:
URL: https://github.com/apache/kafka/pull/22669#discussion_r3507168086


##########
raft/src/testFixtures/java/org/apache/kafka/raft/RaftClientBenchmarkContext.java:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.kafka.raft;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientTestContext.RaftProtocol;
+import org.apache.kafka.server.common.KRaftVersion;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.IntSupplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public final class RaftClientBenchmarkContext {
+    // Standardized JMH iteration counts, shared by all raft benchmarks so 
every benchmark of a given
+    // mode is configured identically.
+
+    // SingleShotTime measures a single operation per iteration, so it needs 
many iterations to build
+    // a stable distribution.
+    public static final int SINGLE_SHOT_WARMUP_ITERATIONS = 50;
+    public static final int SINGLE_SHOT_MEASUREMENT_ITERATIONS = 30;
+    public static final int SINGLE_SHOT_FORKS = 5;
+
+    // AverageTime averages many operations within each timed iteration, so it 
needs fewer.
+    public static final int AVERAGE_TIME_WARMUP_ITERATIONS = 5;
+    public static final int AVERAGE_TIME_MEASUREMENT_ITERATIONS = 10;
+    public static final int AVERAGE_TIME_FORKS = 3;
+
+    // Default to the newest version of each (the highest-ordinal enum 
constant). Enum natural order
+    // is ordinal order, so this picks the last-declared constant; relies on 
the constants being
+    // declared oldest-to-newest, which avoids updating these when a new 
version is added.
+    public static final KRaftVersion DEFAULT_KRAFT_VERSION =
+        
Arrays.stream(KRaftVersion.values()).max(Comparator.naturalOrder()).orElseThrow();
+    public static final RaftProtocol DEFAULT_RAFT_PROTOCOL =
+        
Arrays.stream(RaftProtocol.values()).max(Comparator.naturalOrder()).orElseThrow();
+
+    private final RaftClientTestContext context;
+    private final MockLog log;
+    private final MockNetworkChannel channel;
+    private final List<ReplicaKey> voters;
+
+    // Each tracks one cumulative mock counter as a drainable delta against a 
baseline. The baseline is
+    // reset by zeroCountersOnSetup() at the end of benchmark setup.
+    private final DrainableCounter logFlushes;
+    private final DrainableCounter logReads;
+    private final DrainableCounter logTruncations;
+    private final DrainableCounter rpcRequestsSent;
+    private final DrainableCounter quorumStateWrites;
+    private final DrainableCounter quorumStateReads;
+
+    private RaftClientBenchmarkContext(RaftClientTestContext context, 
List<ReplicaKey> voters) {
+        this.context = context;
+        this.log = context.log;
+        this.channel = context.channel;
+        this.voters = List.copyOf(voters);
+        this.logFlushes = new DrainableCounter(log::flushCount);
+        this.logReads = new DrainableCounter(log::readCount);
+        this.logTruncations = new DrainableCounter(log::truncationCount);
+        this.rpcRequestsSent = new DrainableCounter(channel::requestsSent);
+        this.quorumStateWrites = new 
DrainableCounter(context::quorumStateWriteCount);
+        this.quorumStateReads = new 
DrainableCounter(context::quorumStateReadCount);
+    }
+
+    /**
+     * Builds a local, unattached node in a {@code voterCount}-node cluster 
(the local node is not yet
+     * the leader). Use {@link RaftClientTestContext#unattachedToLeader()} on 
{@link #testContext()} as
+     * the measured operation to drive a full Unattached &rarr; Leader 
election. A single-voter cluster
+     * is rejected because such a node elects itself at initialization, before 
any measured poll.
+     */
+    public static RaftClientBenchmarkContext unattached(int voterCount) throws 
Exception {
+        return unattached(voterCount, DEFAULT_KRAFT_VERSION, 
DEFAULT_RAFT_PROTOCOL);
+    }
+
+    public static RaftClientBenchmarkContext unattached(
+        int voterCount,
+        KRaftVersion kraftVersion,
+        RaftProtocol raftProtocol
+    ) throws Exception {
+        if (voterCount < 2) {
+            throw new IllegalArgumentException("voterCount must be at least 2; 
a single voter self-elects at init");
+        }
+        List<ReplicaKey> voterKeys = voterKeys(voterCount);
+        return new RaftClientBenchmarkContext(buildContext(voterKeys, 
kraftVersion, raftProtocol), voterKeys);
+    }
+
+    public static RaftClientBenchmarkContext leader(int voterCount) throws 
Exception {
+        return leader(voterCount, DEFAULT_KRAFT_VERSION, 
DEFAULT_RAFT_PROTOCOL);
+    }
+
+    public static RaftClientBenchmarkContext leader(
+        int voterCount,
+        KRaftVersion kraftVersion,
+        RaftProtocol raftProtocol
+    ) throws Exception {
+        List<ReplicaKey> voterKeys = voterKeys(voterCount);
+        RaftClientTestContext context = buildContext(voterKeys, kraftVersion, 
raftProtocol);
+        context.unattachedToLeader();
+
+        return new RaftClientBenchmarkContext(context, voterKeys);
+    }
+
+    /**
+     * {@code voterCount} voter keys, each with a random directory id, with 
the local node first.
+     */
+    private static List<ReplicaKey> voterKeys(int voterCount) {
+        int localId = randomReplicaId();
+        return IntStream.range(0, voterCount)
+            .mapToObj(i -> ReplicaKey.of(localId + i, Uuid.randomUuid()))
+            .collect(Collectors.toList());
+    }
+
+    private static int randomReplicaId() {
+        return ThreadLocalRandom.current().nextInt(1025);
+    }
+
+    /**
+     * Initializes a local, unattached node in a cluster of {@code voterKeys} 
(first entry is the local
+     * node).
+     */
+    private static RaftClientTestContext buildContext(
+        List<ReplicaKey> voterKeys,
+        KRaftVersion kraftVersion,
+        RaftProtocol raftProtocol
+    ) throws Exception {
+        ReplicaKey local = voterKeys.get(0);
+        VoterSet voters = VoterSetTestUtil.voterSet(voterKeys.stream());
+
+        return new RaftClientTestContext.Builder(local.id(), 
local.directoryId().get())
+            .withStartingVoters(voters, kraftVersion)
+            .withRaftProtocol(raftProtocol)
+            .withPollIntervalMs(0)
+            .withUnknownLeader(0)
+            .build();
+    }
+
+    public RaftClientTestContext testContext() {
+        return context;
+    }
+
+    /** The local node's log end offset. Kept here because the {@code log} 
field is package-private. */
+    public long logEndOffset() {
+        return log.endOffset().offset();
+    }
+
+    /**
+     * The voters other than the local node, in voter-set order. May be empty 
(single-voter cluster).
+     * Use these as the source of delivered requests, e.g. a FETCH from a 
follower on the leader.
+     */
+    public List<ReplicaKey> remoteVoters() {
+        return voters.subList(1, voters.size());
+    }
+
+    /**
+     * Establishes the counter baseline so that work done before this point 
(building the context,
+     * driving an election in {@code leader()}, or anything else a benchmark 
does in its setup) is not
+     * attributed to the measured operation. Call this at the <b>end of 
benchmark setup</b>, just
+     * before the measured region begins.
+     */
+    public void zeroCountersOnSetup() {
+        logFlushes.reset();
+        logReads.reset();
+        logTruncations.reset();
+        rpcRequestsSent.reset();
+        quorumStateWrites.reset();
+        quorumStateReads.reset();
+        channel.drainSendQueue();
+        context.drainAllSentResponses();
+    }
+
+    public int getLogFlushesDelta() {
+        return logFlushes.delta();
+    }
+
+    public int getLogReadsDelta() {
+        return logReads.delta();
+    }
+
+    public int getLogTruncationsDelta() {
+        return logTruncations.delta();
+    }
+
+    /**
+     * Total number of requests (all API keys) the client has sent since the 
last call. Uses the
+     * channel's cumulative counter, so it is unaffected by a test driver 
draining the send queue.
+     */
+    public int getRpcRequestsSentDelta() {
+        return rpcRequestsSent.delta();
+    }
+
+    /**
+     * Drains the requests the benchmark expects to be in-flight at the end of 
the invocation (the
+     * given {@code expectedRequest} API key, if any) and asserts the send 
queue is then empty. A
+     * non-empty queue means the client sent more requests than the benchmark 
accounts for.
+     */
+    public void drainExpectedRequestsAndAssertEmpty(Optional<ApiKeys> 
expectedRequest) {
+        expectedRequest.ifPresent(apiKey -> 
channel.drainSentRequests(Optional.of(apiKey)));
+        if (channel.hasSentRequests()) {
+            throw new IllegalStateException(
+                "Unexpected outstanding requests at end of benchmark 
invocation: " + channel.drainSendQueue());
+        }
+    }
+
+    public int getQuorumStateWritesDelta() {
+        return quorumStateWrites.delta();
+    }
+
+    public int getQuorumStateReadsDelta() {
+        return quorumStateReads.delta();
+    }
+
+    /**
+     * Drains the responses the benchmark expects to be in-flight at the end 
of the invocation (the
+     * given {@code apiKey}, if any), counts them, then asserts no other 
responses remain. Returns the
+     * number of expected responses drained (0 if none are expected). A 
leftover response means the
+     * client sent more than the benchmark accounts for.
+     */
+    public int maybeDrainSentRpcResponses(Optional<ApiKeys> apiKey) {
+        int expected = apiKey.map(key -> 
context.drainSentResponses(key).size()).orElse(0);
+        int remaining = context.drainAllSentResponses();
+        if (remaining > 0) {
+            throw new IllegalStateException(
+                "Unexpected outstanding responses at end of benchmark 
invocation: " + remaining);
+        }
+        return expected;
+    }
+
+    /**
+     * Tracks one cumulative mock counter as a delta against a baseline. 
{@link #reset()} snapshots the
+     * current value (so the next {@link #delta()} starts from zero), and 
{@link #delta()} returns the
+     * increase since the last reset/delta and advances the baseline.
+     */
+    private static final class DrainableCounter {

Review Comment:
   I like the idea of this class to reduce duplication. However, let's make 
sure we have unit tests for it.



##########
raft/src/testFixtures/java/org/apache/kafka/raft/RaftClientBenchmarkContext.java:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.kafka.raft;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientTestContext.RaftProtocol;
+import org.apache.kafka.server.common.KRaftVersion;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.IntSupplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public final class RaftClientBenchmarkContext {
+    // Standardized JMH iteration counts, shared by all raft benchmarks so 
every benchmark of a given
+    // mode is configured identically.
+
+    // SingleShotTime measures a single operation per iteration, so it needs 
many iterations to build
+    // a stable distribution.
+    public static final int SINGLE_SHOT_WARMUP_ITERATIONS = 50;
+    public static final int SINGLE_SHOT_MEASUREMENT_ITERATIONS = 30;
+    public static final int SINGLE_SHOT_FORKS = 5;
+
+    // AverageTime averages many operations within each timed iteration, so it 
needs fewer.
+    public static final int AVERAGE_TIME_WARMUP_ITERATIONS = 5;
+    public static final int AVERAGE_TIME_MEASUREMENT_ITERATIONS = 10;
+    public static final int AVERAGE_TIME_FORKS = 3;
+
+    // Default to the newest version of each (the highest-ordinal enum 
constant). Enum natural order
+    // is ordinal order, so this picks the last-declared constant; relies on 
the constants being
+    // declared oldest-to-newest, which avoids updating these when a new 
version is added.
+    public static final KRaftVersion DEFAULT_KRAFT_VERSION =
+        
Arrays.stream(KRaftVersion.values()).max(Comparator.naturalOrder()).orElseThrow();
+    public static final RaftProtocol DEFAULT_RAFT_PROTOCOL =
+        
Arrays.stream(RaftProtocol.values()).max(Comparator.naturalOrder()).orElseThrow();
+
+    private final RaftClientTestContext context;
+    private final MockLog log;
+    private final MockNetworkChannel channel;
+    private final List<ReplicaKey> voters;

Review Comment:
   A note for you to think about, since this state may not be enough as we 
write more benchmarks: 
   
   Currently, all benchmarks written have had the property of all nodes in the 
"cluster" being voters. This is not going to hold as we write more benchmarks, 
and is not true of production KRaft deployments. For example, what if we want 
to benchmark how a leader handles fetch from an observer? The behavior may be 
different in some cases because observer fetch offsets are not considered in 
HWM calculation. 
   
   Representing the membership of the KRaft cluster well in the benchmarks may 
be challenging, since KIP-853 makes it so observer controllers can become 
voters and vice versa. That is why the unit tests actually refer to their 
representation of the voters as the `startingVoters`, since this state can 
actually be "incorrect" once the local node's voter set changes.
   
   As for a suggestion, I think we can start with an additional observer 
replica key list, and see when/if that bites us later. 



##########
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/raft/KRaftBenchmarkingCounters.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.kafka.jmh.raft;
+
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientBenchmarkContext;
+
+import org.openjdk.jmh.annotations.AuxCounters;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.infra.BenchmarkParams;
+
+import java.util.Optional;
+
+/**
+ * Secondary, machine-independent work counters reported by the raft 
benchmarks alongside the timing
+ * score, as {@code benchmark:counter} rows.
+ *
+ * <p>Throughout this class, an <em>operation</em> is JMH's unit of work: a 
single invocation of a
+ * {@code @Benchmark}-annotated method. (One operation equals one invocation 
here because we don't use
+ * {@code @OperationsPerInvocation}.) JMH reports the timing score in {@code 
ns/op}, and these work
+ * counters are reported {@code PerOp} to match.
+ *
+ * <p>Each benchmark calls {@link #collectDeltasAndDrainRPCs} every invocation 
to accumulate the work deltas drained
+ * from {@link RaftClientBenchmarkContext}. The raw totals are private 
accumulators; what we report
+ * are the per-operation values from the {@code *PerOp()} methods (the 
quantity of interest), plus
+ * {@link #operations}.
+ *
+ * <p>JMH aggregates {@code Type.EVENTS} secondary results with {@code SUM} 
across all measurement
+ * data points i.e {@code forks x measurement iterations}. To make the 
<em>summary</em> row
+ * report the true per-operation value rather than that value multiplied by 
the data-point count, each
+ * method pre-divides by the data-point count obtained from {@link 
BenchmarkParams} in
+ * {@link #captureRunShape}. The SUM then reconstitutes the exact 
per-operation value (e.g.
+ * {@code logReadsPerOp = 1.0}) in the summary, for any {@code -f}/{@code -i} 
configuration. (The
+ * per-iteration console values are correspondingly a small fraction of the 
per-op value; read the
+ * summary row.)

Review Comment:
   This paragraph is pretty confusing to me. I assume it is to document what 
was discussed here: 
https://github.com/apache/kafka/pull/22669#discussion_r3496284459? Perhaps this 
information should go above the `captureRunShape` method instead of for the 
whole class. I would consider this functionality a nitty-gritty implementation 
detail that users of this class shouldn't need to read unless they are working 
on that code specifically.
   
   As a reader of a class' documentation, my opinion is that the most important 
questions are: What is this class used for, and what does it do at a very high 
level? I think the remaining paragraphs are trying to answer those questions 
(i.e. this class contains non-time measurements of KRaft, which are needed to 
detect performance regressions), but the two paragraphs I highlighted are not. 
For example, take a look at `KRaftControlRecordStateMachine`'s documentation. 
Complicated parts of a class' implementation that need documentation for future 
readers should be documented in-line/at the method level, rather than the class 
level.



##########
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/raft/KRaftBenchmarkingCounters.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.kafka.jmh.raft;
+
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientBenchmarkContext;
+
+import org.openjdk.jmh.annotations.AuxCounters;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.infra.BenchmarkParams;
+
+import java.util.Optional;
+
+/**
+ * Secondary, machine-independent work counters reported by the raft 
benchmarks alongside the timing
+ * score, as {@code benchmark:counter} rows.
+ *
+ * <p>Throughout this class, an <em>operation</em> is JMH's unit of work: a 
single invocation of a
+ * {@code @Benchmark}-annotated method. (One operation equals one invocation 
here because we don't use
+ * {@code @OperationsPerInvocation}.) JMH reports the timing score in {@code 
ns/op}, and these work
+ * counters are reported {@code PerOp} to match.
+ *
+ * <p>Each benchmark calls {@link #collectDeltasAndDrainRPCs} every invocation 
to accumulate the work deltas drained
+ * from {@link RaftClientBenchmarkContext}. The raw totals are private 
accumulators; what we report
+ * are the per-operation values from the {@code *PerOp()} methods (the 
quantity of interest), plus
+ * {@link #operations}.
+ *
+ * <p>JMH aggregates {@code Type.EVENTS} secondary results with {@code SUM} 
across all measurement
+ * data points i.e {@code forks x measurement iterations}. To make the 
<em>summary</em> row
+ * report the true per-operation value rather than that value multiplied by 
the data-point count, each
+ * method pre-divides by the data-point count obtained from {@link 
BenchmarkParams} in
+ * {@link #captureRunShape}. The SUM then reconstitutes the exact 
per-operation value (e.g.
+ * {@code logReadsPerOp = 1.0}) in the summary, for any {@code -f}/{@code -i} 
configuration. (The
+ * per-iteration console values are correspondingly a small fraction of the 
per-op value; read the
+ * summary row.)
+ *
+ * <p>The per-operation values are integer-exact and should be stable across a 
correct refactor of
+ * {@code KafkaRaftClient}: a flush count moving from 1 to 2 per operation is 
a behavioral diff, not
+ * measurement noise. The counters that are zero on a path (e.g. log flushes 
on a caught-up fetch)
+ * are the most useful tripwires, since zero is speed-independent.
+ */
+@State(Scope.Thread)
+@AuxCounters(AuxCounters.Type.EVENTS)
+public class KRaftBenchmarkingCounters {
+    // Private accumulators: not reported directly (we report the per-op 
values below). Being private,
+    // JMH does not touch them between iterations, so reset() must zero them.
+    private long logFlushesTotal;
+    private long logReadsTotal;
+    private long logTruncationsTotal;
+    private long rpcRequestsSentTotal;
+    private long rpcResponsesSentTotal;
+    private long quorumStateWritesTotal;
+    private long quorumStateReadsTotal;
+
+    // Reported: the number of operations (i.e. @Benchmark method invocations) 
measured in the
+    // iteration, and the divisor for the per-operation values below. Being a 
public @AuxCounters
+    // field, JMH zeroes it automatically at the start of every iteration 
(which is why, unlike the
+    // private totals above, it is not reset in reset()).
+    public long operations;
+
+    // The number of measurement data points JMH will SUM the per-op methods 
over, i.e.
+    // (forks x measurement iterations) for this run. Captured from 
BenchmarkParams so it tracks the
+    // actual run shape (including -f/-i overrides) rather than being 
hardcoded.
+    private double measurementDataPoints = 1.0;
+
+    @Setup(Level.Trial)
+    public void captureRunShape(BenchmarkParams params) {
+        // forks() is 0 when forking is disabled (in-process), which is still 
one set of iterations.
+        int forks = Math.max(1, params.getForks());
+        measurementDataPoints = (double) forks * 
params.getMeasurement().getCount();
+    }
+
+    @Setup(Level.Iteration)
+    public void reset() {
+        logFlushesTotal = 0;
+        logReadsTotal = 0;
+        logTruncationsTotal = 0;
+        rpcRequestsSentTotal = 0;
+        rpcResponsesSentTotal = 0;
+        quorumStateWritesTotal = 0;
+        quorumStateReadsTotal = 0;
+    }
+
+    /**
+     * Accumulates this invocation's work deltas drained from {@code context} 
into these counters.
+     *
+     * <p>{@code expectedRequest}/{@code expectedResponse} declare the 
request/response API key the
+     * benchmark expects to still be in-flight at the end of the invocation. 
Those expected messages are
+     * drained, then the send queue / response list is asserted empty — 
anything left over is something
+     * the client sent that the benchmark didn't account for, which fails fast 
instead of silently
+     * inflating a count. An <b>empty</b> {@code Optional} therefore means "no 
outstanding
+     * requests/responses are expected at the end of the invocation," so any 
leftover fails assert.
+     *
+     * <p>The reported request count is always the total across all API keys 
(from the channel's
+     * cumulative counter); the reported response count is the number of 
expected responses drained.

Review Comment:
   I don't think this comment is relevant anymore after we removed that map 
that stores request count by api key right?



##########
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/raft/KRaftBenchmarkingCounters.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.kafka.jmh.raft;
+
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientBenchmarkContext;
+
+import org.openjdk.jmh.annotations.AuxCounters;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.infra.BenchmarkParams;
+
+import java.util.Optional;
+
+/**
+ * Secondary, machine-independent work counters reported by the raft 
benchmarks alongside the timing
+ * score, as {@code benchmark:counter} rows.
+ *
+ * <p>Throughout this class, an <em>operation</em> is JMH's unit of work: a 
single invocation of a
+ * {@code @Benchmark}-annotated method. (One operation equals one invocation 
here because we don't use
+ * {@code @OperationsPerInvocation}.) JMH reports the timing score in {@code 
ns/op}, and these work
+ * counters are reported {@code PerOp} to match.
+ *
+ * <p>Each benchmark calls {@link #collectDeltasAndDrainRPCs} every invocation 
to accumulate the work deltas drained
+ * from {@link RaftClientBenchmarkContext}. The raw totals are private 
accumulators; what we report
+ * are the per-operation values from the {@code *PerOp()} methods (the 
quantity of interest), plus
+ * {@link #operations}.

Review Comment:
   Let's try to simplify some of this documentation in this class. In general, 
well-written code documents itself. For example, I think 
`collectDeltasAndDrainRPCs` is pretty straightforward. You already document 
that method, so this paragraph is a bit of duplication. What do you think?



##########
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/raft/LeaderBenchmarks.java:
##########
@@ -0,0 +1,97 @@
+/*
+ * 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.kafka.jmh.raft;
+
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.raft.RaftClientBenchmarkContext;
+import org.apache.kafka.raft.RaftClientTestContext;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Benchmarks for the leader request-handling path. The outer class is 
intentionally not a JMH
+ * {@code @State}: each benchmark declares the starting state it needs as a 
nested {@code @State}
+ * parameter, so future leader scenarios (e.g. a lagging-follower fetch or a 
commit) can have their own
+ * setup without forcing a single shared {@code @Setup} on the whole class.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = RaftClientBenchmarkContext.AVERAGE_TIME_WARMUP_ITERATIONS)
+@Measurement(iterations = 
RaftClientBenchmarkContext.AVERAGE_TIME_MEASUREMENT_ITERATIONS)
+@Fork(RaftClientBenchmarkContext.AVERAGE_TIME_FORKS)
+public class LeaderBenchmarks {
+
+    /**
+     * Starting state: the local node is Leader with the high watermark at the 
log end and a caught-up
+     * follower ready to fetch. Built once per trial and reused across 
invocations, since handling a
+     * caught-up fetch does not mutate it.

Review Comment:
   ```
   Built once per trial and reused across invocations, since handling a
        * caught-up fetch does not mutate it.
   ```
   This is not necessarily true across other benchmarks you may write with this 
starting state. It is true for the existing benchmark we have. Can we remove 
this comment?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to