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 @@ -137,6 +137,16 @@ public KeyValue getResult() {
return mergeFunction.getResult();
}

@Override
public void validateRetract(KeyValue kv) {
mergeFunction.validateRetract(kv);
}

@Override
public Object retractValidationKey(KeyValue kv) {
return mergeFunction.retractValidationKey(kv);
}

@Override
public boolean requireCopy() {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,29 @@ public interface MergeFunction<T> {
/** Get current merged value. */
T getResult();

/**
* Checks that this merge function accepts the given retraction, and throws if it does not. A
* writer that does not merge records, such as the postpone bucket writer, uses it to reject
* unsupported retractions early.
*
* <p>The default implementation merges the retraction alone and resets the state afterwards.
* Implementations that override it decide without computing a merged result.
*/
default void validateRetract(KeyValue kv) {
reset();
add(kv);
getResult();
reset();
}

/**
* Returns what the result of {@link #validateRetract} depends on, so that a writer only
* validates the first retraction of each key. The default is the row kind.
*/
default Object retractValidationKey(KeyValue kv) {
return kv.valueKind();
}

/** Require copy input kv, this may cache kv in memory. */
boolean requireCopy();
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
Expand All @@ -51,6 +52,7 @@
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.apache.paimon.CoreOptions.FIELDS_PREFIX;
import static org.apache.paimon.CoreOptions.FIELDS_SEPARATOR;
Expand All @@ -67,6 +69,15 @@
public class PartialUpdateMergeFunction implements MergeFunction<KeyValue> {

public static final String SEQUENCE_GROUP = "sequence-group";

private static final String RETRACT_NOT_SUPPORTED =
String.join(
"\n",
"By default, Partial update can not accept delete records,"
+ " you can choose one of the following solutions:",
"1. Configure 'ignore-delete' to ignore delete records.",
"2. Configure 'partial-update.remove-record-on-delete' to remove the whole row when receiving delete records.",
"3. Configure 'sequence-group's to retract partial columns. Also configure 'partial-update.remove-record-on-sequence-group' to remove the whole row when receiving deleted records of `specified sequence group`.");
public static final String SEQUENCE_GROUP_SORT_ORDER = SEQUENCE_GROUP + ".sort-order";
private static final String SEQUENCE_GROUP_PK_ERROR =
"The sequence-group '%s' contains primary key field '%s', "
Expand Down Expand Up @@ -133,6 +144,10 @@ public static List<String> sequenceGroupProtectedFields(String optionValue) {
private final List<WrapperWithFieldIndex<FieldsComparator>> fieldSeqComparators;
private final boolean fieldSequenceEnabled;
private final List<WrapperWithFieldIndex<FieldAggregator>> fieldAggregators;
private final Map<Integer, Object> emptyAccumulators;
/** Fields whose nullness, with the row kind, decides {@link #validateRetract}. */
private final int[] retractValidationFields;

private final boolean removeRecordOnDelete;
private final Set<Integer> sequenceGroupPartialDelete;
private final boolean[] nullables;
Expand Down Expand Up @@ -164,6 +179,27 @@ protected PartialUpdateMergeFunction(
this.ignoreDelete = ignoreDelete;
this.fieldSeqComparators = getKeySortedListFromMap(fieldSeqComparators);
this.fieldAggregators = getKeySortedListFromMap(fieldAggregators);
// Aggregators that define an empty accumulator start from it, or from null for a nullable
// field, instead of from a leading retraction. Other fields are seeded as before.
this.emptyAccumulators = new HashMap<>();
fieldAggregators.forEach(
(i, aggregator) -> {
Object emptyAccumulator = aggregator.emptyAccumulator();
if (emptyAccumulator != null) {
emptyAccumulators.put(i, nullables[i] ? null : emptyAccumulator);
}
});
boolean[] sequenceFields = new boolean[getters.length];
fieldSeqComparators
.values()
.forEach(
c ->
Arrays.stream(c.compareFields())
.forEach(f -> sequenceFields[f] = true));
this.retractValidationFields =
IntStream.range(0, getters.length)
.filter(i -> !nullables[i] || sequenceFields[i])
.toArray();
this.fieldSequenceEnabled = fieldSequenceEnabled;
this.removeRecordOnDelete = removeRecordOnDelete;
this.sequenceGroupPartialDelete = sequenceGroupPartialDelete;
Expand All @@ -188,7 +224,11 @@ public void add(KeyValue kv) {
if (kv.valueKind().isRetract()) {

if (!notNullColumnFilled) {
initRow(row, kv.value());
if (fieldSequenceEnabled && !ignoreDelete) {
initRetractRow(row, kv.value());
} else {
initRow(row, kv.value());
}
notNullColumnFilled = true;
}

Expand All @@ -214,18 +254,14 @@ public void add(KeyValue kv) {
return;
}

String msg =
String.join(
"\n",
"By default, Partial update can not accept delete records,"
+ " you can choose one of the following solutions:",
"1. Configure 'ignore-delete' to ignore delete records.",
"2. Configure 'partial-update.remove-record-on-delete' to remove the whole row when receiving delete records.",
"3. Configure 'sequence-group's to retract partial columns. Also configure 'partial-update.remove-record-on-sequence-group' to remove the whole row when receiving deleted records of `specified sequence group`.");

throw new IllegalArgumentException(msg);
throw new IllegalArgumentException(RETRACT_NOT_SUPPORTED);
}

if (ignoreDelete && fieldSequenceEnabled && notNullColumnFilled && !meetInsert) {
// The first ignored retract seeded the row, which is kept for a possible DELETE
// result. Its values must not be aggregated, so empty those aggregators.
emptyAccumulators.forEach(row::setField);
}
latestSequenceNumber = kv.sequenceNumber();
if (fieldSeqComparators.isEmpty()) {
currentDeleteRow = false;
Expand Down Expand Up @@ -415,6 +451,21 @@ private void retractWithSequenceGroup(KeyValue kv) {
}
}

private void initRetractRow(GenericRow row, InternalRow value) {
// Seed the row as initRow does, but a retraction must not seed an aggregator with its own
// contribution, so those start empty, even if their sequence group skips every record.
initRow(row, value);
emptyAccumulators.forEach(row::setField);
}

private GenericRow copyRow(GenericRow row) {
GenericRow copy = new GenericRow(row.getRowKind(), row.getFieldCount());
for (int i = 0; i < row.getFieldCount(); i++) {
copy.setField(i, row.getField(i));
}
return copy;
}

private void initRow(GenericRow row, InternalRow value) {
for (int i = 0; i < getters.length; i++) {
Object field = getters[i].getFieldOrNull(value);
Expand All @@ -425,14 +476,123 @@ private void initRow(GenericRow row, InternalRow value) {
}
}

private void checkNotNullFields(InternalRow value) {
for (int i = 0; i < getters.length; i++) {
if (!nullables[i] && getters[i].getFieldOrNull(value) == null) {
throw new IllegalArgumentException("Field " + i + " can not be null");
}
}
}

@Override
public KeyValue getResult() {
if (reused == null) {
reused = new KeyValue();
}

RowKind rowKind = currentDeleteRow || !meetInsert ? RowKind.DELETE : RowKind.INSERT;
return reused.replace(currentKey, latestSequenceNumber, rowKind, row);
GenericRow result = row;
if (fieldSequenceEnabled && !meetInsert && !currentDeleteRow && !ignoreDelete) {
// A later merge retracts the DELETE payload again. Let each aggregator convert its
// retraction-only accumulator, and keep the accumulator for subsequent calls to add().
for (WrapperWithFieldIndex<FieldAggregator> field : fieldAggregators) {
int i = field.fieldIndex;
Object accumulator = row.getField(i);
Object retraction = field.getValue().retractionResult(accumulator);
if (retraction != accumulator) {
if (result == row) {
result = copyRow(row);
}
result.setField(i, retraction);
}
}
}
return reused.replace(currentKey, latestSequenceNumber, rowKind, result);
}

@Override
public void validateRetract(KeyValue kv) {
// Mirrors the retract branches of add() for a single retraction, without computing a
// merged result. Like initRow, reject null values of non-nullable fields first.
checkNotNullFields(kv.value());
if (ignoreDelete) {
return;
}
if (fieldSequenceEnabled) {
// Visit the fields as retractWithSequenceGroup does: it retracts the aggregators of
// the sequence groups that the record sets, and skips groups whose sequence fields
// are all null.
Iterator<WrapperWithFieldIndex<FieldsComparator>> comparatorIter =
fieldSeqComparators.iterator();
WrapperWithFieldIndex<FieldsComparator> curComparator =
comparatorIter.hasNext() ? comparatorIter.next() : null;
Iterator<WrapperWithFieldIndex<FieldAggregator>> aggIter = fieldAggregators.iterator();
WrapperWithFieldIndex<FieldAggregator> curAgg =
aggIter.hasNext() ? aggIter.next() : null;
boolean[] isProcessedSequenceField = new boolean[getters.length];
for (int i = 0; i < getters.length; i++) {
FieldsComparator seqComparator = null;
if (curComparator != null && curComparator.fieldIndex == i) {
seqComparator = curComparator.getValue();
curComparator = comparatorIter.hasNext() ? comparatorIter.next() : null;
}
FieldAggregator aggregator = null;
if (curAgg != null && curAgg.fieldIndex == i) {
aggregator = curAgg.getValue();
curAgg = aggIter.hasNext() ? aggIter.next() : null;
}
if (seqComparator == null
|| isProcessedSequenceField[i]
|| isEmptySequenceGroup(kv, seqComparator, isProcessedSequenceField)) {
continue;
}
int index = i;
int[] groupFields = seqComparator.compareFields();
if (Arrays.stream(groupFields).anyMatch(f -> f == index)) {
// A DELETE of a removing sequence group re-initializes the row and stops the
// retraction, so later aggregators are not retracted.
if (kv.valueKind() == RowKind.DELETE
&& Arrays.stream(groupFields)
.anyMatch(sequenceGroupPartialDelete::contains)) {
return;
}
for (int field : groupFields) {
isProcessedSequenceField[field] = true;
}
} else if (aggregator != null) {
// retractWithSequenceGroup retracts from the row that the retraction seeded
Object field = getters[i].getFieldOrNull(kv.value());
Object accumulator =
emptyAccumulators.containsKey(i) ? emptyAccumulators.get(i) : field;
aggregator.validateRetract(accumulator, field);
}
}
return;
}
if (!removeRecordOnDelete) {
throw new IllegalArgumentException(RETRACT_NOT_SUPPORTED);
}
}

@Override
public Object retractValidationKey(KeyValue kv) {
// validateRetract depends on the row kind, on the sequence groups that the retraction sets
// and on null values of non-nullable fields, that is, on which of those fields are null
if (retractValidationFields.length < Long.SIZE) {
long key = kv.valueKind() == RowKind.DELETE ? 1 : 0;
for (int j = 0; j < retractValidationFields.length; j++) {
if (kv.value().isNullAt(retractValidationFields[j])) {
key |= 1L << (j + 1);
}
}
return key;
}
BitSet key = new BitSet();
key.set(0, kv.valueKind() == RowKind.DELETE);
for (int j = 0; j < retractValidationFields.length; j++) {
key.set(j + 1, kv.value().isNullAt(retractValidationFields[j]));
}
return key;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,19 @@ private void initRow(GenericRow row, InternalRow value) {
}
}

@Override
public void validateRetract(KeyValue kv) {
// Mirrors add() without computing a merged result
if (removeRecordOnDelete && kv.valueKind() == RowKind.DELETE) {
initRow(new GenericRow(getters.length), kv.value());
return;
}
for (int i = 0; i < getters.length; i++) {
// add() retracts from the empty row of a fresh merge
aggregators[i].validateRetract(null, getters[i].getFieldOrNull(kv.value()));
}
}

@Override
public KeyValue getResult() {
checkNotNull(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import org.apache.paimon.types.DataType;

import javax.annotation.Nullable;

import java.io.Serializable;

/** abstract class of aggregating a field of a row. */
Expand All @@ -44,8 +46,41 @@ public Object aggReversed(Object accumulator, Object inputField) {
/** reset the aggregator to a clean start state. */
public void reset() {}

/**
* Returns the accumulator before any input is aggregated, or null if the aggregator does not
* define one. It is used when a non-nullable field must be initialized from a retraction.
*/
@Nullable
public Object emptyAccumulator() {
return null;
}

/**
* Converts an accumulator that only received retractions into the value of the emitted retract
* record. A later merge retracts this value again, so the result must undo the accumulated
* retractions.
*/
@Nullable
public Object retractionResult(@Nullable Object accumulator) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

product also implements retract but keeps these defaults, so it still starts from the retracted value. Committing +I(5) and then -U(5), +U(5) reads 25 on master and on this branch. Is product meant to stay out of scope here? A line in the description would help if so.

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.

Yes, product stays out of scope. Its retraction-only state can't be stored in the field type: retractionResult() would have to return 1 / acc, which truncates to 0 for integer types. retract(null, x) also returns null, so a leading retraction is dropped. +I(5) followed by -U(5), +U(5) reads 25 on master and on this branch, so this PR doesn't change it. I opened #11465 to track it and added a note to the description.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks @houlinchn, that makes sense. The note and #11465 cover it.

return accumulator;
}

public Object retract(Object accumulator, Object retractField) {
throw new UnsupportedOperationException(
throw retractNotSupported();
}

/**
* Checks that this aggregator supports retracting the given input from the given accumulator,
* and throws as {@link #retract} does if it does not. The default implementation calls {@link
* #retract}. Aggregators that support every retraction override it to skip the computation, so
* that a check never fails on, for example, an overflow.
*/
public void validateRetract(@Nullable Object accumulator, @Nullable Object retractField) {
retract(accumulator, retractField);
}

private UnsupportedOperationException retractNotSupported() {
return new UnsupportedOperationException(
String.format(
"Aggregate function '%s' does not support retraction,"
+ " If you allow this function to ignore retraction messages,"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ private boolean contains(
return false;
}

@Override
public void validateRetract(Object accumulator, Object retractField) {}

@Override
public Object retract(Object accumulator, Object retractField) {
// it's hard to mark the input is retracted without accumulator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ public void reset() {
aggregator.reset();
}

@Override
public Object emptyAccumulator() {
return aggregator.emptyAccumulator();
}

@Override
public void validateRetract(Object accumulator, Object retractField) {}

@Override
public Object retract(Object accumulator, Object retractField) {
return accumulator;
Expand Down
Loading