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 @@ -20,6 +20,7 @@

import org.apache.hudi.client.WriteStatus;
import org.apache.hudi.common.model.HoodieDeltaWriteStat;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.util.ValidationUtils;
import org.apache.hudi.util.WriteStatusMerger;

Expand All @@ -28,9 +29,13 @@
import lombok.Setter;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

Expand All @@ -46,6 +51,8 @@ public class WriteMetadataEvent implements OperatorEvent {
public static final String BOOTSTRAP_INSTANT = "";

private List<WriteStatus> writeStatuses;
// Coordinator-only index. Checkpoints continue to store the original list representation.
private transient Map<String, WriteStatus> writeStatusesByFile;
private int taskID;
private long checkpointId;
private String instantTime;
Expand Down Expand Up @@ -118,7 +125,13 @@ public void mergeWith(WriteMetadataEvent other) {
this.instantTime = other.instantTime;
// true if one of the event lastBatch is true
this.lastBatch |= other.lastBatch;
this.writeStatuses = mergeWriteStatuses(this.writeStatuses, other.writeStatuses);
List<WriteStatus> incoming = other.getWriteStatuses();
if (writeStatusesByFile == null) {
writeStatusesByFile = new HashMap<>();
writeStatuses.forEach(this::accumulateWriteStatus);
writeStatuses = null;
}
incoming.forEach(this::accumulateWriteStatus);
}

/**
Expand All @@ -132,10 +145,32 @@ public WriteMetadataEvent mergeWithRescale(WriteMetadataEvent other) {
this.instantTime = other.instantTime;
// true if one of the event lastBatch is true
this.lastBatch |= other.lastBatch;
this.writeStatuses = mergeWriteStatuses(this.writeStatuses, other.writeStatuses);
this.writeStatuses = mergeWriteStatuses(getWriteStatuses(), other.getWriteStatuses());
return this;
}

public List<WriteStatus> getWriteStatuses() {
if (writeStatusesByFile != null) {
writeStatuses = new ArrayList<>(writeStatusesByFile.values());
writeStatusesByFile = null;
}
return writeStatuses;
}

public void setWriteStatuses(List<WriteStatus> writeStatuses) {
this.writeStatuses = writeStatuses;
this.writeStatusesByFile = null;
}

private void writeObject(ObjectOutputStream out) throws IOException {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This writeObject changes the serializer for the writer’s write-metadata-state. I compared the base and PR serializer snapshots using TypeInformation.of(WriteMetadataEvent.class), the same call as AbstractStreamWriteFunction.initializeState. On Flink 2.0.0, 2.1.1, and 2.2.1, the base used PojoSerializer, the PR used KryoSerializer, and Flink reported INCOMPATIBLE. An existing job can therefore fail to restore after upgrading. The SerializedValue test exercises event transport. Could we keep the existing event serialization and cover the writer-state snapshot in the upgrade test?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching the distinction between event transport and writer state. In 1d28aef I removed the custom serialization and persistent index and kept the optimization inside the shared merge helper. I reproduced the old PR head’s incompatibility with base-written writer state on Flink 2.0.0, 2.1.1, and 2.2.1; the new head reports compatible-as-is and reads the original bytes on all three. The writer-state regression fails on the old head and passes on the new head on Flink 2.2.1. I removed the closing keyword so #20991 can remain open for the scaling work.

getWriteStatuses();
out.defaultWriteObject();
}

private void accumulateWriteStatus(WriteStatus status) {
writeStatusesByFile.merge(writeStatusKey(status), status, WriteStatusMerger::merge);
}

/**
* Returns whether the event is ready to commit.
*/
Expand All @@ -146,7 +181,7 @@ public boolean isReady(String currentInstant) {
@Override
public String toString() {
return "WriteMetadataEvent{"
+ "writeStatusesSize=" + writeStatuses.size()
+ "writeStatusesSize=" + (writeStatusesByFile == null ? writeStatuses.size() : writeStatusesByFile.size())
+ ", taskID=" + taskID
+ ", checkpointId=" + checkpointId
+ ", instantTime='" + instantTime + '\''
Expand Down Expand Up @@ -186,18 +221,17 @@ private static List<WriteStatus> mergeWriteStatuses(List<WriteStatus> curStatuse
merged.addAll(newStatuses);
return merged
.stream()
.collect(Collectors.groupingBy(writeStatus -> {
if (writeStatus.getStat() instanceof HoodieDeltaWriteStat) {
return writeStatus.getStat().getPartitionPath() + writeStatus.getStat().getPath();
} else {
return writeStatus.getStat().getPartitionPath() + writeStatus.getStat().getFileId();
}
}))
.collect(Collectors.groupingBy(WriteMetadataEvent::writeStatusKey))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we keep this optimization inside mergeWriteStatuses and use it from both merge paths? The full replacement for the method body would be

Map<String, WriteStatus> byFile = Stream.concat(curStatuses.stream(), newStatuses.stream())
    .collect(Collectors.toMap(WriteMetadataEvent::writeStatusKey, Function.identity(), WriteStatusMerger::merge));
return new ArrayList<>(byFile.values());

The sequential stream visits existing statuses first, so the newer status stays on the right. This removes the per-file lists and lets us publish the result after the whole flush merges successfully. In a local 256-flush, distinct-file fixture, merge allocations fell from 12.8 MB to 3.9 MB. The persistent index saved about 4.6 ms over the base across that entire fixture. I’d keep the quadratic-scaling issue open and defer the index until a representative job shows coordinator queueing or checkpoint latency worth addressing.

.values().stream()
.map(duplicates -> duplicates.stream().reduce(WriteStatusMerger::merge).get())
.collect(Collectors.toList());
}

private static String writeStatusKey(WriteStatus status) {
HoodieWriteStat stat = status.getStat();
return stat.getPartitionPath() + (stat instanceof HoodieDeltaWriteStat ? stat.getPath() : stat.getFileId());
}

// -------------------------------------------------------------------------
// Builder
// -------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,11 @@ public List<String> getPendingInstantsBefore(long checkpointId) {
public Map<Long, Pair<String, EventBuffer>> getAllCompletedEvents() {
return this.eventBuffers.entrySet().stream()
.filter(entry -> entry.getValue().getRight().allEventsReceived())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
Pair<String, EventBuffer> pair = entry.getValue();
pair.getRight().materializeWriteStatuses();
return pair;
}));
}

/**
Expand Down Expand Up @@ -188,6 +192,12 @@ public void addEvent(WriteMetadataEvent event) {
}
}

private void materializeWriteStatuses() {
// Kryo field serialization must only see the existing event/list representation.
Stream.concat(Arrays.stream(dataWriteEventBuffer), Arrays.stream(indexWriteEventBuffer))
.forEach(WriteMetadataEvent::getWriteStatuses);
}

public void addBootstrapEvent(WriteMetadataEvent event) {
WriteMetadataEvent[] eventBuffer = event.isMetadataTable() ? indexWriteEventBuffer : dataWriteEventBuffer;
WriteMetadataEvent existing = eventBuffer[event.getTaskID()];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,23 @@
package org.apache.hudi.sink.event;

import org.apache.hudi.client.WriteStatus;
import org.apache.hudi.common.model.HoodieDeltaWriteStat;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.util.SerializationUtils;
import org.apache.hudi.configuration.FlinkOptions;
import org.apache.hudi.sink.utils.EventBuffers;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.SerializedValue;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

Expand All @@ -52,6 +60,128 @@ void testMergeWithRescaleMergesEventsAcrossTasks() {
.collect(Collectors.toSet()));
}

@Test
void testSmallFlushesDoNotRevisitUnrelatedStatuses() {
Configuration conf = new Configuration();
EventBuffers buffers = EventBuffers.getInstance(conf, 1);
buffers.initNewEventBuffer(1L, "001");
int[] statReads = {0};
int flushes = 256;
for (int i = 0; i < flushes; i++) {
WriteStatus status = new WriteStatus() {
@Override
public HoodieWriteStat getStat() {
statReads[0]++;
return super.getStat();
}
};
status.setStat(newEvent(0, "001", "part", false, "file-" + i).getWriteStatuses().get(0).getStat());
buffers.addEventToBuffer(event("001", false, false, status));
}
assertEquals(flushes, buffers.getEventBuffer(1L).collectDataWriteStatuses().size());
assertTrue(statReads[0] <= 4 * flushes, "stat reads: " + statReads[0]);
}

@Test
void testCompletedCheckpointPreservesBothStatusBuffers() throws Exception {
Configuration conf = new Configuration();
conf.set(FlinkOptions.METADATA_ENABLED, true);
conf.set(FlinkOptions.INDEX_TYPE, "RECORD_LEVEL_INDEX");
conf.set(FlinkOptions.OPERATION, "upsert");
conf.set(FlinkOptions.INDEX_WRITE_TASKS, 1);
EventBuffers buffers = EventBuffers.getInstance(conf, 1);
buffers.initNewEventBuffer(1L, "001");

WriteStatus first = newEvent(0, "001", "part", false, "file").getWriteStatuses().get(0);
first.getStat().setPath("part/first");
first.setTotalRecords(2);
first.setTotalErrorRecords(1);
WriteStatus second = newEvent(0, "001", "part", false, "file").getWriteStatuses().get(0);
second.getStat().setPath("part/second");
second.setTotalRecords(3);
buffers.addEventToBuffer(event("001", false, false, first));
buffers.addEventToBuffer(event("001", true, false, second));
assertFalse(buffers.getEventBuffer(1L).allEventsReceived());

WriteStatus delta = new WriteStatus();
HoodieDeltaWriteStat stat = new HoodieDeltaWriteStat();
stat.setPartitionPath("metadata");
stat.setFileId("index-file");
stat.setPath("metadata/log-1");
stat.setLogFiles(Collections.singletonList("log-1"));
delta.setStat(stat);
delta.setTotalRecords(1);
WriteStatus delta2 = new WriteStatus();
HoodieDeltaWriteStat stat2 = new HoodieDeltaWriteStat();
stat2.setPartitionPath("metadata");
stat2.setFileId("index-file");
stat2.setPath("metadata/log-2");
stat2.setLogFiles(Collections.singletonList("log-2"));
delta2.setStat(stat2);
WriteStatus delta3 = new WriteStatus();
HoodieDeltaWriteStat stat3 = new HoodieDeltaWriteStat();
stat3.setPartitionPath("metadata");
stat3.setFileId("index-file");
stat3.setPath("metadata/log-1");
stat3.setLogVersion(2);
stat3.setLogFiles(Collections.singletonList("log-1"));
delta3.setStat(stat3);
delta3.setTotalRecords(2);
buffers.addEventToBuffer(event("001", false, true, delta));
buffers.addEventToBuffer(event("001", false, true, delta2));
buffers.addEventToBuffer(event("001", true, true, delta3));

byte[] checkpoint = SerializationUtils.serialize(buffers.getAllCompletedEvents());
EventBuffers restored = EventBuffers.getInstance(conf, 1);
restored.addEventsToBuffer(SerializationUtils.deserialize(checkpoint));
EventBuffers.EventBuffer recovered = restored.getEventBuffer(1L);
assertTrue(recovered.allEventsReceived());
List<WriteStatus> data = recovered.collectDataWriteStatuses();
assertEquals(1, data.size());
assertEquals(5, data.get(0).getTotalRecords());
assertEquals(1, data.get(0).getTotalErrorRecords());
assertEquals("part/second", data.get(0).getStat().getPath());
List<WriteStatus> index = recovered.collectIndexWriteStatuses();
assertEquals(2, index.size());
assertEquals(Set.of("metadata/log-1", "metadata/log-2"), index.stream()
.map(status -> status.getStat().getPath())
.collect(Collectors.toSet()));
WriteStatus mergedLog = index.stream().filter(status -> "metadata/log-1".equals(status.getStat().getPath())).findFirst().get();
assertEquals(3, mergedLog.getTotalRecords());
assertEquals(2, ((HoodieDeltaWriteStat) mergedLog.getStat()).getLogVersion());

WriteStatus next = newEvent(0, "001", "part", false, "file").getWriteStatuses().get(0);
next.setTotalRecords(7);
restored.addEventToBuffer(event("001", false, false, next));
assertEquals(12, recovered.collectDataWriteStatuses().get(0).getTotalRecords());
assertTrue(recovered.allEventsReceived());
}

@Test
void testFlinkSerializationPreservesMergedStatuses() throws Exception {
WriteMetadataEvent first = newEvent(0, "001", "part", false, "file-1");
first.mergeWith(newEvent(0, "001", "part", true, "file-2"));

WriteMetadataEvent restored =
new SerializedValue<>(first).deserializeValue(getClass().getClassLoader());

assertTrue(restored.isLastBatch());
assertEquals(Set.of("file-1", "file-2"), restored.getWriteStatuses().stream()
.map(status -> status.getStat().getFileId())
.collect(Collectors.toSet()));
}

private static WriteMetadataEvent event(String instant, boolean lastBatch, boolean metadata, WriteStatus status) {
return WriteMetadataEvent.builder()
.taskID(0)
.checkpointId(1L)
.instantTime(instant)
.writeStatus(Collections.singletonList(status))
.lastBatch(lastBatch)
.metadataTable(metadata)
.build();
}

private static WriteMetadataEvent newEvent(
int taskId,
String instant,
Expand Down