yihua commented on code in PR #20890:
URL: https://github.com/apache/hudi/pull/20890#discussion_r4725525332


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala:
##########
@@ -1357,26 +1358,43 @@ object HoodieSparkSqlWriterInternal {
       shouldDropDuplicatesForInserts(hoodieConfig)
   }
 
+  // An insert into a table of a non-native table format with a record key 
that sets no duplicate policy fails on
+  // duplicate record keys. A native table keeps them unless a policy says 
otherwise. This is the format the table
+  // loads, which is native for a name that no table format implementation 
answers to, such as NATIVE.
+  def failsOnDuplicatesByDefault(hoodieConfig: HoodieConfig, tableMetaClient: 
HoodieTableMetaClient): Boolean = {
+    !hoodieConfig.contains(INSERT_DUP_POLICY) &&
+      
!NativeTableFormat.TABLE_FORMAT.equals(tableMetaClient.getTableFormat.getName) 
&&
+      !shouldAutoGenerateRecordKeys(hoodieConfig.getProps.asScala.toMap)
+  }
+
   // Check if deduplication is needed.
   def isDeduplicationNeeded(operation: WriteOperationType): Boolean = {
     operation == WriteOperationType.INSERT
   }
 
   def handleInsertDuplicates(incomingRecords: JavaRDD[HoodieRecord[_]],
                              hoodieConfig: HoodieConfig,
+                             tableMetaClient: HoodieTableMetaClient,
                              operation: WriteOperationType,
-                             client: SparkRDDWriteClient[_]): 
JavaRDD[HoodieRecord[_]] = {
-    // If no deduplication is needed, return the incoming records as is
-    if (!isDeduplicationRequired(hoodieConfig) || 
!isDeduplicationNeeded(operation)) {
+                             client: SparkRDDWriteClient[_],
+                             instantTime: String): JavaRDD[HoodieRecord[_]] = {
+    // Resolve duplicates on the committing client's engine context and config 
rather than a throwaway
+    // context. The record index lookup this triggers collects its counters 
into a registry owned by the
+    // context that ran the lookup, and postCommit drains the client's 
context; a separate context would
+    // strand those counters and the INSERT would publish none. See 
RecordIndexLookupMetrics.
+    lazy val engineContext = 
client.getEngineContext.asInstanceOf[HoodieSparkEngineContext]
+    if (!isDeduplicationNeeded(operation)) {
+      incomingRecords
+    } else if (shouldFailWhenDuplicatesFound(hoodieConfig)) {
+      DataSourceUtils.failOnDuplicates(engineContext, incomingRecords, 
client.getConfig, instantTime, true)
+      incomingRecords
+    } else if (isDeduplicationRequired(hoodieConfig)) {
+      DataSourceUtils.handleDuplicates(engineContext, incomingRecords, 
client.getConfig, false)
+    } else if (failsOnDuplicatesByDefault(hoodieConfig, tableMetaClient)) {

Review Comment:
   Fixed, the check now runs on the records the write inserts, skipping those 
no insert clause accepts (`shouldIgnore`, as the create handles do), and 
`TestInsertTable5` covers your exact case on COW and MOR for a non-native and a 
native table, plus the both-accepted twin failing and the `fail` policy looking 
the table up only for accepted rows.



##########
hudi-spark-datasource/hudi-spark-common/src/main/java/org/apache/hudi/DataSourceUtils.java:
##########
@@ -283,6 +297,114 @@ public static JavaRDD<HoodieRecord> 
handleDuplicates(HoodieSparkEngineContext en
     }
   }
 
+  /**
+   * Fails an insert before it writes, with a {@link 
HoodieDuplicateKeyException} as the cause, if a record key
+   * repeats among the incoming records, unless {@code 
hoodie.combine.before.insert} combines them, or, with
+   * {@code lookUpDataset}, is already present in the dataset.
+   *
+   * <p>The check runs as jobs of its own and the write gets the incoming 
records as they are, in their order
+   * and partitioning. The incoming records are persisted for that at the 
level the write persists them at, so
+   * that the check and the write read them once, and are released with the 
resources of the instant.
+   */
+  public static void failOnDuplicates(HoodieSparkEngineContext engineContext,
+                                      JavaRDD<HoodieRecord> 
incomingHoodieRecords,
+                                      HoodieWriteConfig writeConfig,
+                                      String instantTime,
+                                      boolean lookUpDataset) {
+    boolean checkIncomingRecords = !writeConfig.shouldCombineBeforeInsert();
+    if (!checkIncomingRecords && !lookUpDataset) {
+      return;
+    }
+    boolean persist = incomingHoodieRecords.getStorageLevel() == 
StorageLevel.NONE();
+    if (persist) {
+      
HoodieJavaRDD.of(incomingHoodieRecords).persist(writeConfig.getTaggedRecordStorageLevel(),
+          engineContext, 
HoodieData.HoodieDataCacheKey.of(writeConfig.getBasePath(), instantTime));
+    }
+    try {
+      if (checkIncomingRecords) {
+        failOnIncomingDuplicates(incomingHoodieRecords, writeConfig);
+      }
+      if (lookUpDataset) {
+        // An index persists the records it tags and releases them once they 
are tagged, so it gets a view of
+        // the incoming records, which stay persisted for the write
+        handleDuplicates(engineContext, incomingHoodieRecords.map(record -> 
record), writeConfig, true).count();
+      }
+    } catch (Exception e) {
+      if (persist) {
+        incomingHoodieRecords.unpersist();
+      }
+      throw new HoodieInsertException("Failed to insert for commit time " + 
instantTime, e);
+    }
+  }
+
+  /**
+   * The duplicate handling of an insert into a table with a record key that 
sets no duplicate policy:
+   * {@link #failOnDuplicates}, where the dataset is looked up only through a 
built record level index, see
+   * {@link #looksUpDatasetByDefault}.
+   */
+  public static void failOnDuplicatesByDefault(HoodieSparkEngineContext 
engineContext,
+                                               JavaRDD<HoodieRecord> 
incomingHoodieRecords,
+                                               HoodieWriteConfig writeConfig,
+                                               String instantTime) {
+    failOnDuplicates(engineContext, incomingHoodieRecords, writeConfig, 
instantTime, looksUpDatasetByDefault(engineContext, writeConfig));
+  }
+
+  /**
+   * Whether the duplicate handling of an insert without a duplicate policy 
looks the dataset up. Only a built record
+   * level index answers that lookup from the metadata table, seeing the 
deletes in the log files of a merge-on-read
+   * table; the other indexes read the keys of the base files, or locate any 
key (bucket index), so with them the
+   * incoming records alone are checked. Until the record level index is 
built, it falls back to such an index.
+   */
+  private static boolean looksUpDatasetByDefault(HoodieSparkEngineContext 
engineContext, HoodieWriteConfig writeConfig) {
+    if (!StringUtils.isNullOrEmpty(writeConfig.getIndexClass())) {
+      return false;
+    }
+    switch (writeConfig.getIndexType()) {
+      case RECORD_INDEX:
+      case GLOBAL_RECORD_LEVEL_INDEX:
+      case RECORD_LEVEL_INDEX:
+        return isRecordIndexBuilt(engineContext, writeConfig);

Review Comment:
   Done, `NativeBackedTestTableFormat` keeps the native timeline and metadata 
table under another name, and `testInsertWithBuiltRecordIndexChecksKeysInTable` 
(COW and MOR) asserts the record index is built, fails a no-policy insert of a 
key in the table, and inserts it again after a delete that lands in a log file 
on MOR.



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestInsertDedupPolicy.scala:
##########
@@ -84,7 +89,7 @@ class TestInsertDedupPolicy extends 
SparkClientFunctionalTestHarness {
     if (dedupPolicy.equals(FAIL_INSERT_DUP_POLICY)) {
       // Write and check throws.
       Assertions.assertThrows(
-        classOf[HoodieUpsertException],
+        classOf[HoodieInsertException],

Review Comment:
   Done, the native-table cells insert (5,'a'),(5,'b') under `fail` with no 
existing key and assert "More than one inserted record has this key", and the 
`hoodie.combine.before.insert=true` twin keeps (5,'b').



##########
hudi-spark-datasource/hudi-spark-common/src/main/java/org/apache/hudi/DataSourceUtils.java:
##########
@@ -283,6 +297,114 @@ public static JavaRDD<HoodieRecord> 
handleDuplicates(HoodieSparkEngineContext en
     }
   }
 
+  /**
+   * Fails an insert before it writes, with a {@link 
HoodieDuplicateKeyException} as the cause, if a record key
+   * repeats among the incoming records, unless {@code 
hoodie.combine.before.insert} combines them, or, with
+   * {@code lookUpDataset}, is already present in the dataset.
+   *
+   * <p>The check runs as jobs of its own and the write gets the incoming 
records as they are, in their order
+   * and partitioning. The incoming records are persisted for that at the 
level the write persists them at, so
+   * that the check and the write read them once, and are released with the 
resources of the instant.
+   */
+  public static void failOnDuplicates(HoodieSparkEngineContext engineContext,
+                                      JavaRDD<HoodieRecord> 
incomingHoodieRecords,
+                                      HoodieWriteConfig writeConfig,
+                                      String instantTime,
+                                      boolean lookUpDataset) {
+    boolean checkIncomingRecords = !writeConfig.shouldCombineBeforeInsert();
+    if (!checkIncomingRecords && !lookUpDataset) {
+      return;
+    }
+    boolean persist = incomingHoodieRecords.getStorageLevel() == 
StorageLevel.NONE();

Review Comment:
   Thanks, good catch. I'd like to leave this as a follow-up: the write's own 
persisted copy is derived from this one and only materializes inside the commit 
action, so this layer has no point to release its copy without a hook in the 
write path, and persisting only the shuffled keys would read the source twice, 
which `testDuplicateKeyCheckKeepsOrderOfInsertedRecords` pins as once. Both 
copies are released with the instant's resources at commit.



-- 
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]

Reply via email to