github-actions[bot] commented on code in PR #41468:
URL: https://github.com/apache/beam/pull/41468#discussion_r4623183639


##########
sdks/java/core/src/main/java/org/apache/beam/sdk/util/BundleLifter.java:
##########
@@ -57,89 +90,311 @@ public class BundleLifter<T> extends 
PTransform<PCollection<T>, PCollectionTuple
 
   final TupleTag<T> smallBatchTag;
   final TupleTag<T> largeBatchTag;
-  final int threshold;
+  final long threshold;
+  final long maxBufferedBytes;
+  final int maxLiftedKeys;
   final SerializableFunction<T, Integer> elementSizer;
+  final @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn;
+
+  /** The default memory cap: twice the threshold. */
+  static long defaultMaxBufferedBytes(long threshold) {
+    return threshold > Long.MAX_VALUE / 2 ? Long.MAX_VALUE : 2 * threshold;
+  }
 
   /**
-   * A DoFn that buffers elements within a bundle and outputs them to 
different tags in
-   * finish_bundle based on the total bundle size.
+   * A DoFn that buffers elements per key within a bundle and outputs them to 
the large tag once a
+   * key reaches the threshold, or to the small tag otherwise.
    *
    * @param <T> The type of elements being processed.
    */
   static class BundleLiftDoFn<T> extends DoFn<T, Void> {
     private static final Logger LOG = 
LoggerFactory.getLogger(BundleLiftDoFn.class);
 
+    /** The key shared by all elements without a key, or whose key function 
returns null. */
+    private static final Object UNKEYED = new Object();
+
     final TupleTag<T> smallBatchTag;
     final TupleTag<T> largeBatchTag;
-    final int threshold;
+    final long threshold;
+    final long maxBufferedBytes;
+    final int maxLiftedKeys;
     final SerializableFunction<T, Integer> elementSizer;
+    final @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn;
 
-    private transient @MonotonicNonNull List<T> buffer;
-    private transient long bundleSizeBytes;
-    private transient @Nullable MultiOutputReceiver receiver;
+    // Per-bundle state, allocated once in setup and cleared at the start of 
each bundle.
+    private transient @MonotonicNonNull Map<Object, KeyBuffer<T>> buffers;
+    private transient @MonotonicNonNull Set<Object> liftedKeys;
+    // Reset in startBundle; not transient so SpotBugs doesn't flag them as 
unrestored state.
+    private long bufferedBytes;
+    // Set once the memory cap is exceeded or the lifted key limit is reached 
in this bundle: keys
+    // that are neither buffered nor lifted are no longer tracked and go to 
the small output
+    // immediately.
+    private boolean keysFinalized;
 
     BundleLiftDoFn(
         TupleTag<T> smallBatchTag,
         TupleTag<T> largeBatchTag,
-        int threshold,
-        SerializableFunction<T, Integer> elementSizer) {
+        long threshold,
+        long maxBufferedBytes,
+        int maxLiftedKeys,
+        SerializableFunction<T, Integer> elementSizer,
+        @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn) {
       this.smallBatchTag = smallBatchTag;
       this.largeBatchTag = largeBatchTag;
       this.threshold = threshold;
+      this.maxBufferedBytes = maxBufferedBytes;
+      this.maxLiftedKeys = maxLiftedKeys;
       this.elementSizer = elementSizer;
+      this.keyFn = keyFn;
+    }
+
+    @Setup
+    public void setup() {
+      buffers = new LinkedHashMap<>();
+      liftedKeys = new HashSet<>();
     }
 
     @StartBundle
     public void startBundle() {
-      buffer = new ArrayList<>();
-      receiver = null;
-      bundleSizeBytes = 0L;
+      checkStateNotNull(buffers, "Buffers should be set by setup.").clear();
+      checkStateNotNull(liftedKeys, "Lifted keys should be set by 
setup.").clear();
+      bufferedBytes = 0L;
+      keysFinalized = false;
     }
 
     @ProcessElement
-    public void processElement(@Element T element, MultiOutputReceiver mor) {
-      if (receiver == null) {
-        receiver = mor;
+    public void processElement(
+        @Element T element,
+        @Timestamp Instant timestamp,
+        BoundedWindow window,
+        PaneInfo pane,
+        MultiOutputReceiver receiver) {
+      Map<Object, KeyBuffer<T>> buffers =
+          checkStateNotNull(this.buffers, "Buffers should be set by setup.");
+      Set<Object> liftedKeys =
+          checkStateNotNull(this.liftedKeys, "Lifted keys should be set by 
setup.");
+
+      Object key;
+      if (keyFn == null) {
+        key = UNKEYED;
+      } else {
+        @Nullable Object userKey = keyFn.apply(element);
+        key = new WindowedKey(window, pane, userKey == null ? UNKEYED : 
userKey);
+      }
+
+      if (liftedKeys.contains(key)) {
+        // This key already reached the threshold in this bundle; stream it 
through.
+        receiver.get(largeBatchTag).output(element);

Review Comment:
   **🟡 Medium**: Because `@ProcessElement` declares a `BoundedWindow window` 
parameter (`observesWindow == true`) and both `largeBatchTag` and 
`smallBatchTag` are non-main output tags, calling 
`receiver.get(tag).output(element)` behaves unexpectedly in `FnApiDoFnRunner` 
when an input element belongs to multiple windows (e.g., `SlidingWindows`).
   
   In `FnApiDoFnRunner.ProcessBundleContextBase`, 
`MultiOutputReceiver.get(tag)` for non-main tags constructs its `OutputBuilder` 
via `WindowedValues.builder(currentElement)`, which retains **all** windows of 
the unexploded `currentElement` rather than just `currentWindow`. As a result, 
`.output(element)` emits the element into all of its windows on each per-window 
invocation (and can leak an element into `largeBatchTag` for a window that was 
not lifted). Using `outputWindowedValue` with 
`Collections.singletonList(window)` (matching `emit()` below, and likewise on 
line 195 for `smallBatchTag`) ensures only the current window is emitted.
   
   ```suggestion
           receiver.get(largeBatchTag).outputWindowedValue(element, timestamp, 
Collections.singletonList(window), pane);
   ```



##########
sdks/java/core/src/main/java/org/apache/beam/sdk/util/BundleLifter.java:
##########
@@ -57,89 +90,311 @@ public class BundleLifter<T> extends 
PTransform<PCollection<T>, PCollectionTuple
 
   final TupleTag<T> smallBatchTag;
   final TupleTag<T> largeBatchTag;
-  final int threshold;
+  final long threshold;
+  final long maxBufferedBytes;
+  final int maxLiftedKeys;
   final SerializableFunction<T, Integer> elementSizer;
+  final @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn;
+
+  /** The default memory cap: twice the threshold. */
+  static long defaultMaxBufferedBytes(long threshold) {
+    return threshold > Long.MAX_VALUE / 2 ? Long.MAX_VALUE : 2 * threshold;
+  }
 
   /**
-   * A DoFn that buffers elements within a bundle and outputs them to 
different tags in
-   * finish_bundle based on the total bundle size.
+   * A DoFn that buffers elements per key within a bundle and outputs them to 
the large tag once a
+   * key reaches the threshold, or to the small tag otherwise.
    *
    * @param <T> The type of elements being processed.
    */
   static class BundleLiftDoFn<T> extends DoFn<T, Void> {
     private static final Logger LOG = 
LoggerFactory.getLogger(BundleLiftDoFn.class);
 
+    /** The key shared by all elements without a key, or whose key function 
returns null. */
+    private static final Object UNKEYED = new Object();
+
     final TupleTag<T> smallBatchTag;
     final TupleTag<T> largeBatchTag;
-    final int threshold;
+    final long threshold;
+    final long maxBufferedBytes;
+    final int maxLiftedKeys;
     final SerializableFunction<T, Integer> elementSizer;
+    final @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn;
 
-    private transient @MonotonicNonNull List<T> buffer;
-    private transient long bundleSizeBytes;
-    private transient @Nullable MultiOutputReceiver receiver;
+    // Per-bundle state, allocated once in setup and cleared at the start of 
each bundle.
+    private transient @MonotonicNonNull Map<Object, KeyBuffer<T>> buffers;
+    private transient @MonotonicNonNull Set<Object> liftedKeys;
+    // Reset in startBundle; not transient so SpotBugs doesn't flag them as 
unrestored state.
+    private long bufferedBytes;
+    // Set once the memory cap is exceeded or the lifted key limit is reached 
in this bundle: keys
+    // that are neither buffered nor lifted are no longer tracked and go to 
the small output
+    // immediately.
+    private boolean keysFinalized;
 
     BundleLiftDoFn(
         TupleTag<T> smallBatchTag,
         TupleTag<T> largeBatchTag,
-        int threshold,
-        SerializableFunction<T, Integer> elementSizer) {
+        long threshold,
+        long maxBufferedBytes,
+        int maxLiftedKeys,
+        SerializableFunction<T, Integer> elementSizer,
+        @Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn) {
       this.smallBatchTag = smallBatchTag;
       this.largeBatchTag = largeBatchTag;
       this.threshold = threshold;
+      this.maxBufferedBytes = maxBufferedBytes;
+      this.maxLiftedKeys = maxLiftedKeys;
       this.elementSizer = elementSizer;
+      this.keyFn = keyFn;
+    }
+
+    @Setup
+    public void setup() {
+      buffers = new LinkedHashMap<>();
+      liftedKeys = new HashSet<>();
     }
 
     @StartBundle
     public void startBundle() {
-      buffer = new ArrayList<>();
-      receiver = null;
-      bundleSizeBytes = 0L;
+      checkStateNotNull(buffers, "Buffers should be set by setup.").clear();
+      checkStateNotNull(liftedKeys, "Lifted keys should be set by 
setup.").clear();
+      bufferedBytes = 0L;
+      keysFinalized = false;
     }
 
     @ProcessElement
-    public void processElement(@Element T element, MultiOutputReceiver mor) {
-      if (receiver == null) {
-        receiver = mor;
+    public void processElement(
+        @Element T element,
+        @Timestamp Instant timestamp,
+        BoundedWindow window,
+        PaneInfo pane,
+        MultiOutputReceiver receiver) {
+      Map<Object, KeyBuffer<T>> buffers =
+          checkStateNotNull(this.buffers, "Buffers should be set by setup.");
+      Set<Object> liftedKeys =
+          checkStateNotNull(this.liftedKeys, "Lifted keys should be set by 
setup.");
+
+      Object key;
+      if (keyFn == null) {
+        key = UNKEYED;
+      } else {
+        @Nullable Object userKey = keyFn.apply(element);
+        key = new WindowedKey(window, pane, userKey == null ? UNKEYED : 
userKey);
+      }
+
+      if (liftedKeys.contains(key)) {
+        // This key already reached the threshold in this bundle; stream it 
through.
+        receiver.get(largeBatchTag).output(element);
+        return;
+      }
+
+      KeyBuffer<T> buffer = buffers.get(key);
+      if (buffer == null) {
+        if (keysFinalized) {
+          // The memory cap was exceeded earlier in this bundle; don't track 
new keys.
+          receiver.get(smallBatchTag).output(element);
+          return;
+        }
+        buffer = new KeyBuffer<>();
+        buffers.put(key, buffer);
+      }
+      long elementBytes = elementSizer.apply(element);
+      buffer.add(new BufferedElement<>(element, timestamp, window, pane), 
elementBytes);
+      bufferedBytes += elementBytes;
+
+      if (buffer.sizeBytes >= threshold) {
+        buffers.remove(key);
+        bufferedBytes -= buffer.sizeBytes;
+        liftedKeys.add(key);
+        LOG.debug(
+            "Key reached {} estimated bytes; emitting {} buffered elements to 
tag: '{}'",
+            buffer.sizeBytes,
+            buffer.elements.size(),
+            largeBatchTag.getId());
+        emit(buffer, receiver.get(largeBatchTag));
+        buffer.elements.clear();
+        if (liftedKeys.size() >= maxLiftedKeys) {
+          // No other key can be lifted in this bundle; release the remaining 
buffers.
+          keysFinalized = true;
+          OutputReceiver<T> small = receiver.get(smallBatchTag);
+          Iterator<KeyBuffer<T>> it = buffers.values().iterator();
+          while (it.hasNext()) {
+            KeyBuffer<T> other = it.next();
+            it.remove();
+            emit(other, small);
+            other.elements.clear();
+          }
+          bufferedBytes = 0L;
+        }
+        return;
+      }
+
+      // Anything that isn't in lifted keys or buffers is sent to small keys 
immediately.
+      if (bufferedBytes > maxBufferedBytes) {
+        keysFinalized = true;
+        evictSmallestKeys(buffers, receiver.get(smallBatchTag));
       }
-      checkArgumentNotNull(buffer, "Buffer should be set by startBundle.");
-      buffer.add(element);
-      bundleSizeBytes += elementSizer.apply(element);
     }
 
     @FinishBundle
-    public void finishBundle() {
-      checkArgumentNotNull(buffer, "Buffer should be set by startBundle.");
-      if (buffer.isEmpty()) {
-        return;
+    public void finishBundle(FinishBundleContext context) {
+      Map<Object, KeyBuffer<T>> buffers =
+          checkStateNotNull(this.buffers, "Buffers should be set by setup.");
+      Iterator<KeyBuffer<T>> it = buffers.values().iterator();
+      while (it.hasNext()) {
+        KeyBuffer<T> buffer = it.next();
+        it.remove();
+        LOG.debug(
+            "Emitting {} elements of {} estimated bytes to tag: '{}'",
+            buffer.elements.size(),
+            buffer.sizeBytes,
+            smallBatchTag.getId());
+        // FinishBundleContext.output has no PaneInfo overload, and 
MultiOutputReceiver from
+        // @ProcessElement cannot be retained across bundle lifecycle methods 
(FnApiDoFnRunner
+        // clears currentElement after each processElement).
+        for (BufferedElement<T> e : buffer.elements) {
+          context.output(smallBatchTag, e.value, e.timestamp, e.window);
+        }
+        buffer.elements.clear();
       }
+      checkStateNotNull(this.liftedKeys).clear();
+      bufferedBytes = 0L;
+      keysFinalized = false;
+    }
 
-      // Select the target tag based on the bundle size
-      TupleTag<T> targetTag;
-      targetTag = (bundleSizeBytes < threshold) ? smallBatchTag : 
largeBatchTag;
-      LOG.debug(
-          "Emitting {} elements of {} estimated bytes to tag: '{}'",
-          buffer.size(),
-          bundleSizeBytes,
-          targetTag.getId());
+    /**
+     * Buffered elements are re-emitted from {@link ProcessElement} with their 
own timestamps, which
+     * may be earlier than the current element's. This is safe because they 
belong to the same
+     * bundle, so the input watermark is still held at or before them.
+     */
+    @Override
+    public Duration getAllowedTimestampSkew() {
+      return Duration.millis(Long.MAX_VALUE);
+    }
 
-      checkArgumentNotNull(receiver, "Receiver should be set by startBundle.");
-      OutputReceiver<T> taggedOutput = receiver.get(targetTag);
+    /**
+     * Emits the smallest keys to the small output until at most half of 
{@code maxBufferedBytes}
+     * remains buffered, so each call frees a large chunk and the sort's cost 
stays amortized.
+     */
+    private void evictSmallestKeys(Map<Object, KeyBuffer<T>> buffers, 
OutputReceiver<T> small) {
+      long target = maxBufferedBytes / 2;
+      List<Map.Entry<Object, KeyBuffer<T>>> bySize = new 
ArrayList<>(buffers.entrySet());
+      bySize.sort(Comparator.comparingLong(entry -> 
entry.getValue().sizeBytes));
+      for (Map.Entry<Object, KeyBuffer<T>> entry : bySize) {
+        if (bufferedBytes <= target) {

Review Comment:
   **🟠 High**: When `maxBufferedBytes` is configured to a value in `[threshold, 
2 * threshold - 1]` (which is explicitly allowed by the constructor check 
`maxBufferedBytes >= threshold`), `target = maxBufferedBytes / 2` is less than 
`threshold`.
   
   If the largest buffered key has `sizeBytes` in `(target, threshold)` when 
another key pushes `bufferedBytes` over `maxBufferedBytes`, `evictSmallestKeys` 
will evict the smaller keys and then also evict the last remaining key because 
`bufferedBytes <= target` is still `false`. This leaves `buffers` completely 
empty with `keysFinalized = true`, so all subsequent elements in the bundle 
(including for that largest key) are sent directly to `smallBatchTag` and no 
key can ever reach `threshold`.
   
   Since any single buffered key is guaranteed to have `sizeBytes < threshold 
<= maxBufferedBytes`, stopping once `buffers.size() <= 1` ensures the memory 
bound is respected while keeping the largest key eligible to reach `threshold`.
   
   ```suggestion
           if (bufferedBytes <= target || buffers.size() <= 1) {
   ```



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