Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@
import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.metrics.FlinkStreamWriteMetrics;
import org.apache.hudi.sink.buffer.PreemptiveMemorySegmentPool;
import org.apache.hudi.sink.buffer.RowDataBinaryBuffer;
import org.apache.hudi.sink.buffer.RowDataBucket;
import org.apache.hudi.sink.buffer.StableSortBuffer;
import org.apache.hudi.sink.buffer.SequentialRowDataBuffer;
import org.apache.hudi.sink.buffer.TotalSizeTracer;
import org.apache.hudi.sink.bulk.RowDataKeyGen;
import org.apache.hudi.sink.bulk.RowDataKeyGens;
Expand Down Expand Up @@ -84,7 +85,7 @@
*
* <p><h2>Work Flow</h2>
*
* <p>The function firstly buffers the data (RowData) in a {@link StableSortBuffer}.
* <p>The function firstly buffers the data (RowData) in a paged {@link RowDataBinaryBuffer} per bucket.
* It flushes(write) the records batch when the batch size exceeds the configured size {@link FlinkOptions#WRITE_BATCH_SIZE}
* or the memory of the binary buffer is exhausted, and could not append any more data or a Flink checkpoint starts.
* After a batch has been written successfully, the function notifies its operator coordinator {@link StreamWriteOperatorCoordinator}
Expand Down Expand Up @@ -355,7 +356,7 @@ protected void bufferRecord(HoodieFlinkInternalRow record) throws IOException {
boolean success = doBufferRecord(bucketID, record);
if (!success) {
// 2. reclaim pages. A buffer whose write returned false must never be reused because
// StableSortBuffer may already have changed its variable-length storage state.
// the failed append may have written a partial row.
reclaimMemoryAfterFailedWrite(bucketID);

// 2.1 retry once with a newly-created buffer
Expand Down Expand Up @@ -552,7 +553,7 @@ protected List<WriteStatus> writeRecords(
RowDataBucket rowDataBucket) {
writeMetrics.startFileFlush();

sortBucketIfNeeded(rowDataBucket);
rowDataBucket.sort();
Iterator<BinaryRowData> rowItr =
new MutableIteratorWrapperIterator<>(
rowDataBucket.getDataIterator(), () -> new BinaryRowData(rowType.getFieldCount()));
Expand All @@ -566,9 +567,9 @@ protected List<WriteStatus> writeRecords(
return statuses;
}

private StableSortBuffer createDataBuffer() {
private RowDataBinaryBuffer createDataBuffer() {
if (recordKeyComputer == null) {
return BufferUtils.createStableSortBuffer(rowType, preemptiveMemorySegmentPool);
return new SequentialRowDataBuffer(rowType, preemptiveMemorySegmentPool);
Comment thread
cshuo marked this conversation as resolved.
Resolved
}
try {
return BufferUtils.createStableSortBuffer(
Expand All @@ -584,17 +585,6 @@ private StableSortBuffer createDataBuffer() {
}
}

private void sortBucketIfNeeded(RowDataBucket rowDataBucket) {
if (recordKeyComputer == null) {
return;
}
try {
rowDataBucket.sort();
} catch (IOException e) {
throw new HoodieException("Failed to sort buffered RowData records by record key.", e);
}
}

protected Iterator<HoodieRecord> deduplicateRecordsIfNeeded(Iterator<HoodieRecord> records) {
// Other write paths can call this method without sorting their input first.
return deduplicateRecordsIfNeeded(records, false);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.util.MutableObjectIterator;

import java.io.IOException;

/** Paged row storage owned by one write bucket. */
public interface RowDataBinaryBuffer {
/**
* Appends a row, returning false if the buffer runs out of pages.
* A failed append may leave a partial row. Only previously appended rows may be read.
* Do not write again until the buffer has been fully reset or replaced.
*/
boolean write(RowData row) throws IOException;

boolean isEmpty();

MutableObjectIterator<BinaryRowData> getIterator();

default void sortIfNeeded() {
// Sequential buffers already have the required iteration order.
}

/**
* Discards all rows, including any partial last row, and leaves the buffer ready for a new batch.
* Existing iterators and rows backed by the buffer's pages must no longer be used.
*/
void reset();

/** Returns all pages to the pool. The buffer must not be used afterwards. */
void dispose();
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import org.apache.hudi.table.action.commit.BucketInfo;

import lombok.Getter;
import org.apache.flink.runtime.operators.sort.QuickSort;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.util.MutableObjectIterator;
Expand All @@ -34,7 +33,7 @@
* to minimize GC costs.
*/
public class RowDataBucket {
private final StableSortBuffer dataBuffer;
private final RowDataBinaryBuffer dataBuffer;
@Getter
private final BucketInfo bucketInfo;
private final BufferSizeDetector detector;
Expand All @@ -45,7 +44,7 @@ public class RowDataBucket {

public RowDataBucket(
String bucketId,
StableSortBuffer dataBuffer,
RowDataBinaryBuffer dataBuffer,
BucketInfo bucketInfo,
Double batchSize) {
this.bucketId = bucketId;
Expand All @@ -59,12 +58,10 @@ public MutableObjectIterator<BinaryRowData> getDataIterator() {
}

/**
* Sorts by record key, retaining arrival order for equal keys.
* Prepares the buffer for iteration, sorting by record key for layouts that require it.
*/
public void sort() throws IOException {
if (dataBuffer.size() > 1) {
new QuickSort().sort(dataBuffer);
}
public void sort() {
dataBuffer.sortIfNeeded();
}

public boolean writeRow(RowData rowData) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.sink.exception.MemoryPagesExhaustedException;

import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.RandomAccessInputView;
import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
import org.apache.flink.table.runtime.util.MemorySegmentPool;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.MutableObjectIterator;

import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;

/** Stores rows in arrival order without a per-row offset index. */
public final class SequentialRowDataBuffer implements RowDataBinaryBuffer {
private final ArrayList<MemorySegment> pages = new ArrayList<>();
private final MemorySegmentPool pool;
private final RowDataSerializer serializer;
private final SimpleCollectingOutputView output;
private int numRecords;

public SequentialRowDataBuffer(RowType rowType, MemorySegmentPool pool) {
if (pool.freePages() < 1) {
throw new MemoryPagesExhaustedException("No free page to create a sequential RowData buffer.");
}
this.pool = pool;
this.serializer = new RowDataSerializer(rowType);
this.output = new SimpleCollectingOutputView(pages, pool, pool.pageSize());
}

@Override
public boolean write(RowData row) throws IOException {
try {
serializer.serializeToPages(row, output);
} catch (EOFException e) {
// A partial row can occupy several pages. Only complete rows are visible to readers.
return false;
}
numRecords++;
return true;
}

@Override
public boolean isEmpty() {
return numRecords == 0;
}

@Override
public MutableObjectIterator<BinaryRowData> getIterator() {
return new MutableObjectIterator<BinaryRowData>() {
private final RandomAccessInputView input = new RandomAccessInputView(pages, pool.pageSize());
private int remaining = numRecords;

@Override
public BinaryRowData next(BinaryRowData reuse) throws IOException {
if (remaining == 0) {
return null;
}
remaining--;
return (BinaryRowData) serializer.mapFromPages(reuse, input);
}

@Override
public BinaryRowData next() throws IOException {
return next(new BinaryRowData(serializer.getArity()));
}
};
}

@Override
public void reset() {
returnPages();
numRecords = 0;
output.reset();
}

@Override
public void dispose() {
returnPages();
}

private void returnPages() {
pool.returnAll(pages);
pages.clear();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
import org.apache.flink.runtime.operators.sort.QuickSort;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.runtime.generated.NormalizedKeyComputer;
Expand All @@ -42,7 +43,7 @@
* <p>Provides stable sorting by comparing record offsets when keys are equal,
* preserving the original insertion order of records with equal keys.
*/
public final class StableSortBuffer extends BinaryIndexedSortable {
public final class StableSortBuffer extends BinaryIndexedSortable implements RowDataBinaryBuffer {

private static final int MIN_REQUIRED_BUFFERS = 3;

Expand Down Expand Up @@ -92,6 +93,13 @@ private StableSortBuffer(
this.totalNumBuffers = totalNumBuffers;
}

@Override
public void sortIfNeeded() {
if (size() > 1) {
new QuickSort().sort(this);
}
}

// Preserve arrival order for equal keys using the existing record offsets.
@Override
public int compare(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, int segmentOffsetJ) {
Expand All @@ -106,9 +114,7 @@ public int compare(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, i
sortIndex.get(segmentNumberJ).getLong(segmentOffsetJ));
}

/**
* Resets the sort buffer back to the state where it is empty. All contained data is discarded.
*/
@Override
public void reset() {
// reset all offsets
this.numRecords = 0;
Expand All @@ -131,10 +137,12 @@ public void returnToSegmentPool() {
this.recordBufferSegments.clear();
}

@Override
public boolean isEmpty() {
return this.numRecords == 0;
}

@Override
public void dispose() {
returnToSegmentPool();
}
Expand All @@ -156,6 +164,7 @@ public long getOccupancy() {
* @throws IOException Thrown, if an error occurred while serializing the record into the
* buffers.
*/
@Override
public boolean write(RowData record) throws IOException {
// check whether we need a new memory segment for the sort index
if (!checkNextIndexOffset()) {
Expand Down Expand Up @@ -191,6 +200,7 @@ private BinaryRowData getRecordFromBuffer(BinaryRowData reuse, long pointer)
*
* @return An iterator returning the records in their logical order.
*/
@Override
public MutableObjectIterator<BinaryRowData> getIterator() {
return new MutableObjectIterator<BinaryRowData>() {
private final int size = size();
Expand Down
Loading