scwhittle commented on code in PR #41540:
URL: https://github.com/apache/beam/pull/41540#discussion_r4777119199


##########
sdks/java/harness/jmh/src/main/java/org/apache/beam/fn/harness/jmh/StateBenchmark.java:
##########
@@ -0,0 +1,335 @@
+/*
+ * 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.beam.fn.harness.jmh;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.beam.fn.harness.Cache;
+import org.apache.beam.fn.harness.Caches;
+import org.apache.beam.fn.harness.Caches.ClearableCache;
+import org.apache.beam.fn.harness.state.BagUserState;
+import org.apache.beam.fn.harness.state.BeamFnStateClient;
+import org.apache.beam.fn.harness.state.MultimapSideInput;
+import org.apache.beam.fn.harness.state.MultimapUserState;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateResponse;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.IterableCoder;
+import org.apache.beam.sdk.coders.KvCoder;
+import org.apache.beam.sdk.coders.StringUtf8Coder;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.options.SdkHarnessOptions;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.vendor.grpc.v1p69p0.com.google.protobuf.ByteString;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Level;
+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;
+
+/**
+ * Microbenchmarks for Java SDK Harness {@link BagUserState}, {@link 
MultimapUserState}, and {@link
+ * MultimapSideInput}.
+ */
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+public class StateBenchmark {
+
+  /** Thread-local benchmark fixtures. */
+  @State(Scope.Thread)
+  public static class BenchmarkState {
+    Cache<Object, Object> processWideCache;
+    Cache<Object, Object> sideInputCache;
+    Cache<Object, Object> largeSideInputCache;
+    ClearableCache<Object, Object> appendOnlyBagParentCache;
+    ClearableCache<Object, Object> appendRemoveMmapParentCache;
+
+    Coder<KV<String, String>> kvCoder;
+    StateKey bagStateKey;
+    StateKey bagAppendStateKey;
+    StateKey multimapStateKey;
+    StateKey multimapAppendStateKey;
+    StateKey multimapSideInputKey;
+    StateKey largeMultimapSideInputKey;
+    BeamFnStateClient noopStateClient;
+    BeamFnStateClient sideInputSmallClient;
+    BeamFnStateClient sideInputLargeClient;
+    List<KV<String, String>> kvBatch;
+    List<KV<String, String>> multimapBatchWithDuplicates;
+
+    int appendCounter;
+    int mmapAppendCounter;
+
+    /** Initializes caches, keys, coders, and fake state clients. */
+    @Setup(Level.Trial)
+    public void setUp() throws IOException {
+      ByteString sampleKey = 
ByteString.copyFromUtf8("encoded-user-key-0123456789-abcdef");
+
+      bagStateKey =
+          StateKey.newBuilder()
+              .setBagUserState(
+                  StateKey.BagUserState.newBuilder()
+                      .setTransformId("t1")
+                      .setUserStateId("bag")
+                      .setWindow(ByteString.EMPTY)
+                      .setKey(sampleKey))
+              .build();
+
+      bagAppendStateKey =
+          StateKey.newBuilder()
+              .setBagUserState(
+                  StateKey.BagUserState.newBuilder()
+                      .setTransformId("t1")
+                      .setUserStateId("bag-append")
+                      .setWindow(ByteString.EMPTY)
+                      .setKey(sampleKey))
+              .build();
+
+      multimapStateKey =
+          StateKey.newBuilder()
+              .setMultimapKeysUserState(
+                  StateKey.MultimapKeysUserState.newBuilder()
+                      .setTransformId("t1")
+                      .setUserStateId("mmap")
+                      .setWindow(ByteString.EMPTY)
+                      .setKey(sampleKey))
+              .build();
+
+      multimapAppendStateKey =
+          StateKey.newBuilder()
+              .setMultimapKeysUserState(
+                  StateKey.MultimapKeysUserState.newBuilder()
+                      .setTransformId("t1")
+                      .setUserStateId("mmap-append")
+                      .setWindow(ByteString.EMPTY)
+                      .setKey(sampleKey))
+              .build();
+
+      multimapSideInputKey =
+          StateKey.newBuilder()
+              .setMultimapKeysSideInput(
+                  StateKey.MultimapKeysSideInput.newBuilder()
+                      .setTransformId("t1")
+                      .setSideInputId("si-small")
+                      .setWindow(ByteString.EMPTY))
+              .build();
+
+      largeMultimapSideInputKey =
+          StateKey.newBuilder()
+              .setMultimapKeysSideInput(
+                  StateKey.MultimapKeysSideInput.newBuilder()
+                      .setTransformId("t1")
+                      .setSideInputId("si-large")
+                      .setWindow(ByteString.EMPTY))
+              .build();
+
+      kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of());
+
+      PipelineOptions opts64 = PipelineOptionsFactory.create();
+      opts64.as(SdkHarnessOptions.class).setMaxCacheMemoryUsageMb(64);
+      processWideCache = Caches.fromOptions(opts64);
+      sideInputCache = Caches.fromOptions(opts64);
+      largeSideInputCache = Caches.fromOptions(opts64);
+
+      appendOnlyBagParentCache =
+          new ClearableCache<>(Caches.subCache(processWideCache, 
"BagAppendRoot"));
+      appendRemoveMmapParentCache =
+          new ClearableCache<>(Caches.subCache(processWideCache, 
"MmapAppendRoot"));
+
+      noopStateClient =
+          requestBuilder -> 
CompletableFuture.completedFuture(StateResponse.getDefaultInstance());
+
+      KvCoder<String, Iterable<String>> entryCoder =
+          KvCoder.of(StringUtf8Coder.of(), 
IterableCoder.of(StringUtf8Coder.of()));
+
+      ByteString encodedSmallBulk = encodeBulkSideInput(entryCoder, 20);
+      sideInputSmallClient =
+          requestBuilder -> {
+            StateResponse.Builder resp = StateResponse.newBuilder();
+            resp.getGetBuilder().setData(encodedSmallBulk);
+            return CompletableFuture.completedFuture(resp.build());
+          };
+
+      ByteString encodedLargeBulk = encodeBulkSideInput(entryCoder, 150);
+      ByteArrayOutputStream singleValOut = new ByteArrayOutputStream();
+      StringUtf8Coder.of().encode("val-120", singleValOut);
+      ByteString encodedSingleValue = 
ByteString.copyFrom(singleValOut.toByteArray());
+      sideInputLargeClient =
+          requestBuilder -> {
+            StateResponse.Builder resp = StateResponse.newBuilder();
+            if (requestBuilder.getStateKey().hasMultimapKeysValuesSideInput()) 
{
+              resp.getGetBuilder().setData(encodedLargeBulk);
+            } else {
+              resp.getGetBuilder().setData(encodedSingleValue);
+            }
+            return CompletableFuture.completedFuture(resp.build());
+          };
+
+      kvBatch = new ArrayList<>(16);
+      for (int i = 0; i < 16; i++) {
+        kvBatch.add(KV.of("k-" + i, "payload-value-for-bag-state-" + i));
+      }
+
+      // 8 distinct keys with 4 values each -> exercises both new-key put and 
hit-key appends.
+      multimapBatchWithDuplicates = new ArrayList<>(32);
+      for (int i = 0; i < 32; i++) {
+        multimapBatchWithDuplicates.add(KV.of("k-" + (i & 7), "val-" + i));
+      }
+    }
+
+    private static ByteString encodeBulkSideInput(
+        KvCoder<String, Iterable<String>> entryCoder, int count) throws 
IOException {
+      ByteArrayOutputStream baos = new ByteArrayOutputStream();
+      for (int i = 0; i < count; i++) {
+        entryCoder.encode(KV.of("key-" + i, Collections.singletonList("val-" + 
i)), baos);
+      }
+      return ByteString.copyFrom(baos.toByteArray());
+    }
+  }
+
+  @Benchmark
+  public int bagUserStateClearAppendClose(BenchmarkState s) throws Exception {
+    Cache<Object, Object> userCache = Caches.subCache(s.processWideCache, 
"BagBench");
+    BagUserState<KV<String, String>> bag =
+        new BagUserState<>(userCache, s.noopStateClient, "inst-1", 
s.bagStateKey, s.kvCoder);
+    bag.clear();
+    for (int i = 0; i < s.kvBatch.size(); i++) {
+      bag.append(s.kvBatch.get(i));
+    }
+    bag.asyncClose();
+    return s.kvBatch.size();
+  }
+
+  @Benchmark
+  public int bagUserStateAppendOnlyClose(BenchmarkState s) throws Exception {
+    int turn = s.appendCounter++ & 15;
+    BagUserState<KV<String, String>> bag =
+        new BagUserState<>(
+            s.appendOnlyBagParentCache,
+            s.noopStateClient,
+            "inst-1",
+            s.bagAppendStateKey,
+            s.kvCoder);
+    if (turn == 0) {
+      bag.clear();
+    }
+    for (int i = 0; i < 4; i++) {
+      bag.append(s.kvBatch.get(i));
+    }
+    bag.asyncClose();
+    return turn;
+  }
+
+  @Benchmark
+  public int multimapUserStateClearPutClose(BenchmarkState s) throws Exception 
{
+    Cache<Object, Object> userCache = Caches.subCache(s.processWideCache, 
"MmapBench");
+    MultimapUserState<String, String> mmap =
+        new MultimapUserState<>(
+            userCache,
+            s.noopStateClient,
+            "inst-1",
+            s.multimapStateKey,
+            StringUtf8Coder.of(),
+            StringUtf8Coder.of());
+    mmap.clear();
+    for (int i = 0; i < s.multimapBatchWithDuplicates.size(); i++) {
+      KV<String, String> item = s.multimapBatchWithDuplicates.get(i);
+      mmap.put(item.getKey(), item.getValue());
+    }
+    mmap.asyncClose();
+    return s.multimapBatchWithDuplicates.size();
+  }
+
+  @Benchmark
+  public int multimapUserStateAppendRemoveClose(BenchmarkState s) throws 
Exception {
+    int turn = s.mmapAppendCounter++ & 15;
+    MultimapUserState<String, String> mmap =
+        new MultimapUserState<>(
+            s.appendRemoveMmapParentCache,
+            s.noopStateClient,
+            "inst-1",
+            s.multimapAppendStateKey,
+            StringUtf8Coder.of(),
+            StringUtf8Coder.of());
+    if (turn == 0) {
+      mmap.clear();
+      for (int i = 0; i < 4; i++) {
+        mmap.put("k-" + i, "seed-" + i);
+      }
+    } else {
+      // Load one key into persistedValues, append to it, and remove another 
key.
+      mmap.get("k-0");
+      mmap.put("k-0", "v-" + turn);
+      mmap.remove("k-1");
+      mmap.put("k-1", "readd-" + turn);
+      mmap.remove("k-2");
+    }
+    mmap.asyncClose();
+    return turn;
+  }
+
+  @Benchmark
+  public int multimapSideInputBulkReadSmall(BenchmarkState s) {
+    Cache<Object, Object> siCache = Caches.subCache(s.sideInputCache, 
"BulkSiSmall");
+    MultimapSideInput<String, String> si =
+        new MultimapSideInput<>(
+            siCache,
+            s.sideInputSmallClient,
+            "inst-1",
+            s.multimapSideInputKey,
+            StringUtf8Coder.of(),
+            StringUtf8Coder.of(),
+            true);
+    int count = 0;
+    for (String v : si.get("key-5")) {
+      count += v.length();
+    }
+    return count;
+  }
+
+  @Benchmark
+  public int multimapSideInputBulkReadLarge(BenchmarkState s) {

Review Comment:
   haha, me either :P



-- 
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