Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -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 @@ -585,9 +586,6 @@ private StableSortBuffer createDataBuffer() {
}

private void sortBucketIfNeeded(RowDataBucket rowDataBucket) {
if (recordKeyComputer == null) {
return;
}
try {
rowDataBucket.sort();
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* 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, so the caller must not write to this buffer again.
* Previously appended rows remain available for sorting and iteration. Dispose of this buffer
* and retry the failed row in a fresh buffer.
*/
boolean write(RowData row) throws IOException;

boolean isEmpty();

MutableObjectIterator<BinaryRowData> getIterator();

default void sortIfNeeded() throws IOException {
Comment thread
cshuo marked this conversation as resolved.
Resolved
// Sequential buffers already have the required iteration order.
}

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);
}
dataBuffer.sortIfNeeded();
}

public boolean writeRow(RowData rowData) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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 dispose() {
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() throws IOException {
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 Down Expand Up @@ -131,10 +139,12 @@ public void returnToSegmentPool() {
this.recordBufferSegments.clear();
}

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

@Override
public void dispose() {
returnToSegmentPool();
}
Expand All @@ -156,6 +166,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 +202,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
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@
import org.apache.hudi.configuration.FlinkOptions;
import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.metadata.HoodieMetadataPayload;
import org.apache.hudi.sink.buffer.StableSortBuffer;
import org.apache.hudi.sink.buffer.SequentialRowDataBuffer;
import org.apache.hudi.sink.common.AbstractStreamWriteFunction;
import org.apache.hudi.sink.event.WriteMetadataEvent;
import org.apache.hudi.sink.utils.BufferUtils;
import org.apache.hudi.table.HoodieFlinkTable;
import org.apache.hudi.util.MutableIteratorWrapperIterator;

Expand Down Expand Up @@ -78,7 +77,7 @@ public class IndexWriteFunction extends AbstractStreamWriteFunction<RowData> {

private transient MemorySegmentPool memorySegmentPool;

private transient StableSortBuffer indexDataBuffer;
private transient SequentialRowDataBuffer indexDataBuffer;

/**
* Hoodie Flink table.
Expand All @@ -98,11 +97,15 @@ public void open(Configuration parameters) throws Exception {
this.memorySegmentPool = this.memorySegmentPoolFactory.createMemorySegmentPool(
config,
config.get(FlinkOptions.INDEX_RLI_WRITE_BUFFER_SIZE) * 1024 * 1024);
this.indexDataBuffer = BufferUtils.createStableSortBuffer(IndexRowUtils.INDEX_ROW_TYPE, memorySegmentPool);
this.indexDataBuffer = createIndexBuffer();
this.dedupKeyExtractor = this.writeClient.getConfig().isRecordLevelIndexEnabled()
? IndexWriteFunction::getPartitionedDedupKey : IndexRowUtils::getRecordKey;
}

private SequentialRowDataBuffer createIndexBuffer() {
return new SequentialRowDataBuffer(IndexRowUtils.INDEX_ROW_TYPE, memorySegmentPool);
}

@Override
protected void sendWriteMetadataEvent(WriteMetadataEvent metadataEvent) {
this.correspondent.sendWriteMetadataEvent(metadataEvent);
Expand All @@ -129,7 +132,7 @@ public void snapshotState() {
private void flushBuffer(boolean lastBatch, boolean endInput) {
// in case of there is no index record during the checkpoint interval, request instant from coordinator.
this.currentInstant = instantToWrite(true);
Pair<List<HoodieRecord>, Set<String>> indexRecordsAndPartitions = prepareIndexRecordsAndPartitions(this.indexDataBuffer);
Pair<List<HoodieRecord>, Set<String>> indexRecordsAndPartitions = prepareIndexRecordsAndPartitions();
HoodieData<HoodieRecord> indexRecords = HoodieListData.eager(indexRecordsAndPartitions.getLeft());
List<WriteStatus> writeStatus = this.writeClient.streamWriteToMetadataPartitions(
flinkTable, indexRecords, indexRecordsAndPartitions.getRight(), this.currentInstant).collectAsList();
Expand All @@ -147,15 +150,16 @@ private void flushBuffer(boolean lastBatch, boolean endInput) {
this.correspondent.sendWriteMetadataEvent(event);
this.writeStatuses.addAll(writeStatus);

// reset buffer for reusing
this.indexDataBuffer.reset();
// A failed append may have left a partial index row; never append to the old buffer again.
this.indexDataBuffer.dispose();
this.indexDataBuffer = createIndexBuffer();
Comment thread
cshuo marked this conversation as resolved.
Resolved
// close the metadata writer if the current instant writing is finished.
if (lastBatch) {
this.writeClient.cleanResources(this.currentInstant);
}
}

private Pair<List<HoodieRecord>, Set<String>> prepareIndexRecordsAndPartitions(StableSortBuffer indexDataBuffer) {
private Pair<List<HoodieRecord>, Set<String>> prepareIndexRecordsAndPartitions() {
BinaryRowData reusedRow = new BinaryRowData(IndexRowUtils.INDEX_ROW_TYPE.getFieldCount());
Iterator<BinaryRowData> rowItr = new MutableIteratorWrapperIterator<>(indexDataBuffer.getIterator(), () -> reusedRow);
Set<String> dataPartitions = new HashSet<>();
Expand Down Expand Up @@ -193,7 +197,7 @@ public void handleOperatorEvent(OperatorEvent event) {
@VisibleForTesting
@SuppressWarnings("rawtypes")
public List<HoodieRecord> getDataBuffer() {
return prepareIndexRecordsAndPartitions(this.indexDataBuffer).getLeft();
return prepareIndexRecordsAndPartitions().getLeft();
}

@Override
Expand Down
Loading