cshuo commented on code in PR #19728:
URL: https://github.com/apache/hudi/pull/19728#discussion_r3868222405


##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/StreamWriteFunction.java:
##########
@@ -379,12 +386,9 @@ private void reclaimMemoryAfterFailedWrite(String 
bucketID) {
     // A creation failure leaves no bucket in the map, while a write failure 
leaves the
     // diverged bucket in the map so that its committed records can be flushed 
and disposed.
     RowDataBucket failedBucket = this.buckets.get(bucketID);
-    RowDataBucket bucketToFlush = this.buckets.values().stream()
-        .filter(bucket -> !bucketID.equals(bucket.getBucketId()) && 
!bucket.isEmpty())
-        .max(Comparator.comparingLong(RowDataBucket::getBufferSize))
-        .orElse(null);
 
     if (failedBucket == null) {
+      RowDataBucket bucketToFlush = 
findLargestNonEmptyBucketExcluding(bucketID);

Review Comment:
   Since this branch performs the same largest-non-empty-bucket selection and 
flush as `preemptMemory(bucketID)`, we can reuse it here:
   ```
   if (!preemptMemory(bucketID)) {
       throw new HoodieException(
           "Not enough memory pages to create a RowData buffer and no non-empty 
bucket can be flushed");
   }
   return;
   ```



##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/buffer/PreemptiveMemorySegmentPool.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.hudi.sink.buffer;
+
+import org.apache.hudi.common.util.ValidationUtils;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+
+import javax.annotation.Nullable;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * A {@link MemorySegmentPool} wrapper that can reclaim pages from an inactive 
owner when the
+ * delegate pool is exhausted.
+ *
+ * <p>The owner represents the bucket whose buffer is currently requesting 
pages. The reclaimer
+ * must never reclaim that owner because the request may occur in the middle 
of serializing a row.
+ * If no other owner can release pages, this pool returns {@code null} and 
lets the caller handle
+ * the allocation failure.
+ */
+public class PreemptiveMemorySegmentPool implements MemorySegmentPool, 
Closeable {
+
+  /** Callback that reclaims memory from an owner other than the excluded 
in-flight owner. */
+  @FunctionalInterface
+  public interface MemoryReclaimer {
+    /**
+     * Reclaims memory from an inactive owner.
+     *
+     * @param excludedOwnerId the owner currently requesting a page
+     * @return {@code true} if memory was reclaimed and allocation should be 
retried
+     */
+    boolean reclaim(String excludedOwnerId);
+  }
+
+  private final MemorySegmentPool delegate;
+  private final MemoryReclaimer memoryReclaimer;
+
+  @Nullable
+  private String currentOwnerId;
+  private boolean preempting;
+
+  public PreemptiveMemorySegmentPool(
+      MemorySegmentPool delegate,
+      MemoryReclaimer memoryReclaimer) {
+    ValidationUtils.checkArgument(delegate != null, "Delegate memory segment 
pool must not be null");
+    ValidationUtils.checkArgument(memoryReclaimer != null, "Memory reclaimer 
must not be null");
+    this.delegate = delegate;
+    this.memoryReclaimer = memoryReclaimer;
+  }
+
+  /** Marks the owner whose buffer is currently requesting memory pages. */
+  public void setCurrentOwner(String ownerId) {
+    ValidationUtils.checkArgument(ownerId != null, "Memory segment pool owner 
must not be null");
+    ValidationUtils.checkState(
+        currentOwnerId == null,
+        "A memory segment pool owner is already active: " + currentOwnerId);
+    this.currentOwnerId = ownerId;
+  }
+
+  /** Clears the current owner after its buffer write finishes. */
+  public void clearCurrentOwner() {
+    this.currentOwnerId = null;
+  }
+
+  @Override
+  public int pageSize() {
+    return delegate.pageSize();
+  }
+
+  @Override
+  public void returnAll(List<MemorySegment> memorySegments) {
+    delegate.returnAll(memorySegments);
+  }
+
+  @Override
+  public int freePages() {
+    return delegate.freePages();
+  }
+
+  @Override
+  public MemorySegment nextSegment() {
+    MemorySegment segment = delegate.nextSegment();
+    if (segment != null || currentOwnerId == null || preempting) {

Review Comment:
   Thanks for the clarification. I don't think we need to expand the condition 
here. The existing behavior looks fine; adding some comments to explain should 
be sufficient.



##########
hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/sink/bucket/TestBucketStreamWriteMemoryExhaustion.java:
##########
@@ -84,27 +94,21 @@ void 
testRecoveryPreservesVariableLengthValuesAndReleasesPages() throws Exceptio
     pipeline.openFunction();
     int initialFreePages = pipeline.freePages();
     try {
-      boolean reclaimedOtherBucketBeforeDivergedBucket = false;
+      boolean preemptedInactiveBucket = false;

Review Comment:
   The updated test verifies successful preemption of an inactive bucket, but 
it no longer explicitly verifies the fallback when no eligible victim exists.
   
   Could we retain or add a scenario where only the current bucket holds 
buffered rows, the next record exhausts the remaining pages, and the record 
fits after the diverged bucket is flushed and disposed? This would cover 
`reclaim()` returning `false`, followed by flushing the diverged bucket and 
successfully retrying the record, while also verifying that no records or 
memory pages are lost.



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