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


##########
sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/BatchElements.java:
##########
@@ -469,25 +570,41 @@ public void setup() {
     public void startBundle() {
       batch = new ArrayList<>();
       runningBatchSize = 0;
+      runningBatchWeight = 0L;
       targetBatchSize = estimator.nextBatchSize();
     }
 
     @ProcessElement
     public void processElement(@Element T element, OutputReceiver<List<T>> 
receiver) {
-      int elementSize = 1;
-      if (runningBatchSize + elementSize > targetBatchSize) {
-        if (runningBatchSize > 0 && !batch.isEmpty()) {
-          try (BatchElements.BatchSizeEstimator.Stopwatch sw =
-              estimator.recordTime(runningBatchSize)) {
-            receiver.output(batch); // emit full batch downstream
-          }
+      int elementSize;
+      long elementWeight;
+      if (maxBatchWeight == null) {
+        elementSize = measureElementSize(elementSizeFn, element);
+        elementWeight = 0L;
+      } else {
+        elementSize = 1;
+        elementWeight = measureElementSize(elementSizeFn, element);
+      }
+
+      boolean wouldExceedSize = runningBatchSize + (long) elementSize > 
targetBatchSize;
+      boolean wouldExceedWeight =
+          maxBatchWeight != null && runningBatchWeight > maxBatchWeight - 
elementWeight;
+
+      // Never emit an empty batch: an element that exceeds the limits on its 
own
+      // is emitted in a batch by itself.
+      if (!batch.isEmpty() && (wouldExceedSize || wouldExceedWeight)) {
+        try (BatchElements.BatchSizeEstimator.Stopwatch sw =
+            estimator.recordTime(runningBatchSize)) {

Review Comment:
   Now that `elementSizeFn` can return `0` and `GlobalWindowsBatchingDoFn` 
rightly emits size-0 batches (removing the `runningBatchSize > 0` check), 
`estimator.recordTime(0)` can be called during warmup (`ignoreNextTiming == 
true`).
   
   In `BatchSizeEstimator.Stopwatch.close()` (line 395), that sets 
`replayLastBatchSize = Math.min(0, config.maxBatchSize) = 0`. Unlike Python 
(`if self._replay_last_batch_size:`, where `0` is falsy), Java checks `if 
(replayLastBatchSize != null)` (line 525), so `nextBatchSize()` returns 
`targetBatchSize = 0` — even for `constantConfig(10)` (`minBatchSize == 
maxBatchSize == 10`) — and sets `ignoreNextTiming = true` again, causing 
subsequent non-empty elements to be emitted as singletons.
   
   Guarding and clamping in `Stopwatch.close()`, e.g.:
   ```java
   if (batchSize > 0) {
     replayLastBatchSize =
         Math.max(config.minBatchSize, Math.min(batchSize, 
config.maxBatchSize));
   }
   ```
   avoids replaying `0` (and prevents partial/weight-limited batches from 
temporarily dropping `targetBatchSize` below `minBatchSize`).



##########
sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/BatchElementsTest.java:
##########
@@ -104,6 +106,35 @@ public void 
testBatchConfigNegativeFixedCostDurationThrows() {
     
BatchElements.BatchConfig.builder().withTargetBatchDurationSecsWithFixedCost(-5.0).build();
   }
 
+  // Element sizing & max batch weight validation
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testMaxBatchWeightZeroThrows() {
+    
BatchElements.<String>withDefaults().withElementSizeFn(String::length).withMaxBatchWeight(0);
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testMaxBatchWeightNegativeThrows() {
+    
BatchElements.<String>withDefaults().withElementSizeFn(String::length).withMaxBatchWeight(-10);
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testNullConfigThrows() {
+    BatchElements.<String>withConfig(null);
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testNullElementSizeFnThrows() {
+    BatchElements.<String>withDefaults().withElementSizeFn(null);
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testMaxBatchWeightRequiresElementSizeFn() {

Review Comment:
   Please add `pipeline.enableAbandonedNodeEnforcement(false);` at the start of 
`testMaxBatchWeightRequiresElementSizeFn()`. Because JUnit 4's `@Test(expected 
= ...)` catches the exception inside `@Rule TestPipeline`, this test will fail 
with `PipelineRunMissingException` whenever run against a real runner (rather 
than `CrashingRunner`).
   
   (Optional nit on the tests below: since the `@Category(NeedsRunner.class)` 
tests are excluded from `:sdks:java:core:test` and only assert upper bounds to 
tolerate runner bundle splits, an implementation that always emits singletons 
would still pass them. Consider adding a couple of direct single-bundle unit 
tests invoking `GlobalWindowsBatchingDoFn` / `WindowAwareBatchingDoFn` to 
assert exact batch boundaries, including a size-0 element followed by non-empty 
elements for the `replayLastBatchSize` case above.)



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