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


##########
sdks/java/harness/jmh/src/main/java/org/apache/beam/fn/harness/jmh/StateAndSamplerBenchmark.java:
##########
@@ -0,0 +1,374 @@
+/*

Review Comment:
   let's just have this be StateBenchmark.java and remove the sampler stuff, it 
is unrelated
   
   AI likes to make And things that don't necessarily belong together



##########
sdks/java/harness/jmh/src/test/java/org/apache/beam/fn/harness/jmh/StateAndSamplerBenchmarkTest.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   rm this file, it seems overkill



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

Review Comment:
   check it is active? it seems otherwise there is unintended multithreaded use 
of this?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ExecutionStateSampler.java:
##########
@@ -337,6 +321,10 @@ public class ExecutionStateTracker implements 
BundleProgressReporter {
     private final AtomicReference<@Nullable ExecutionStateImpl> 
currentStateLazy;
     // If an exception occurs, this will be to state at the time of exception.
     private boolean inErrorState = false;
+    // Tracks whether start() registered this tracker with activeStateTrackers.
+    private volatile boolean active = false;

Review Comment:
   does this need to be volatile? It seems like start/reset would be sequenced 
already



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ExecutionStateSampler.java:
##########
@@ -662,21 +653,36 @@ public void updateFinalMonitoringData(Map<String, 
ByteString> monitoringData) {
      */
     @Override
     public void reset() {
-      synchronized (activeStateTrackers) {
-        activeStateTrackers.remove(this);
-        for (ExecutionStateImpl executionState : executionStates) {
-          executionState.reset();
+      boolean deactivated = false;
+      if (this.active) {
+        synchronized (activeStateTrackers) {
+          if (this.active) {
+            activeStateTrackers.remove(this);
+            this.transitionsAtLastSample = 0;
+            this.active = false;
+            deactivated = true;
+          }
         }
-        this.transitionsAtLastSample = 0;
       }
-      this.processBundleId.lazySet(null);
-      this.trackedThread.lazySet(null);
-      this.startTimeMillis.lazySet(0);
-      this.numTransitions = 0;
-      this.numTransitionsLazy.lazySet(0);
-      this.lastTransitionTimeMillis.lazySet(0);
+      boolean wasReported = this.monitoringReported;
+      if (wasReported) {
+        this.monitoringReported = false;
+      }
+      if (deactivated || wasReported) {
+        for (int i = 0, size = executionStates.size(); i < size; i++) {
+          executionStates.get(i).reset();
+        }
+      }
+      if (deactivated || this.numTransitions != 0 || this.inErrorState) {

Review Comment:
   is this worth trying to see if this is correct? seems like lazy sets should 
be cheap and the common case is that it is deactivated anyway



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -47,13 +53,49 @@
 public class MultimapSideInput<K, V> implements MultimapView<K, V> {
 
   private static final int BULK_READ_SIZE = 100;
+  private static final int WEIGH_SAMPLE_LIMIT = 64;
+
+  private enum BulkReadCacheKey {
+    INSTANCE
+  }
+
+  /**
+   * Immutable, bounded snapshot of up to {@link #BULK_READ_SIZE} multimap 
entries shared across
+   * bundles via the state cache.
+   */
+  private static final class CachedBulkRead<V> implements Weighted {
+    private final Map<Object, Iterable<V>> entries;
+    private final boolean complete;
+    private final long weight;
+
+    CachedBulkRead(Map<Object, Iterable<V>> entries, boolean complete, long 
weight) {
+      this.entries = entries;
+      this.complete = complete;
+      this.weight = weight;
+    }
+
+    @Override
+    public long getWeight() {
+      return weight;
+    }
+
+    Iterable<V> get(Object structuralKey) {
+      Iterable<V> result = entries.get(structuralKey);
+      if (result == null && complete) {
+        // As we read the entire set of values, we don't have to do a lookup 
to know
+        // this key doesn't exist. Missing keys are treated as empty iterables 
in this multimap.
+        return Collections.emptyList();
+      }
+      return result;
+    }
+  }
 
   private final Cache<?, ?> cache;

Review Comment:
   can we add some guardedby annotations



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -172,6 +165,117 @@ 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));
+      while (bulkRead.size() < BULK_READ_SIZE && entries.hasNext()) {
+        KV<K, Iterable<V>> entry = entries.next();
+        bulkRead.put(
+            keyCoder.structuralValue(entry.getKey()), 
toUnmodifiableIterable(entry.getValue()));
+      }
+      boolean complete = !entries.hasNext();
+      reader = new CachedBulkRead<>(bulkRead, complete, 
weighBulkRead(bulkRead));
+      bulkReadCache.put(BulkReadCacheKey.INSTANCE, reader);
+    } catch (Exception exn) {
+      // Do not publish partial/failed bulk reads to the shared cache.
+      reader = new CachedBulkRead<>(bulkRead, false, 0L);
+    }
+    this.bulkReadResult = reader;
+    return reader;
+  }
+
+  private static <V> Iterable<V> toUnmodifiableIterable(Iterable<V> values) {

Review Comment:
   remove and just use Iterables.unmodifiableIterable
   
   doesn't seem worth the complexity



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -172,6 +165,117 @@ 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));
+      while (bulkRead.size() < BULK_READ_SIZE && entries.hasNext()) {
+        KV<K, Iterable<V>> entry = entries.next();
+        bulkRead.put(
+            keyCoder.structuralValue(entry.getKey()), 
toUnmodifiableIterable(entry.getValue()));
+      }
+      boolean complete = !entries.hasNext();
+      reader = new CachedBulkRead<>(bulkRead, complete, 
weighBulkRead(bulkRead));
+      bulkReadCache.put(BulkReadCacheKey.INSTANCE, reader);
+    } catch (Exception exn) {
+      // Do not publish partial/failed bulk reads to the shared cache.
+      reader = new CachedBulkRead<>(bulkRead, false, 0L);
+    }
+    this.bulkReadResult = reader;
+    return reader;
+  }
+
+  private static <V> Iterable<V> toUnmodifiableIterable(Iterable<V> values) {
+    if (values instanceof List) {
+      return Collections.unmodifiableList((List<V>) values);
+    }
+    if (values instanceof Collection) {
+      return Collections.unmodifiableCollection((Collection<V>) values);
+    }
+    return Iterables.unmodifiableIterable(values);
+  }
+
+  private static <V> long weighBulkRead(Map<Object, Iterable<V>> bulkRead) {
+    // CachedBulkRead + HashMap base (~96 B) + Node[] table (next power of 2 
>= size / 0.75).
+    int size = bulkRead.size();
+    int tableCapacity = size == 0 ? 0 : Integer.highestOneBit(Math.max(16, 
(size * 4) / 3) * 2 - 1);
+    long weight = 96L + (long) tableCapacity * Caches.REFERENCE_SIZE;
+    for (Map.Entry<Object, Iterable<V>> entry : bulkRead.entrySet()) {
+      // HashMap.Node overhead (~32 B) + structural key + unmodifiable values 
iterable.
+      weight = LongMath.saturatedAdd(weight, 32L);
+      weight = LongMath.saturatedAdd(weight, Caches.weigh(entry.getKey()));
+      weight = LongMath.saturatedAdd(weight, weighIterable(entry.getValue()));
+    }
+    return weight;
+  }
+
+  private static <V> long weighIterable(Iterable<V> iterable) {

Review Comment:
   move this to common place like Caches.weigh?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java:
##########
@@ -172,6 +165,117 @@ 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));
+      while (bulkRead.size() < BULK_READ_SIZE && entries.hasNext()) {
+        KV<K, Iterable<V>> entry = entries.next();
+        bulkRead.put(
+            keyCoder.structuralValue(entry.getKey()), 
toUnmodifiableIterable(entry.getValue()));
+      }
+      boolean complete = !entries.hasNext();
+      reader = new CachedBulkRead<>(bulkRead, complete, 
weighBulkRead(bulkRead));
+      bulkReadCache.put(BulkReadCacheKey.INSTANCE, reader);
+    } catch (Exception exn) {
+      // Do not publish partial/failed bulk reads to the shared cache.
+      reader = new CachedBulkRead<>(bulkRead, false, 0L);
+    }
+    this.bulkReadResult = reader;
+    return reader;
+  }
+
+  private static <V> Iterable<V> toUnmodifiableIterable(Iterable<V> values) {
+    if (values instanceof List) {
+      return Collections.unmodifiableList((List<V>) values);
+    }
+    if (values instanceof Collection) {
+      return Collections.unmodifiableCollection((Collection<V>) values);
+    }
+    return Iterables.unmodifiableIterable(values);
+  }
+
+  private static <V> long weighBulkRead(Map<Object, Iterable<V>> bulkRead) {
+    // CachedBulkRead + HashMap base (~96 B) + Node[] table (next power of 2 
>= size / 0.75).
+    int size = bulkRead.size();
+    int tableCapacity = size == 0 ? 0 : Integer.highestOneBit(Math.max(16, 
(size * 4) / 3) * 2 - 1);
+    long weight = 96L + (long) tableCapacity * Caches.REFERENCE_SIZE;
+    for (Map.Entry<Object, Iterable<V>> entry : bulkRead.entrySet()) {
+      // HashMap.Node overhead (~32 B) + structural key + unmodifiable values 
iterable.
+      weight = LongMath.saturatedAdd(weight, 32L);
+      weight = LongMath.saturatedAdd(weight, Caches.weigh(entry.getKey()));
+      weight = LongMath.saturatedAdd(weight, weighIterable(entry.getValue()));
+    }
+    return weight;
+  }
+
+  private static <V> long weighIterable(Iterable<V> iterable) {
+    if (iterable instanceof Collection) {

Review Comment:
   if the iterable implements Weighted we should use that weight first



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapUserState.java:
##########
@@ -419,88 +439,203 @@ public void asyncClose() throws Exception {
       return;
     }
 
-    startStateApiWrites();
-    updateCache();
-  }
+    ByteStringOutputStream encodeOut =
+        (pendingRemoves.isEmpty() && pendingAdds.isEmpty()) ? null : new 
ByteStringOutputStream();
 
-  @SuppressWarnings("FutureReturnValueIgnored")
-  private void startStateApiWrites() {
-    // Clear currently persisted key-values
+    // Clear currently persisted key-values, saving encoded requests so each 
removed key is only
+    // encoded once across the clear RPC and cache update.
+    Map<Object, StateRequest> encodedRemoves = Collections.emptyMap();
     if (isCleared) {
       beamFnStateClient.handle(
           
keysStateRequest.toBuilder().setClear(StateClearRequest.getDefaultInstance()));
     } else if (!pendingRemoves.isEmpty()) {
-      for (K key : pendingRemoves.values()) {
-        StateRequest request = createUserStateRequest(key);
+      encodedRemoves = Maps.newHashMapWithExpectedSize(pendingRemoves.size());
+      for (Map.Entry<Object, K> entry : pendingRemoves.entrySet()) {
+        StateRequest request = createUserStateRequest(entry.getValue(), 
encodeOut);
+        encodedRemoves.put(entry.getKey(), request);
         beamFnStateClient.handle(
             
request.toBuilder().setClear(StateClearRequest.getDefaultInstance()));
       }
     }
 
-    // Persist pending key-values
+    List<K> pendingAddsKeys =
+        pendingAdds.isEmpty() ? Collections.emptyList() : new 
ArrayList<>(pendingAdds.size());
+    long pendingAddsKeysBytes = 0;
+    List<PendingCacheUpdate<V>> pendingCacheUpdates = null;

Review Comment:
   add nullable



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


Review Comment:
   comment on thread-safty



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