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


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########


Review Comment:
   remove this suppression? helps verify new code statically



##########
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:
   ditto



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ExecutionStateSampler.java:
##########
@@ -662,21 +655,31 @@ public void updateFinalMonitoringData(Map<String, 
ByteString> monitoringData) {
      */
     @Override
     public void reset() {
-      synchronized (activeStateTrackers) {
-        activeStateTrackers.remove(this);
-        for (ExecutionStateImpl executionState : executionStates) {
-          executionState.reset();
+      boolean deactivated = this.active;
+      if (deactivated) {
+        synchronized (activeStateTrackers) {
+          activeStateTrackers.remove(this);
+          this.transitionsAtLastSample = 0;
+          this.active = false;

Review Comment:
   move this.active above out of synchronized block



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -172,6 +166,71 @@ public Iterable<V> get(K k) {
         Caches.subCache(cache, "ValuesForKey", encodedKey), beamFnStateClient, 
request, valueCoder);
   }
 
+  private synchronized CachedBulkRead<V> loadOrGetBulkRead() {
+    CachedBulkRead<V> reader = this.bulkReadResult;
+    if (reader != null) {
+      return reader;
+    }
+
+    Cache<BulkReadCacheKey, CachedBulkRead<V>> bulkReadCache = 
Caches.subCache(cache, "BulkRead");
+    reader = bulkReadCache.peek(BulkReadCacheKey.INSTANCE);
+    if (reader != null) {
+      this.bulkReadResult = reader;
+      return reader;
+    }
+
+    Map<Object, Iterable<V>> bulkRead = new HashMap<>();
+    StateKey bulkReadStateKey =
+        StateKey.newBuilder()
+            .setMultimapKeysValuesSideInput(
+                StateKey.MultimapKeysValuesSideInput.newBuilder()
+                    .setTransformId(
+                        
keysRequest.getStateKey().getMultimapKeysSideInput().getTransformId())
+                    .setSideInputId(
+                        
keysRequest.getStateKey().getMultimapKeysSideInput().getSideInputId())
+                    
.setWindow(keysRequest.getStateKey().getMultimapKeysSideInput().getWindow()))
+            .build();
+
+    StateRequest bulkReadRequest = 
keysRequest.toBuilder().setStateKey(bulkReadStateKey).build();
+    try {
+      // Stream lazily via DataStreamDecoder over chunked state responses so 
pages holding
+      // > BULK_READ_SIZE keys stop decoding after entry BULK_READ_SIZE while 
still supporting
+      // individual KV entries that straddle chunk boundaries.
+      DataStreamDecoder<KV<K, Iterable<V>>> entries =
+          new DataStreamDecoder<>(
+              KvCoder.of(keyCoder, IterableCoder.of(valueCoder)),
+              new StateFetchingIterators.LazyBlockingStateFetchingIterator(
+                  beamFnStateClient, bulkReadRequest));
+      long entriesWeight = 0L;
+      while (bulkRead.size() < BULK_READ_SIZE && entries.hasNext()) {
+        KV<K, Iterable<V>> entry = entries.next();
+        Object structuralKey = keyCoder.structuralValue(entry.getKey());
+        Iterable<V> rawValues = entry.getValue();
+        // Weigh rawValues before wrapping with Iterables.unmodifiableIterable 
so Caches.weigh()
+        // checks Weighted and hits its RandomAccess list fast paths rather 
than falling back to
+        // jamm. Includes ~32B HashMap.Node + ~16B UnmodifiableIterable 
wrapper overhead.
+        entriesWeight = LongMath.saturatedAdd(entriesWeight, 48L);
+        entriesWeight = LongMath.saturatedAdd(entriesWeight, 
Caches.weigh(structuralKey));
+        entriesWeight = LongMath.saturatedAdd(entriesWeight, 
Caches.weigh(rawValues));
+        bulkRead.put(structuralKey, Iterables.unmodifiableIterable(rawValues));
+      }
+      boolean complete = !entries.hasNext();
+      int size = bulkRead.size();
+      int tableCapacity =
+          size == 0 ? 0 : Integer.highestOneBit(Math.max(16, (size * 4) / 3) * 
2 - 1);
+      // CachedBulkRead + HashMap base (~96 B) + Node[] table (next power of 2 
>= size / 0.75).

Review Comment:
   add some helper method to Caches to calculate HashMap overhead? It's 
somewhat complicated and would be good to test in isolation as well by 
comparing the estimate with what JAMM calculates



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -183,6 +242,8 @@ private ByteString encodeKey(K k) {
               k, 
keysRequest.getStateKey().getMultimapKeysSideInput().getSideInputId()),
           e);
     }
-    return output.toByteString();
+    // Trim small buffers to an exact-sized LiteralByteString so sub-cache 
keys do not retain an

Review Comment:
   are all buffers necessarily small? should we compare the size and possibly 
modify toByteString internally to do this copy for small strings to aid memory 
overhead for other use-cases too?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/StateFetchingIterators.java:
##########
@@ -258,27 +259,40 @@ private Builder(int initialCapacity) {
 
         void addAndWeighAll(List<T> addedValues) {
           values.addAll(addedValues);
+          weight =
+              LongMath.saturatedAdd(
+                  weight, LongMath.saturatedMultiply(addedValues.size(), 
Caches.REFERENCE_SIZE));
           for (@Nullable T v : addedValues) {
             weight = LongMath.saturatedAdd(weight, Caches.weigh(v));
           }
         }
 
+        /**
+         * Adds {@code addedValues} with a pre-computed weight that already 
includes {@code
+         * addedValues.size() * Caches.REFERENCE_SIZE}.
+         */
         void addAllWithWeight(List<T> addedValues, long addedWeight) {
           values.addAll(addedValues);
           weight = LongMath.saturatedAdd(weight, addedWeight);
         }
 
         void addBlock(Block<T> b) {
           values.addAll(b.getValues());
-          weight = LongMath.saturatedAdd(weight, b.getWeight());
+          long blockWeight = b.getWeight();
+          // Non-empty blocks already include ARRAY_LIST_OVERHEAD and 
per-element REFERENCE_SIZE.

Review Comment:
   can we just skip doing anything for empty blocks? seems simpler



##########
sdks/java/harness/src/test/java/org/apache/beam/fn/harness/control/ExecutionStateSamplerTest.java:
##########
@@ -898,4 +905,241 @@ public void testDefaultElementProcessingTimeoutMinutes() {
     assertThat(sampler.getUserSpecifiedLullTimeMsForRestart(), equalTo(0L));
     assertThat(sampler.getUserSpecifiedTimeoutForRestart(), equalTo(false));
   }
+
+  @Test
+  public void testRepeatedResetAndReuse() {
+    AtomicLong currentTimeMillis = new AtomicLong(100L);
+    ExecutionStateSampler sampler =
+        new ExecutionStateSampler(
+            PipelineOptionsFactory.create(),
+            () -> currentTimeMillis.getAndAdd(10L),
+            mockOnTimeoutExceededCallback);
+    try {
+      ExecutionStateTracker tracker = sampler.create();
+      ExecutionState state =
+          tracker.create("shortId", "ptransformId", "ptransformIdName", 
"process");
+
+      // Repeated reset before start should be a safe no-op.
+      tracker.reset();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+
+      // First bundle lifecycle + redundant reset calls (as done by 
ProcessBundleHandler).
+      tracker.start("bundle1");
+      assertSame(tracker, BeamFnLoggingMDC.getStateTracker());
+      state.activate();
+      assertEquals("ptransformId", tracker.getCurrentThreadsPTransformId());
+      Counter counter = 
tracker.getMetricsContainer().getCounter(MetricName.named("ns", "c"));
+      counter.inc(7L);
+      state.deactivate();
+      Map<String, ByteString> finalData = new HashMap<>();
+      tracker.updateFinalMonitoringData(finalData);
+      assertTrue(finalData.containsKey("shortId"));
+      assertEquals(
+          7L,
+          tracker
+              .getMetricsContainerRegistry()
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "c"))
+              .getCumulative()
+              .longValue());
+
+      tracker.reset();
+      tracker.reset();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(tracker.getCurrentThreadsPTransformId());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+      assertEquals(
+          0L,
+          tracker
+              .getMetricsContainerRegistry()
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "c"))
+              .getCumulative()
+              .longValue());
+
+      // Second bundle lifecycle on the same tracker should work identically.
+      tracker.start("bundle2");
+      state.activate();
+      assertEquals("ptransformId", tracker.getCurrentThreadsPTransformId());
+      state.deactivate();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+    } finally {
+      sampler.stop();
+    }
+  }
+
+  @Test
+  public void testResetWithRetainedMetricHandlesAndRegistry() {
+    AtomicLong clockMillis = new AtomicLong(100L);
+    ExecutionStateSampler sampler =
+        new ExecutionStateSampler(
+            PipelineOptionsFactory.create(), clockMillis::get, 
mockOnTimeoutExceededCallback);
+    try {
+      ExecutionStateTracker tracker = sampler.create();
+      ExecutionState state =
+          tracker.create("shortId", "ptransformId", "ptransformIdName", 
"process");
+      MetricsContainerStepMap registry = tracker.getMetricsContainerRegistry();
+
+      state.activate();
+      Counter retainedCounter =
+          tracker.getMetricsContainer().getCounter(MetricName.named("ns", 
"retained"));
+      Distribution retainedDist =
+          tracker.getMetricsContainer().getDistribution(MetricName.named("ns", 
"dist"));
+      Gauge retainedGauge = 
tracker.getMetricsContainer().getGauge(MetricName.named("ns", "gauge"));
+      StringSet retainedSet =
+          tracker.getMetricsContainer().getStringSet(MetricName.named("ns", 
"set"));
+      BoundedTrie retainedTrie =
+          tracker.getMetricsContainer().getBoundedTrie(MetricName.named("ns", 
"trie"));
+      HistogramData.BucketType bucketType = HistogramData.LinearBuckets.of(0, 
1, 5);
+      Histogram retainedHist =
+          tracker.getMetricsContainer().getHistogram(MetricName.named("ns", 
"hist"), bucketType);
+      state.deactivate();
+
+      retainedCounter.inc(10L);
+      tracker.reset();
+      assertEquals(
+          0L,
+          registry
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "retained"))
+              .getCumulative()
+              .longValue());
+
+      // Mutate retained handles directly AFTER reset() without calling 
getCounter()/getRegistry().
+      retainedCounter.inc(42L);
+      retainedDist.update(5L);
+      retainedGauge.set(9L);
+      retainedSet.add("x");
+      retainedTrie.add("a");
+      retainedHist.update(1.0);
+      registry.getUnboundContainer().getCounter(MetricName.named("ns", 
"unbound")).inc(99L);
+
+      tracker.reset();

Review Comment:
   are the metrics modified above distinct from the current 
getCounter/getRegistry? 
   I think that is the case, but then it seems a better test to not reset here.
   
   If that's not the case not,it seems like we should verify that the values 
are reflected in the current getCounter/getRegistry before resetting.



##########
sdks/java/harness/src/test/java/org/apache/beam/fn/harness/state/MultimapSideInputTest.java:
##########
@@ -72,13 +92,478 @@ public void testGetWithBulkRead() throws Exception {
             StringUtf8Coder.of(),
             true);
     assertArrayEquals(
-        new String[] {"A1", "A2", "A3"}, 
Iterables.toArray(multimapSideInput.get(A), String.class));
+        new String[] {"A1", "A2", "A3"},
+        Iterables.toArray(multimapSideInput.get(Arrays.copyOf(A, A.length)), 
String.class));
     assertArrayEquals(
         new String[] {"B1", "B2"}, Iterables.toArray(multimapSideInput.get(B), 
String.class));
     assertArrayEquals(
         new String[] {}, Iterables.toArray(multimapSideInput.get(UNKNOWN), 
String.class));
   }
 
+  @Test
+  public void testGetWithBulkReadCached() throws Exception {
+    FakeBeamFnStateClient fakeBeamFnStateClient =
+        new FakeBeamFnStateClient(
+            ImmutableMap.of(
+                keysValuesStateKey(),
+                KV.of(
+                    KvCoder.of(ByteArrayCoder.of(), 
IterableCoder.of(StringUtf8Coder.of())),
+                    asList(KV.of(A, asList("A1", "A2", "A3")), KV.of(B, 
asList("B1", "B2"))))));
+
+    Cache<?, ?> cache = Caches.eternal();
+    {
+      // The first side input populates the bulk-read cache.
+      MultimapSideInput<byte[], String> multimapSideInput =
+          new MultimapSideInput<>(
+              cache,
+              fakeBeamFnStateClient,
+              "instructionId",
+              keysStateKey(),
+              ByteArrayCoder.of(),
+              StringUtf8Coder.of(),
+              true);
+      Iterable<String> aValues = multimapSideInput.get(A);
+      assertArrayEquals(new String[] {"A1", "A2", "A3"}, 
Iterables.toArray(aValues, String.class));
+      // Cached bulk-read iterables must be unmodifiable so callers cannot 
corrupt shared entries.
+      if (aValues instanceof List) {
+        assertThrows(UnsupportedOperationException.class, () -> 
((List<String>) aValues).clear());
+      }
+      Iterator<String> it = aValues.iterator();
+      it.next();
+      assertThrows(UnsupportedOperationException.class, it::remove);
+      assertArrayEquals(
+          new String[] {"B1", "B2"}, 
Iterables.toArray(multimapSideInput.get(B), String.class));
+      assertArrayEquals(
+          new String[] {}, Iterables.toArray(multimapSideInput.get(UNKNOWN), 
String.class));
+    }
+
+    {
+      // The second side input must serve all bulk-read lookups purely from 
the cache.
+      MultimapSideInput<byte[], String> multimapSideInput =
+          new MultimapSideInput<>(
+              cache,
+              requestBuilder -> {
+                throw new IllegalStateException("Unexpected call for test.");
+              },
+              "instructionId",
+              keysStateKey(),
+              ByteArrayCoder.of(),
+              StringUtf8Coder.of(),
+              true);
+      assertArrayEquals(
+          new String[] {"A1", "A2", "A3"},
+          Iterables.toArray(multimapSideInput.get(Arrays.copyOf(A, A.length)), 
String.class));
+      assertArrayEquals(
+          new String[] {"B1", "B2"}, 
Iterables.toArray(multimapSideInput.get(B), String.class));
+      assertArrayEquals(
+          new String[] {}, Iterables.toArray(multimapSideInput.get(UNKNOWN), 
String.class));
+    }
+  }
+
+  @Test
+  public void testGetWithBulkReadMoreThan100KeysCached() throws Exception {

Review Comment:
   why is the 100 keys special? Is there a constant to refer to to clarify?



##########
sdks/java/harness/src/test/java/org/apache/beam/fn/harness/control/ExecutionStateSamplerTest.java:
##########
@@ -898,4 +905,241 @@ public void testDefaultElementProcessingTimeoutMinutes() {
     assertThat(sampler.getUserSpecifiedLullTimeMsForRestart(), equalTo(0L));
     assertThat(sampler.getUserSpecifiedTimeoutForRestart(), equalTo(false));
   }
+
+  @Test
+  public void testRepeatedResetAndReuse() {
+    AtomicLong currentTimeMillis = new AtomicLong(100L);
+    ExecutionStateSampler sampler =
+        new ExecutionStateSampler(
+            PipelineOptionsFactory.create(),
+            () -> currentTimeMillis.getAndAdd(10L),
+            mockOnTimeoutExceededCallback);
+    try {
+      ExecutionStateTracker tracker = sampler.create();
+      ExecutionState state =
+          tracker.create("shortId", "ptransformId", "ptransformIdName", 
"process");
+
+      // Repeated reset before start should be a safe no-op.
+      tracker.reset();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+
+      // First bundle lifecycle + redundant reset calls (as done by 
ProcessBundleHandler).
+      tracker.start("bundle1");
+      assertSame(tracker, BeamFnLoggingMDC.getStateTracker());
+      state.activate();
+      assertEquals("ptransformId", tracker.getCurrentThreadsPTransformId());
+      Counter counter = 
tracker.getMetricsContainer().getCounter(MetricName.named("ns", "c"));
+      counter.inc(7L);
+      state.deactivate();
+      Map<String, ByteString> finalData = new HashMap<>();
+      tracker.updateFinalMonitoringData(finalData);
+      assertTrue(finalData.containsKey("shortId"));
+      assertEquals(
+          7L,
+          tracker
+              .getMetricsContainerRegistry()
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "c"))
+              .getCumulative()
+              .longValue());
+
+      tracker.reset();
+      tracker.reset();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(tracker.getCurrentThreadsPTransformId());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+      assertEquals(
+          0L,
+          tracker
+              .getMetricsContainerRegistry()
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "c"))
+              .getCumulative()
+              .longValue());
+
+      // Second bundle lifecycle on the same tracker should work identically.
+      tracker.start("bundle2");
+      state.activate();
+      assertEquals("ptransformId", tracker.getCurrentThreadsPTransformId());
+      state.deactivate();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+    } finally {
+      sampler.stop();
+    }
+  }
+
+  @Test
+  public void testResetWithRetainedMetricHandlesAndRegistry() {
+    AtomicLong clockMillis = new AtomicLong(100L);
+    ExecutionStateSampler sampler =
+        new ExecutionStateSampler(
+            PipelineOptionsFactory.create(), clockMillis::get, 
mockOnTimeoutExceededCallback);
+    try {
+      ExecutionStateTracker tracker = sampler.create();
+      ExecutionState state =
+          tracker.create("shortId", "ptransformId", "ptransformIdName", 
"process");
+      MetricsContainerStepMap registry = tracker.getMetricsContainerRegistry();
+
+      state.activate();
+      Counter retainedCounter =
+          tracker.getMetricsContainer().getCounter(MetricName.named("ns", 
"retained"));
+      Distribution retainedDist =
+          tracker.getMetricsContainer().getDistribution(MetricName.named("ns", 
"dist"));
+      Gauge retainedGauge = 
tracker.getMetricsContainer().getGauge(MetricName.named("ns", "gauge"));
+      StringSet retainedSet =
+          tracker.getMetricsContainer().getStringSet(MetricName.named("ns", 
"set"));
+      BoundedTrie retainedTrie =
+          tracker.getMetricsContainer().getBoundedTrie(MetricName.named("ns", 
"trie"));
+      HistogramData.BucketType bucketType = HistogramData.LinearBuckets.of(0, 
1, 5);
+      Histogram retainedHist =
+          tracker.getMetricsContainer().getHistogram(MetricName.named("ns", 
"hist"), bucketType);
+      state.deactivate();
+
+      retainedCounter.inc(10L);
+      tracker.reset();
+      assertEquals(
+          0L,
+          registry
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "retained"))
+              .getCumulative()
+              .longValue());
+
+      // Mutate retained handles directly AFTER reset() without calling 
getCounter()/getRegistry().
+      retainedCounter.inc(42L);
+      retainedDist.update(5L);
+      retainedGauge.set(9L);
+      retainedSet.add("x");
+      retainedTrie.add("a");
+      retainedHist.update(1.0);
+      registry.getUnboundContainer().getCounter(MetricName.named("ns", 
"unbound")).inc(99L);
+
+      tracker.reset();
+      assertEquals(
+          0L,
+          registry
+              .getContainer("ptransformId")
+              .getCounter(MetricName.named("ns", "retained"))
+              .getCumulative()
+              .longValue());
+      assertEquals(
+          0L,
+          registry
+              .getContainer("ptransformId")
+              .getDistribution(MetricName.named("ns", "dist"))
+              .getCumulative()
+              .count());
+      assertEquals(
+          GaugeResult.empty(),
+          registry
+              .getContainer("ptransformId")
+              .getGauge(MetricName.named("ns", "gauge"))
+              .getCumulative()
+              .extractResult());
+      assertEquals(
+          0,
+          registry
+              .getContainer("ptransformId")
+              .getStringSet(MetricName.named("ns", "set"))
+              .getCumulative()
+              .stringSet()
+              .size());
+      assertTrue(
+          registry
+              .getContainer("ptransformId")
+              .getBoundedTrie(MetricName.named("ns", "trie"))
+              .getCumulative()
+              .toProto()
+              .getSingletonList()
+              .isEmpty());
+      assertEquals(
+          0L,
+          registry
+              .getContainer("ptransformId")
+              .getHistogram(MetricName.named("ns", "hist"), bucketType)
+              .getCumulative()
+              .getTotalCount());
+      assertEquals(
+          0L,
+          registry
+              .getUnboundContainer()
+              .getCounter(MetricName.named("ns", "unbound"))
+              .getCumulative()
+              .longValue());
+    } finally {
+      sampler.stop();
+    }
+  }
+
+  @Test
+  public void testResetInactiveMonitoringErrorAndDirectMdc() {
+    AtomicLong clockMillis = new AtomicLong(100L);
+    ExecutionStateSampler sampler =
+        new ExecutionStateSampler(
+            PipelineOptionsFactory.create(), clockMillis::get, 
mockOnTimeoutExceededCallback);
+    try {
+      ExecutionStateTracker tracker = sampler.create();
+      ExecutionState state =
+          tracker.create("shortId", "ptransformId", "ptransformIdName", 
"process");
+
+      // Error flag set without calling start() must clear on reset().
+      assertTrue(state.error());
+      assertFalse(state.error());
+      tracker.reset();
+      assertTrue(state.error());
+      tracker.reset();
+
+      // Direct MDC binding without start() must still be cleared by reset().
+      BeamFnLoggingMDC.setStateTracker(tracker);
+      tracker.reset();
+      assertNull(BeamFnLoggingMDC.getStateTracker());
+
+      // Monitoring update without start() must still reset state reporting on 
reset().
+      Map<String, ByteString> data = new HashMap<>();
+      tracker.updateIntermediateMonitoringData(data);
+      assertTrue(data.containsKey("shortId"));
+      tracker.reset();
+
+      // Activation without start() clears error/transition state safely.
+      state.activate();
+      state.deactivate();
+      tracker.reset();
+      assertNull(tracker.getStatus());
+    } finally {
+      sampler.stop();
+    }
+  }
+
+  @Test
+  public void testStartClockThrowsDoesNotLeakMdc() {

Review Comment:
   remove? I don't think we need to test the clock throwing an exception



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapUserState.java:
##########
@@ -138,9 +148,15 @@ public void clear() {
         keysStateRequest.getStateKey());
 

Review Comment:
   if it is safe to keep the same object, just clear without checking isEmpty
   
   If it is not safe to keep the same object, just reset the maps



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapUserState.java:
##########
@@ -308,24 +321,28 @@ public PrefetchableIterator<Map.Entry<K, V>> 
createIterator() {
                       Iterables.concat(
                           Iterables.filter(
                               Iterables.transform(
-                                  persistedEntries,
+                                  entriesIterable,
                                   entry -> {
                                     final Object structuralKey =
                                         
mapKeyCoder.structuralValue(entry.getKey());
                                     if 
(pendingRemovesNow.contains(structuralKey)) {
                                       return null;
                                     }
                                     // add returns true if we haven't seen 
this key yet.
-                                    if (seenKeys.add(structuralKey)
-                                        && 
pendingAddsNow.containsKey(structuralKey)) {
-                                      return PrefetchableIterables.concat(
-                                          Iterables.transform(
-                                              
pendingAddsNow.get(structuralKey).getValue(),
-                                              pendingAdd ->
-                                                  
Maps.immutableEntry(entry.getKey(), pendingAdd)),
-                                          Iterables.transform(
-                                              entry.getValue(),
-                                              value -> 
Maps.immutableEntry(entry.getKey(), value)));
+                                    if (seenKeys.add(structuralKey)) {
+                                      KV<K, List<V>> pendingAdd = 
pendingAddsNow.get(structuralKey);
+                                      if (pendingAdd != null) {
+                                        return PrefetchableIterables.concat(
+                                            Iterables.transform(
+                                                pendingAdd.getValue(),
+                                                pendingVal ->
+                                                    Maps.immutableEntry(
+                                                        entry.getKey(), 
pendingVal)),
+                                            Iterables.transform(

Review Comment:
   Is it ever possible that the iterable we're transforming is a 
PrefetchableIterable?
   If so we might want to instead have a PrefetchableIterables.transform that 
preserves that instead of using Iterables.transform



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/StateFetchingIterators.java:
##########
@@ -480,7 +509,16 @@ public void append(List<T> values) {
      * cache.
      */
     public void append(WeightedList<T> values) {
-      appendHelper(values.getBacking(), values.getWeight());
+      append(values.getBacking(), values.getWeight());
+    }
+
+    /**
+     * Appends {@code values} to the cached iterable with a pre-computed 
weight (including {@code
+     * values.size() * Caches.REFERENCE_SIZE}), avoiding a {@link 
WeightedList} wrapper.
+     */
+    void append(List<T> values, long valuesWeight) {
+      checkArgument(valuesWeight >= 0, "valuesWeight must be non-negative, got 
%s", valuesWeight);

Review Comment:
   remove this method and move the checkArgument in to appendHelper?



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