damccorm commented on code in PR #41692:
URL: https://github.com/apache/beam/pull/41692#discussion_r4744097616


##########
sdks/java/core/src/main/java/org/apache/beam/sdk/util/common/ElementByteSizeObserver.java:
##########
@@ -66,14 +81,25 @@ public void setScalingFactor(double scalingFactor) {
   @Override
   public void update(Observable obs, Object obj) {
     if (obj instanceof Long) {
-      totalSize += (long) (scalingFactor * (Long) obj);
+      update(((Long) obj).longValue());
     } else if (obj instanceof Integer) {
-      totalSize += (long) (scalingFactor * (Integer) obj);
+      update(((Integer) obj).longValue());
     } else {
       throw new AssertionError("unexpected parameter object");
     }
   }
 
+  /**
+   * Resets any accumulated byte size, lazy state, and scaling factor to 
{@code 1.0} without
+   * reporting. Unlike {@link #advance()}, this clears the scaling factor so a 
reused observer does
+   * not inherit a prior element's scaling factor.
+   */
+  public void reset() {

Review Comment:
   Adding `public void reset()` here will break compilation of 
`:sdks:java:core:jmh` on `master`, where 
`ElementByteSizeObservableBenchmark.BaseAccumulatingByteSizeObserver` (added in 
#41537) defines a package-private `void reset()` (line 121). Note also that 
`scaledByteSizeObserver` sets `scalingFactor = 1.5` once in 
`@Setup(Level.Trial)` (line 191) and calls `reset()` in 
`@Setup(Level.Iteration)` (line 259), so widening it and calling 
`super.reset()` would silently reset `scalingFactor` back to `1.0`.
   
   Since `ByteSizeObserver.reportElementSize` only updates `observedSize`, the 
cleanest option may be to drop the `sdks/java/core` edits altogether and 
implement `reset()` privately on `ByteSizeObserver`:
   ```java
   void reset() {
     advance();
     setScalingFactor(1.0);
     observedSize = 0;
   }
   ```
   (Alternatively, if you'd prefer to keep `ElementByteSizeObserver.reset()`, 
please also update `BaseAccumulatingByteSizeObserver` in 
`ElementByteSizeObservableBenchmark.java` without resetting `scalingFactor`, 
and add the `TestElementByteSizeObserver.reset()` test mentioned in the PR 
description.)



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -517,80 +523,165 @@ private static class ByteSizeObserver extends 
ElementByteSizeObserver {
       protected void reportElementSize(long elementSize) {
         observedSize += elementSize;
       }
+
+      @Override
+      public void reset() {
+        super.reset();
+        observedSize = 0;
+      }
     }
 
-    final Distribution distribution;
-    ByteSizeObserver byteCountObserver;
+    private final Distribution distribution;
+    private final @Nullable Random randomOverride;
+    private ByteSizeObserver reusableObserver = new ByteSizeObserver();
+    private @Nullable ByteSizeObserver pendingLazyObserver = null;
 
     public SampleByteSizeDistribution(Distribution distribution) {
+      this(distribution, null);
+    }
+
+    @VisibleForTesting
+    SampleByteSizeDistribution(Distribution distribution, @Nullable Random 
randomGenerator) {
       this.distribution = distribution;
-      this.byteCountObserver = null;
+      this.randomOverride = randomGenerator;
+    }
+
+    private Random random() {
+      return randomOverride != null ? randomOverride : 
ThreadLocalRandom.current();
     }
 
     public void tryUpdate(T value, Coder<T> coder) throws Exception {
+      // Clear any pending lazy observer from a prior element that exited 
abnormally.
+      if (pendingLazyObserver != null) {
+        pendingLazyObserver = null;
+      }
       if (shouldSampleElement()) {
-        // First try using byte size observer
-        byteCountObserver = new ByteSizeObserver();
-        coder.registerByteSizeObserver(value, byteCountObserver);
+        recordSample(value, coder);
+      }
+    }
 
-        if (!byteCountObserver.getIsLazy()) {
-          byteCountObserver.advance();
-          this.distribution.update(byteCountObserver.observedSize);
+    private void recordSample(T value, Coder<T> coder) throws Exception {
+      ByteSizeObserver observer = reusableObserver;
+      observer.reset();
+      try {
+        coder.registerByteSizeObserver(value, observer);
+      } catch (Exception | Error e) {
+        if (observer.getIsLazy()) {

Review Comment:
   Optional nit: on this exceptional slow path, consider replacing 
`reusableObserver = new ByteSizeObserver()` unconditionally (matching 
`ElementByteSizeCounter`) rather than gating on `observer.getIsLazy()`. 
Built-in `IterableLikeCoder` sets `setLazy()` before `addObserver(...)`, so 
it's covered, but an unconditional reset also protects against custom coders 
that attach the observer before calling `setLazy()` and throw in between, at 
zero fast-path cost.
   
   (Also tiny wording nit on line 570: the iterable/stream retains a reference 
to the observer, rather than vice versa.)



##########
sdks/java/core/src/main/java/org/apache/beam/sdk/util/common/ElementByteSizeObserver.java:
##########
@@ -53,6 +53,21 @@ public boolean getIsLazy() {
     return isLazy;
   }
 
+  /**
+   * Updates the observer with the byte size of an element piece without 
boxing.
+   *
+   * <p>Subclasses that override {@link #update(Object)} or {@link 
#update(Observable, Object)} must
+   * also override this method if they intercept all updates, as this method 
updates internal state
+   * directly rather than delegating to those overloads.
+   */
+  public void update(long bytes) {

Review Comment:
   PR #41537 (`1b6e977f6ed`) landed on `master` and already updated 
`ElementByteSizeObserver` to extend `PrimitiveByteSizeObserver`, added 
`@Override public void update(long byteSize)`, and added `@Nullable` 
annotations on `update(Observable, Object)`. Please rebase onto `master` and 
drop the duplicate `update` changes.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to