voonhous commented on code in PR #20857:
URL: https://github.com/apache/hudi/pull/20857#discussion_r4696178659
##########
hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/table/action/deltacommit/SparkUpsertDeltaCommitPartitioner.java:
##########
@@ -53,6 +53,11 @@ public SparkUpsertDeltaCommitPartitioner(WorkloadProfile
profile, HoodieSparkEng
@Override
protected List<SmallFile> getSmallFiles(String partitionPath) {
+ if (config.isSparkSqlMergeIntoReadingTarget()) {
Review Comment:
**blocker:** Returning no small files for every flagged statement means each
one that inserts opens a new file group per partition: three MERGEs inserting
one key each left 4 file groups for 4 rows, against 1 without the flag. The
re-evaluation this guards against needs a small file that also receives
resolved records. Could only the candidates whose file id is in
`updateLocationToBucket` be dropped, keeping packing for the rest?
##########
hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieIndexUtils.java:
##########
@@ -558,6 +659,101 @@ public static <R> HoodieData<HoodieRecord<R>>
mergeForPartitionUpdatesAndDeletio
return taggedUpdatingRecords.union(taggedNewRecords);
}
+ /**
+ * Resolves each located record of a Spark SQL MERGE INTO write against the
record it matches, read from the
+ * latest merged file slice of the located file group, so that its matched
clauses see the fields of the target
+ * table. A record the clauses update is replaced with its new version and a
record they delete with a delete
+ * record, both at the location and row position the index tagged, and a
record none of them accepts is dropped.
+ * A record whose location holds no live record with its key, as a deleted
copy in a base file or the bucket of a
+ * bucket index can get it tagged, is replaced with what its not-matched
clauses make of it at the same location,
+ * and dropped when none of them accepts it. The records of any other write
are returned as they are.
+ */
+ public static <R> HoodieData<HoodieRecord<R>>
mergeLocatedExpressionPayloadRecords(HoodieData<HoodieRecord<R>> taggedRecords,
+
HoodieWriteConfig config,
+
HoodieTable hoodieTable,
+
int parallelism) {
+ if (!EXPRESSION_PAYLOAD_CLASS_NAME.equals(config.getPayloadClass())) {
+ return taggedRecords;
+ }
+ HoodieReaderContext<R> readerContext = ((ReaderContextFactory<R>)
hoodieTable.getContext()
+ .getReaderContextFactoryForWrite(hoodieTable.getMetaClient(),
config.getRecordMerger().getRecordType(), config.getProps())).getContext();
+ readerContext.initRecordMergerForIngestion(config.getProps());
+ HoodieSchema writerSchema = HoodieSchema.parse(config.getWriteSchema());
+ ExistingRecordMerger<R> merger = new ExistingRecordMerger<>(config,
hoodieTable, readerContext, writerSchema);
+ TypedProperties notMatchedProps = TypedProperties.copy(config.getProps());
+
notMatchedProps.setProperty(HoodiePayloadProps.PAYLOAD_IS_UPDATE_RECORD_FOR_MOR,
"false");
+ HoodieData<HoodieRecord<R>> locatedRecords =
taggedRecords.filter(HoodieIndexUtils::isLocatedExpressionPayloadRecord);
+ HoodieData<Pair<String, String>> locations = locatedRecords
+ .map(record -> Pair.of(record.getPartitionPath(),
record.getCurrentLocation().getFileId()))
+ .distinct(parallelism);
+ HoodieData<HoodieRecord<R>> resolvedRecords =
locatedRecords.mapToPair(record -> Pair.of(fileIdAndRecordKey(record), record))
+ .groupByKey()
+ .leftOuterJoin(merger.getExistingRecords(locations, hoodieTable, true)
+ .mapToPair(record -> Pair.of(fileIdAndRecordKey(record),
record)).groupByKey())
+ .values()
+ .flatMap(entry -> pairWithExistingRecords(entry.getLeft(),
entry.getRight()).iterator())
+ .flatMap(entry -> {
+ HoodieRecord<R> incoming = entry.getLeft();
+ if (!entry.getRight().isPresent()) {
+ Option<IndexedRecord> inserted = ((HoodieRecordPayload<?>)
incoming.getData()).getInsertValue(writerSchema.toAvroSchema(),
notMatchedProps);
+ if (!inserted.isPresent() ||
inserted.get().equals(HoodieRecord.SENTINEL)) {
+ return Collections.emptyIterator();
+ }
+ HoodieRecord<R> insertRecord = (HoodieRecord<R>) new
HoodieAvroIndexedRecord(incoming.getKey(), inserted.get());
+ return Collections.singletonList(tagRecord(insertRecord,
incoming.getCurrentLocation())).iterator();
+ }
+ Option<HoodieRecord<R>> mergedOpt = merger.merge(incoming,
entry.getRight().get());
+ if (mergedOpt.isPresent() &&
mergedOpt.get().getData().equals(HoodieRecord.SENTINEL)) {
+ return Collections.emptyIterator();
+ }
+ HoodieRecord<R> resolved = mergedOpt.isPresent()
+ ? mergedOpt.get().newInstance(incoming.getKey()) :
createDeleteRecord(config, incoming.getKey());
+ return Collections.singletonList(tagRecord(resolved,
incoming.getCurrentLocation())).iterator();
+ });
+ return taggedRecords.filter(record ->
!isLocatedExpressionPayloadRecord(record)).union(resolvedRecords);
+ }
+
+ /**
+ * Pairs the located records of one record key in one file group with the
records the file group holds for the key.
+ * A file group can hold a key more than once, and an index that reads the
base file locates the incoming record at
+ * each of its rows, so each such row is paired with the located record at
its position. When the positions do not
+ * tell the rows apart, one located record is paired with one record of the
key.
+ */
+ private static <R> List<Pair<HoodieRecord<R>, Option<HoodieRecord<R>>>>
pairWithExistingRecords(
+ Iterable<HoodieRecord<R>> locatedRecords,
Option<Iterable<HoodieRecord<R>>> existingRecords) {
+ HoodieRecord<R> firstLocated = locatedRecords.iterator().next();
+ if (!existingRecords.isPresent()) {
+ return Collections.singletonList(Pair.of(firstLocated, Option.empty()));
+ }
+ Map<Long, HoodieRecord<R>> locatedByPosition = new HashMap<>();
+ for (HoodieRecord<R> located : locatedRecords) {
+ long position = located.getCurrentLocation().getPosition();
+ if (HoodieRecordLocation.isPositionValid(position)) {
+ locatedByPosition.putIfAbsent(position, located);
+ }
+ }
+ List<Pair<HoodieRecord<R>, Option<HoodieRecord<R>>>> pairs = new
ArrayList<>();
+ for (HoodieRecord<R> existing : existingRecords.get()) {
+ HoodieRecord<R> located =
locatedByPosition.get(existing.getCurrentLocation().getPosition());
+ if (located != null) {
+ pairs.add(Pair.of(located, Option.of(existing)));
+ }
+ }
+ if (pairs.isEmpty()) {
+ pairs.add(Pair.of(firstLocated,
Option.of(existingRecords.get().iterator().next())));
+ }
+ return pairs;
+ }
+
+ private static boolean isLocatedExpressionPayloadRecord(HoodieRecord<?>
record) {
+ return record.isCurrentLocationKnown() && record.getData() instanceof
HoodieRecordPayload
+ &&
EXPRESSION_PAYLOAD_CLASS_NAME.equals(record.getData().getClass().getName());
+ }
+
+ private static Pair<String, String> fileIdAndRecordKey(HoodieRecord<?>
record) {
Review Comment:
**blocker:** `fileIdAndRecordKey` leaves out the partition, but file ids
repeat across partitions for the bucket index under NBCC
(`BucketIdentifier.newBucketFileIdForNBCC`). On a partitioned MOR table with 1
bucket and id 1 in `d1` (price 10) and `d2` (price 20), `update set price =
t.price + s.price` with source prices 1 and 2 gave `d1 = 21.0` and left `d2`
unchanged. Could the key be (partition path, file id, record key), as the
`locations` pair already is?
##########
hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieIndexUtils.java:
##########
@@ -558,6 +659,101 @@ public static <R> HoodieData<HoodieRecord<R>>
mergeForPartitionUpdatesAndDeletio
return taggedUpdatingRecords.union(taggedNewRecords);
}
+ /**
+ * Resolves each located record of a Spark SQL MERGE INTO write against the
record it matches, read from the
+ * latest merged file slice of the located file group, so that its matched
clauses see the fields of the target
+ * table. A record the clauses update is replaced with its new version and a
record they delete with a delete
+ * record, both at the location and row position the index tagged, and a
record none of them accepts is dropped.
+ * A record whose location holds no live record with its key, as a deleted
copy in a base file or the bucket of a
+ * bucket index can get it tagged, is replaced with what its not-matched
clauses make of it at the same location,
+ * and dropped when none of them accepts it. The records of any other write
are returned as they are.
+ */
+ public static <R> HoodieData<HoodieRecord<R>>
mergeLocatedExpressionPayloadRecords(HoodieData<HoodieRecord<R>> taggedRecords,
+
HoodieWriteConfig config,
+
HoodieTable hoodieTable,
+
int parallelism) {
+ if (!EXPRESSION_PAYLOAD_CLASS_NAME.equals(config.getPayloadClass())) {
+ return taggedRecords;
+ }
+ HoodieReaderContext<R> readerContext = ((ReaderContextFactory<R>)
hoodieTable.getContext()
+ .getReaderContextFactoryForWrite(hoodieTable.getMetaClient(),
config.getRecordMerger().getRecordType(), config.getProps())).getContext();
+ readerContext.initRecordMergerForIngestion(config.getProps());
+ HoodieSchema writerSchema = HoodieSchema.parse(config.getWriteSchema());
+ ExistingRecordMerger<R> merger = new ExistingRecordMerger<>(config,
hoodieTable, readerContext, writerSchema);
+ TypedProperties notMatchedProps = TypedProperties.copy(config.getProps());
+
notMatchedProps.setProperty(HoodiePayloadProps.PAYLOAD_IS_UPDATE_RECORD_FOR_MOR,
"false");
+ HoodieData<HoodieRecord<R>> locatedRecords =
taggedRecords.filter(HoodieIndexUtils::isLocatedExpressionPayloadRecord);
+ HoodieData<Pair<String, String>> locations = locatedRecords
+ .map(record -> Pair.of(record.getPartitionPath(),
record.getCurrentLocation().getFileId()))
+ .distinct(parallelism);
+ HoodieData<HoodieRecord<R>> resolvedRecords =
locatedRecords.mapToPair(record -> Pair.of(fileIdAndRecordKey(record), record))
+ .groupByKey()
+ .leftOuterJoin(merger.getExistingRecords(locations, hoodieTable, true)
+ .mapToPair(record -> Pair.of(fileIdAndRecordKey(record),
record)).groupByKey())
+ .values()
+ .flatMap(entry -> pairWithExistingRecords(entry.getLeft(),
entry.getRight()).iterator())
+ .flatMap(entry -> {
+ HoodieRecord<R> incoming = entry.getLeft();
+ if (!entry.getRight().isPresent()) {
+ Option<IndexedRecord> inserted = ((HoodieRecordPayload<?>)
incoming.getData()).getInsertValue(writerSchema.toAvroSchema(),
notMatchedProps);
Review Comment:
**blocker:** Under event-time ordering, the insert written here at the old
location loses to the deleted base row when its ordering value is lower: insert
`(1,'a',10.0,ts=100)`, delete it via MERGE, then MERGE `(1,'b',5.0,ts=50)` with
`when not matched then insert *` reads back `[1,a,10.0,100]` on MOR and
`[1,b,5.0,50]` on COW. Could this case get a test, and either be fixed here or
listed as a known limit in the description?
##########
hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieIndexUtils.java:
##########
@@ -558,6 +659,101 @@ public static <R> HoodieData<HoodieRecord<R>>
mergeForPartitionUpdatesAndDeletio
return taggedUpdatingRecords.union(taggedNewRecords);
}
+ /**
+ * Resolves each located record of a Spark SQL MERGE INTO write against the
record it matches, read from the
+ * latest merged file slice of the located file group, so that its matched
clauses see the fields of the target
+ * table. A record the clauses update is replaced with its new version and a
record they delete with a delete
+ * record, both at the location and row position the index tagged, and a
record none of them accepts is dropped.
+ * A record whose location holds no live record with its key, as a deleted
copy in a base file or the bucket of a
+ * bucket index can get it tagged, is replaced with what its not-matched
clauses make of it at the same location,
+ * and dropped when none of them accepts it. The records of any other write
are returned as they are.
+ */
+ public static <R> HoodieData<HoodieRecord<R>>
mergeLocatedExpressionPayloadRecords(HoodieData<HoodieRecord<R>> taggedRecords,
+
HoodieWriteConfig config,
+
HoodieTable hoodieTable,
+
int parallelism) {
+ if (!EXPRESSION_PAYLOAD_CLASS_NAME.equals(config.getPayloadClass())) {
+ return taggedRecords;
+ }
+ HoodieReaderContext<R> readerContext = ((ReaderContextFactory<R>)
hoodieTable.getContext()
+ .getReaderContextFactoryForWrite(hoodieTable.getMetaClient(),
config.getRecordMerger().getRecordType(), config.getProps())).getContext();
+ readerContext.initRecordMergerForIngestion(config.getProps());
+ HoodieSchema writerSchema = HoodieSchema.parse(config.getWriteSchema());
+ ExistingRecordMerger<R> merger = new ExistingRecordMerger<>(config,
hoodieTable, readerContext, writerSchema);
+ TypedProperties notMatchedProps = TypedProperties.copy(config.getProps());
+
notMatchedProps.setProperty(HoodiePayloadProps.PAYLOAD_IS_UPDATE_RECORD_FOR_MOR,
"false");
+ HoodieData<HoodieRecord<R>> locatedRecords =
taggedRecords.filter(HoodieIndexUtils::isLocatedExpressionPayloadRecord);
Review Comment:
**blocker:** This reads every row of each located file group and shuffles
them through `groupByKey` and `leftOuterJoin`, so cost follows file-group size,
not the size of the source. `taggedRecords` also feeds two filters and the
`distinct` without being persisted, so with a bucket index and no ordering
field the source query is recomputed three times. Could `taggedRecords` be
persisted here, and the existing rows filtered to the located keys before the
shuffle?
--
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]