You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2022/06/22 18:57:52 UTC

[GitHub] [beam] lukecwik opened a new pull request, #22002: [BEAM-13015] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

lukecwik opened a new pull request, #22002:
URL: https://github.com/apache/beam/pull/22002

   This counter is limited to be used with a specific thread interaction pattern that is well suited to be used as a system level bundle specific counter and may not be suitable as a user counter.
   
   The new counter is 8.5x faster on updates and even more on reset.
   ```
   Benchmark                                                               Mode  Cnt          Score          Error  Units
   MetricsBenchmark.testCounterCellMutation                               thrpt   25  101509847.937 ±   100089.022  ops/s
   MetricsBenchmark.testCounterCellReset                                  thrpt   25   34072850.016 ±    70718.608  ops/s
   MetricsBenchmark.testSerialMutatorAndFinalReaderBundleCounterMutation  thrpt   25  854084919.952 ± 41010094.337  ops/s
   MetricsBenchmark.testSerialMutatorAndFinalReaderBundleCounterReset     thrpt   25  415817398.009 ±   869847.035  ops/s
   ```
   
   Also clean-up the short id reporting mechanism to bind the short id once during instantiation instead of during each progress report. This clean-up has a tiny impact on the bundle benchmarks as can be seen:
   Before this change:
   ```
   Benchmark                                Mode  Cnt     Score      Error  Units
   ProcessBundleBenchmark.testLargeBundle  thrpt   25  1155.848  ±   7.517  ops/s
   ProcessBundleBenchmark.testTinyBundle   thrpt   25  28858.064 ±  98.341  ops/s
   ```
   
   After this change:
   ```
   Benchmark                                Mode  Cnt     Score      Error  Units
   ProcessBundleBenchmark.testLargeBundle  thrpt   25  1155.204  ±   9.236  ops/s
   ProcessBundleBenchmark.testTinyBundle   thrpt   25  29000.767 ± 195.753  ops/s
   ```
   
   The perf profiles show a better change of CPU usage reduction since the above benchmarks also include the runner side setup and JMH overhead:
   * -0.587% for processBundle on larger bundles
   * -0.282% for processBundle on smaller bundles
   
   Future work would be to update msec counters which are also on the hot path and reduce the cost of state tracking.
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] [**Choose reviewer(s)**](https://beam.apache.org/contribute/#make-your-change) and mention them in a comment (`R: @username`).
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://beam.apache.org/contribute/#make-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] Abacn commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
Abacn commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906437803


##########
runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java:
##########
@@ -30,6 +30,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import com.google.common.collect.ImmutableList;

Review Comment:
   Just note that JavaCommit checkStyle is failing on master and should be fixed some, and please check the checkStyle before merge



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163900808

   Run Java PreCommit


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163637450

   I think that reviewing the interaction with the ProcessBundleHandler and the new metrics class E2E will provide the best context and review quality vs splitting this up. I was planning on throwing in more changes but thought that this was a reasonably sized change. See the follow-up in https://github.com/apache/beam/pull/22005


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163495103

   R: @apilloud @TheNeuralBit 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r907880931


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -138,24 +158,11 @@ public <T> void register(
             labelsMetadata);
     executionStates.register(state);
 
-    pCollectionIdsToConsumers.put(
-        pCollectionId,
+    List<ConsumerAndMetadata> consumerAndMetadatas =
+        pCollectionIdsToConsumers.computeIfAbsent(pCollectionId, (unused) -> new ArrayList<>());
+    consumerAndMetadatas.add(
         ConsumerAndMetadata.forConsumer(
-            consumer,
-            pTransformId,
-            state,
-            valueCoder,
-            metricsContainerRegistry.getContainer(pTransformId)));
-  }
-
-  /** Reset the execution states of the registered functions. */
-  public void reset() {

Review Comment:
   nit: it looks like this just moved ~40 lines but didn't change...



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -663,10 +695,47 @@ private ImmutableMap<String, ByteString> monitoringData(BundleProcessor bundlePr
         ByteString payload = monitoringInfo.getPayload();
         String shortId =
             shortIds.getOrCreateShortId(monitoringInfo.toBuilder().clearPayload().build());
-        result.put(shortId, payload);
+        monitoringData.put(shortId, payload);
       }
     }
-    return result.build();
+    bundleProcessor
+        .getBundleProgressReporterAndRegistrar()
+        .updateIntermediateMonitoringData(monitoringData);

Review Comment:
   I'm not finding where either IntermediateMonitoringData or FinalMonitoringData below is used. It looks like they are being newly set in this change. Are they unused? What am I missing?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -209,44 +235,59 @@ public Map<String, ByteString> getExecutionTimeMonitoringData(ShortIdMap shortId
   private class MetricTrackingFnDataReceiver<T> implements FnDataReceiver<WindowedValue<T>> {
     private final FnDataReceiver<WindowedValue<T>> delegate;
     private final SimpleExecutionState state;
-    private final Counter unboundedElementCountCounter;
-    private final SampleByteSizeDistribution<T> unboundedSampledByteSizeDistribution;
+    private final BundleCounter elementCountCounter;
+    private final SampleByteSizeDistribution<T> sampledByteSizeDistribution;
     private final Coder<T> coder;
     private final MetricsContainer metricsContainer;
 
     public MetricTrackingFnDataReceiver(
-        String pCollectionId, ConsumerAndMetadata consumerAndMetadata) {
+        String pCollectionId, Coder<T> coder, ConsumerAndMetadata consumerAndMetadata) {
       this.delegate = consumerAndMetadata.getConsumer();
       this.state = consumerAndMetadata.getExecutionState();
-      HashMap<String, String> labels = new HashMap<String, String>();
-      labels.put(Labels.PCOLLECTION, pCollectionId);
-
-      // Collect the metric in a metric container which is not bound to the step name.
-      // This is required to count elements from impulse steps, which will produce elements outside
-      // of a pTransform context.
-      MetricsContainer unboundMetricContainer = metricsContainerRegistry.getUnboundContainer();
 
+      HashMap<String, String> labels = new HashMap<>();
+      labels.put(Labels.PCOLLECTION, pCollectionId);

Review Comment:
   nit: looks like this line didn't change at all but the surrounding whitespace did...



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906414654


##########
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/ShortIdMap.java:
##########
@@ -48,4 +53,30 @@ public synchronized MonitoringInfo get(String shortId) {
     }
     return monitoringInfo;
   }
+
+  public synchronized Map<String, MonitoringInfo> get(List<String> shortIds) {
+    Map<String, MonitoringInfo> monitoringInfos = new HashMap<>(shortIds.size());

Review Comment:
   Slower as well and leads to additional object creation.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906608480


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe

Review Comment:
   The thread model of this is a little confusing. It appears the BundleProgressReporter and Counter interface can be called from different threads but otherwise aren't thread safe. Merging the two interfaces muddles that a bit and I fear it will eventually get misused.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906412524


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleCounter implements BundleCounter {
+    private final MetricName name;
+    private final String shortId;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private boolean hasReportedValue;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private long lastReportedValue;
+
+    private final AtomicLong lazyCount;
+    private long count;
+
+    public SerialMutatorAndFinalReaderBundleCounter(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.lazyCount = new AtomicLong();
+    }
+
+    @Override
+    public void inc() {
+      count += 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void inc(long n) {
+      count += n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec() {
+      count -= 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec(long n) {
+      count -= n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      long valueToReport = lazyCount.get();
+      if (hasReportedValue && valueToReport == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(valueToReport));
+      lastReportedValue = valueToReport;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (hasReportedValue && count == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(count));
+      lastReportedValue = count;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void reset() {
+      if (hasReportedValue) {
+        count = 0;
+        lazyCount.set(count);
+        lastReportedValue = 0;
+      }
+    }
+  }
+
+  /**
+   * A {@link Distribution} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleDistribution implements BundleDistribution {
+    private final MetricName name;
+    private final String shortId;
+    @Nullable private DistributionData lastReportedValue;
+    private AtomicReference<DistributionData> lazyData;
+    // Consider using a strategy that doesn't create a new object on each update
+    private DistributionData data;
+
+    public SerialMutatorAndFinalReaderBundleDistribution(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.data = DistributionData.EMPTY;
+      this.lazyData = new AtomicReference<>(data);
+      this.lastReportedValue = null;
+    }
+
+    @Override
+    public void update(long value) {
+      data = data.combine(value);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public void update(long sum, long count, long min, long max) {
+      data = data.combine(sum, count, min, max);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      DistributionData valueToReport = lazyData.get();
+      if (valueToReport.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(lazyData.get()));
+      lastReportedValue = valueToReport;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (data.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(data));
+      lastReportedValue = data;
+    }
+
+    @Override
+    public void reset() {
+      // Use faster equality check
+      if (lastReportedValue != null && lastReportedValue != DistributionData.EMPTY) {
+        data = DistributionData.EMPTY;
+        lazyData.set(DistributionData.EMPTY);
+        lastReportedValue = DistributionData.EMPTY;

Review Comment:
   We want to be able to report the metric at least once which is why null is used to mark that it has never been reported.
   
   This and the counter version have coverage for this case in MetricsTest.java



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906515732


##########
runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java:
##########
@@ -30,6 +30,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import com.google.common.collect.ImmutableList;

Review Comment:
   thanks for the catch



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r908625158


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -663,10 +695,47 @@ private ImmutableMap<String, ByteString> monitoringData(BundleProcessor bundlePr
         ByteString payload = monitoringInfo.getPayload();
         String shortId =
             shortIds.getOrCreateShortId(monitoringInfo.toBuilder().clearPayload().build());
-        result.put(shortId, payload);
+        monitoringData.put(shortId, payload);
       }
     }
-    return result.build();
+    bundleProcessor
+        .getBundleProgressReporterAndRegistrar()
+        .updateIntermediateMonitoringData(monitoringData);

Review Comment:
   intermediateMonitoringData is used at ProcessBundleHandler#655 as part of the bundle progress request
   finalMonitoringData is used at ProcessBundleHandler#560 when the bundle completes processing of user code and final metrics are gathered



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163558923

   Thanks, this seems awesome. Is it possible to break this up into smaller PRs?
   
   (Between leaves, beam summit, and oncall rotations it is unlikely that I will have time for a large review until August, but this is on my todo list if I get time. Don't consider my review a blocker.)
   
   cc: @emilymye 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik merged pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik merged PR #22002:
URL: https://github.com/apache/beam/pull/22002


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r907870946


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -274,13 +280,15 @@ private void createRunnerAndConsumersForPTransformRecursively(
     if (!pTransform.hasSpec()) {
       throw new IllegalArgumentException(
           String.format(
-              "Cannot process transform with no spec: %s", TextFormat.printToString(pTransform)));
+              "Cannot process transform with no spec: %s",
+              TextFormat.printer().printToString(pTransform)));

Review Comment:
   Mixing cleanup changes and functional changes increases the size of the change. Large changes are more difficult to review and more difficult to investigate when they cause breakages. (This is a nit.)



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906294885


##########
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/ShortIdMap.java:
##########
@@ -48,4 +53,30 @@ public synchronized MonitoringInfo get(String shortId) {
     }
     return monitoringInfo;
   }
+
+  public synchronized Map<String, MonitoringInfo> get(List<String> shortIds) {
+    Map<String, MonitoringInfo> monitoringInfos = new HashMap<>(shortIds.size());

Review Comment:
   nit: Use ImmutableMap.Builder?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -274,13 +280,15 @@ private void createRunnerAndConsumersForPTransformRecursively(
     if (!pTransform.hasSpec()) {
       throw new IllegalArgumentException(
           String.format(
-              "Cannot process transform with no spec: %s", TextFormat.printToString(pTransform)));
+              "Cannot process transform with no spec: %s",
+              TextFormat.printer().printToString(pTransform)));

Review Comment:
   I'm not sure what the relation is between this and the rest of the change.



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe

Review Comment:
   If I understand correctly, this doesn't apply to updateIntermediateMonitoringData?



##########
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/ShortIdMap.java:
##########
@@ -48,4 +53,30 @@ public synchronized MonitoringInfo get(String shortId) {
     }
     return monitoringInfo;
   }
+
+  public synchronized Map<String, MonitoringInfo> get(List<String> shortIds) {
+    Map<String, MonitoringInfo> monitoringInfos = new HashMap<>(shortIds.size());
+    for (String shortId : shortIds) {
+      MonitoringInfo info = monitoringInfoMap.get(shortId);
+      if (info == null) {
+        throw new NoSuchElementException(shortId);
+      }
+      monitoringInfos.put(shortId, info);
+    }
+    return monitoringInfos;
+  }
+
+  public synchronized Iterable<MonitoringInfo> toMonitoringInfo(
+      Map<String, ByteString> shortIdToData) {
+    List<MonitoringInfo> monitoringInfos = new ArrayList<>(shortIdToData.size());

Review Comment:
   nit: Use ImmutableList.Builder?



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleCounter implements BundleCounter {
+    private final MetricName name;
+    private final String shortId;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private boolean hasReportedValue;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private long lastReportedValue;
+
+    private final AtomicLong lazyCount;
+    private long count;
+
+    public SerialMutatorAndFinalReaderBundleCounter(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.lazyCount = new AtomicLong();
+    }
+
+    @Override
+    public void inc() {
+      count += 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void inc(long n) {
+      count += n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec() {
+      count -= 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec(long n) {
+      count -= n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      long valueToReport = lazyCount.get();
+      if (hasReportedValue && valueToReport == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(valueToReport));
+      lastReportedValue = valueToReport;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (hasReportedValue && count == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(count));
+      lastReportedValue = count;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void reset() {
+      if (hasReportedValue) {
+        count = 0;
+        lazyCount.set(count);
+        lastReportedValue = 0;
+      }
+    }
+  }
+
+  /**
+   * A {@link Distribution} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleDistribution implements BundleDistribution {
+    private final MetricName name;
+    private final String shortId;
+    @Nullable private DistributionData lastReportedValue;
+    private AtomicReference<DistributionData> lazyData;
+    // Consider using a strategy that doesn't create a new object on each update
+    private DistributionData data;
+
+    public SerialMutatorAndFinalReaderBundleDistribution(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.data = DistributionData.EMPTY;
+      this.lazyData = new AtomicReference<>(data);
+      this.lastReportedValue = null;
+    }
+
+    @Override
+    public void update(long value) {
+      data = data.combine(value);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public void update(long sum, long count, long min, long max) {
+      data = data.combine(sum, count, min, max);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      DistributionData valueToReport = lazyData.get();
+      if (valueToReport.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(lazyData.get()));
+      lastReportedValue = valueToReport;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (data.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(data));
+      lastReportedValue = data;
+    }
+
+    @Override
+    public void reset() {
+      // Use faster equality check
+      if (lastReportedValue != null && lastReportedValue != DistributionData.EMPTY) {
+        data = DistributionData.EMPTY;
+        lazyData.set(DistributionData.EMPTY);
+        lastReportedValue = DistributionData.EMPTY;

Review Comment:
   Should this be `lastReportedValue = null;`? Or is `DistributionData.EMPTY` a reasonable default that would allow you to remove the `null`?



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163633334

   Run Python_PVR_Flink PreCommit


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1165816984

   Run Java PreCommit


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r908622093


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -209,44 +235,59 @@ public Map<String, ByteString> getExecutionTimeMonitoringData(ShortIdMap shortId
   private class MetricTrackingFnDataReceiver<T> implements FnDataReceiver<WindowedValue<T>> {
     private final FnDataReceiver<WindowedValue<T>> delegate;
     private final SimpleExecutionState state;
-    private final Counter unboundedElementCountCounter;
-    private final SampleByteSizeDistribution<T> unboundedSampledByteSizeDistribution;
+    private final BundleCounter elementCountCounter;
+    private final SampleByteSizeDistribution<T> sampledByteSizeDistribution;
     private final Coder<T> coder;
     private final MetricsContainer metricsContainer;
 
     public MetricTrackingFnDataReceiver(
-        String pCollectionId, ConsumerAndMetadata consumerAndMetadata) {
+        String pCollectionId, Coder<T> coder, ConsumerAndMetadata consumerAndMetadata) {
       this.delegate = consumerAndMetadata.getConsumer();
       this.state = consumerAndMetadata.getExecutionState();
-      HashMap<String, String> labels = new HashMap<String, String>();
-      labels.put(Labels.PCOLLECTION, pCollectionId);
-
-      // Collect the metric in a metric container which is not bound to the step name.
-      // This is required to count elements from impulse steps, which will produce elements outside
-      // of a pTransform context.
-      MetricsContainer unboundMetricContainer = metricsContainerRegistry.getUnboundContainer();
 
+      HashMap<String, String> labels = new HashMap<>();
+      labels.put(Labels.PCOLLECTION, pCollectionId);

Review Comment:
   I grouped together the logical portion of creating this counter which was broken up before.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r907573235


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleCounter implements BundleCounter {
+    private final MetricName name;
+    private final String shortId;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private boolean hasReportedValue;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private long lastReportedValue;
+
+    private final AtomicLong lazyCount;
+    private long count;
+
+    public SerialMutatorAndFinalReaderBundleCounter(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.lazyCount = new AtomicLong();
+    }
+
+    @Override
+    public void inc() {
+      count += 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void inc(long n) {
+      count += n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec() {
+      count -= 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec(long n) {
+      count -= n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      long valueToReport = lazyCount.get();
+      if (hasReportedValue && valueToReport == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(valueToReport));
+      lastReportedValue = valueToReport;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (hasReportedValue && count == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(count));
+      lastReportedValue = count;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void reset() {
+      if (hasReportedValue) {
+        count = 0;
+        lazyCount.set(count);
+        lastReportedValue = 0;
+      }
+    }
+  }
+
+  /**
+   * A {@link Distribution} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleDistribution implements BundleDistribution {
+    private final MetricName name;
+    private final String shortId;
+    @Nullable private DistributionData lastReportedValue;
+    private AtomicReference<DistributionData> lazyData;
+    // Consider using a strategy that doesn't create a new object on each update
+    private DistributionData data;
+
+    public SerialMutatorAndFinalReaderBundleDistribution(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.data = DistributionData.EMPTY;
+      this.lazyData = new AtomicReference<>(data);
+      this.lastReportedValue = null;
+    }
+
+    @Override
+    public void update(long value) {
+      data = data.combine(value);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public void update(long sum, long count, long min, long max) {
+      data = data.combine(sum, count, min, max);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      DistributionData valueToReport = lazyData.get();
+      if (valueToReport.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(lazyData.get()));
+      lastReportedValue = valueToReport;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (data.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(data));
+      lastReportedValue = data;
+    }
+
+    @Override
+    public void reset() {
+      // Use faster equality check
+      if (lastReportedValue != null && lastReportedValue != DistributionData.EMPTY) {
+        data = DistributionData.EMPTY;
+        lazyData.set(DistributionData.EMPTY);
+        lastReportedValue = DistributionData.EMPTY;

Review Comment:
   yeah, its so we don't need a boolean hasReportedValue like in the counter version



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r907571003


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe

Review Comment:
   I think the issue is that it isn't thread safe to be called from arbitrary threads but is thread safe if used under a specific pattern.
   
   The thread interaction boils down to who owns:
   * (A) updating the counter
   * (B) reading intermediate progress
   * (C) reading final progress
   * (D) performing the reset
   
   The currently added counter requires A, C, D to be done via one thread or under a lock and B, C, D to be done either via one thread or while under a lock. The current setup has the main processing thread do A, C, D since it is one thread that does these always and B, C, D via lock.
   
   To address your concerns I simplified the comments down to how to use vs the general thread safety semantics which should help a lot in having them not used inappropriately.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906609368


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleCounter implements BundleCounter {
+    private final MetricName name;
+    private final String shortId;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private boolean hasReportedValue;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private long lastReportedValue;
+
+    private final AtomicLong lazyCount;
+    private long count;
+
+    public SerialMutatorAndFinalReaderBundleCounter(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.lazyCount = new AtomicLong();
+    }
+
+    @Override
+    public void inc() {
+      count += 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void inc(long n) {
+      count += n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec() {
+      count -= 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec(long n) {
+      count -= n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      long valueToReport = lazyCount.get();
+      if (hasReportedValue && valueToReport == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(valueToReport));
+      lastReportedValue = valueToReport;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (hasReportedValue && count == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(count));
+      lastReportedValue = count;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void reset() {
+      if (hasReportedValue) {
+        count = 0;
+        lazyCount.set(count);
+        lastReportedValue = 0;
+      }
+    }
+  }
+
+  /**
+   * A {@link Distribution} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleDistribution implements BundleDistribution {
+    private final MetricName name;
+    private final String shortId;
+    @Nullable private DistributionData lastReportedValue;
+    private AtomicReference<DistributionData> lazyData;
+    // Consider using a strategy that doesn't create a new object on each update
+    private DistributionData data;
+
+    public SerialMutatorAndFinalReaderBundleDistribution(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.data = DistributionData.EMPTY;
+      this.lazyData = new AtomicReference<>(data);
+      this.lastReportedValue = null;
+    }
+
+    @Override
+    public void update(long value) {
+      data = data.combine(value);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public void update(long sum, long count, long min, long max) {
+      data = data.combine(sum, count, min, max);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      DistributionData valueToReport = lazyData.get();
+      if (valueToReport.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(lazyData.get()));
+      lastReportedValue = valueToReport;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (data.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(data));
+      lastReportedValue = data;
+    }
+
+    @Override
+    public void reset() {
+      // Use faster equality check
+      if (lastReportedValue != null && lastReportedValue != DistributionData.EMPTY) {
+        data = DistributionData.EMPTY;
+        lazyData.set(DistributionData.EMPTY);
+        lastReportedValue = DistributionData.EMPTY;

Review Comment:
   Ok, so setting `lastReportedValue = DistributionData.EMPTY` is effectively an optimization so we don't report the empty value again after reset.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1163493950

   ![tiny bundle](https://user-images.githubusercontent.com/10078956/175115408-882e810f-07ca-4d94-b231-deb2a177ad66.png)
   ![large bundle](https://user-images.githubusercontent.com/10078956/175115423-76f92110-1cdb-40ca-9e0c-cd69e992d968.png)
   
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r906411734


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe

Review Comment:
   It is still not thread safe since a lock must be hold when invoking this as the lastReportedValue is unguarded.



##########
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/ShortIdMap.java:
##########
@@ -48,4 +53,30 @@ public synchronized MonitoringInfo get(String shortId) {
     }
     return monitoringInfo;
   }
+
+  public synchronized Map<String, MonitoringInfo> get(List<String> shortIds) {
+    Map<String, MonitoringInfo> monitoringInfos = new HashMap<>(shortIds.size());
+    for (String shortId : shortIds) {
+      MonitoringInfo info = monitoringInfoMap.get(shortId);
+      if (info == null) {
+        throw new NoSuchElementException(shortId);
+      }
+      monitoringInfos.put(shortId, info);
+    }
+    return monitoringInfos;
+  }
+
+  public synchronized Iterable<MonitoringInfo> toMonitoringInfo(
+      Map<String, ByteString> shortIdToData) {
+    List<MonitoringInfo> monitoringInfos = new ArrayList<>(shortIdToData.size());

Review Comment:
   It's slower, using array list with a known size is the fastest and also leads to more object creation then needed.



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -274,13 +280,15 @@ private void createRunnerAndConsumersForPTransformRecursively(
     if (!pTransform.hasSpec()) {
       throw new IllegalArgumentException(
           String.format(
-              "Cannot process transform with no spec: %s", TextFormat.printToString(pTransform)));
+              "Cannot process transform with no spec: %s",
+              TextFormat.printer().printToString(pTransform)));

Review Comment:
   The method was deprecated so I swapped to the undeprecated version.



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/Metrics.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.control;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.beam.fn.harness.control.ProcessBundleHandler.BundleProcessor;
+import org.apache.beam.runners.core.metrics.DistributionData;
+import org.apache.beam.runners.core.metrics.MonitoringInfoEncodings;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Distribution;
+import org.apache.beam.sdk.metrics.MetricName;
+import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
+
+public class Metrics {
+
+  /**
+   * A {@link Counter} that is designed to report intermediate and final results and can be re-used
+   * after being reset.
+   */
+  public interface BundleCounter extends BundleProgressReporter, Counter {}
+
+  /**
+   * A {@link Distribution} that is designed to report intermediate and final results and can be
+   * re-used after being reset.
+   */
+  public interface BundleDistribution extends BundleProgressReporter, Distribution {}
+
+  /**
+   * Returns a counter that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Counter} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Counter} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleCounter serialMutatorAndFinalReaderBundleCounter(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleCounter(shortId, name);
+  }
+
+  /**
+   * Returns a {@link Distribution} that will report an accurate final value.
+   *
+   * <p>All invocations to {@link Distribution} methods, {@link
+   * BundleProgressReporter#updateFinalMonitoringData}, and {@link BundleProgressReporter#reset()}
+   * must be done by the same thread.
+   *
+   * <p>All invocations to {@link BundleProgressReporter} methods must be done serially.
+   *
+   * <p>Invocations to {@link Distribution} methods can be done concurrently to {@link
+   * BundleProgressReporter#updateIntermediateMonitoringData}.
+   */
+  public static BundleDistribution serialMutatorAndFinalReaderBundleDistribution(
+      String shortId, MetricName name) {
+    return new SerialMutatorAndFinalReaderBundleDistribution(shortId, name);
+  }
+
+  /**
+   * A {@link Counter} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleCounter implements BundleCounter {
+    private final MetricName name;
+    private final String shortId;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private boolean hasReportedValue;
+    /** Guarded by {@link BundleProcessor#getProgressRequestLock}. */
+    private long lastReportedValue;
+
+    private final AtomicLong lazyCount;
+    private long count;
+
+    public SerialMutatorAndFinalReaderBundleCounter(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.lazyCount = new AtomicLong();
+    }
+
+    @Override
+    public void inc() {
+      count += 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void inc(long n) {
+      count += n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec() {
+      count -= 1;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public void dec(long n) {
+      count -= n;
+      lazyCount.lazySet(count);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      long valueToReport = lazyCount.get();
+      if (hasReportedValue && valueToReport == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(valueToReport));
+      lastReportedValue = valueToReport;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (hasReportedValue && count == lastReportedValue) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Counter(count));
+      lastReportedValue = count;
+      hasReportedValue = true;
+    }
+
+    @Override
+    public void reset() {
+      if (hasReportedValue) {
+        count = 0;
+        lazyCount.set(count);
+        lastReportedValue = 0;
+      }
+    }
+  }
+
+  /**
+   * A {@link Distribution} that shares the data using {@link AtomicReference#lazySet} to reduce
+   * synchronization overhead. This guarantees that intermediate progress reports will report a
+   * value that has been recently updated while the final progress report will get the true final
+   * value.
+   */
+  @NotThreadSafe
+  private static class SerialMutatorAndFinalReaderBundleDistribution implements BundleDistribution {
+    private final MetricName name;
+    private final String shortId;
+    @Nullable private DistributionData lastReportedValue;
+    private AtomicReference<DistributionData> lazyData;
+    // Consider using a strategy that doesn't create a new object on each update
+    private DistributionData data;
+
+    public SerialMutatorAndFinalReaderBundleDistribution(String shortId, MetricName name) {
+      this.shortId = shortId;
+      this.name = name;
+      this.data = DistributionData.EMPTY;
+      this.lazyData = new AtomicReference<>(data);
+      this.lastReportedValue = null;
+    }
+
+    @Override
+    public void update(long value) {
+      data = data.combine(value);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public void update(long sum, long count, long min, long max) {
+      data = data.combine(sum, count, min, max);
+      lazyData.lazySet(data);
+    }
+
+    @Override
+    public MetricName getName() {
+      return name;
+    }
+
+    @Override
+    public void updateIntermediateMonitoringData(Map<String, ByteString> monitoringData) {
+      DistributionData valueToReport = lazyData.get();
+      if (valueToReport.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(lazyData.get()));
+      lastReportedValue = valueToReport;
+    }
+
+    @Override
+    public void updateFinalMonitoringData(Map<String, ByteString> monitoringData) {
+      if (data.equals(lastReportedValue)) {
+        return;
+      }
+      monitoringData.put(shortId, MonitoringInfoEncodings.encodeInt64Distribution(data));
+      lastReportedValue = data;
+    }
+
+    @Override
+    public void reset() {
+      // Use faster equality check
+      if (lastReportedValue != null && lastReportedValue != DistributionData.EMPTY) {
+        data = DistributionData.EMPTY;
+        lazyData.set(DistributionData.EMPTY);
+        lastReportedValue = DistributionData.EMPTY;

Review Comment:
   We want to be able to report the metric at least once which is why null is used to mark that it has never been reported.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1165946152

   @apilloud Thanks for the review. PTAL


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lukecwik commented on pull request #22002: [BEAM-13015, #21250] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
lukecwik commented on PR #22002:
URL: https://github.com/apache/beam/pull/22002#issuecomment-1164540118

   Run Java PreCommit


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] apilloud commented on a diff in pull request #22002: [BEAM-13015, #21250, fixes #22053] Improve PCollectionConsumerRegistry performance by swapping element count and sampled byte size to use a faster counter.

Posted by GitBox <gi...@apache.org>.
apilloud commented on code in PR #22002:
URL: https://github.com/apache/beam/pull/22002#discussion_r907870946


##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java:
##########
@@ -274,13 +280,15 @@ private void createRunnerAndConsumersForPTransformRecursively(
     if (!pTransform.hasSpec()) {
       throw new IllegalArgumentException(
           String.format(
-              "Cannot process transform with no spec: %s", TextFormat.printToString(pTransform)));
+              "Cannot process transform with no spec: %s",
+              TextFormat.printer().printToString(pTransform)));

Review Comment:
   Mixing cleanup changes and functional changes increases the size of the change. Large changes are more difficult to review and more difficult to investigate when they cause breakages.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org