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


##########
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:
   **blocker:** No test reaches the `true` arm here, so the branch that fails 
an insert of a key the table already holds could break with the suite green. 
Every RLI cell keeps the index unbuilt, and `TestTableFormat`'s metadata is 
`FileSystemBackedTableMetadata`, whose `readRecordIndexLocationsWithKeys` 
throws "Unsupported operation: readRecordIndex!", so the `(indexType == 
"RECORD_INDEX")` flags in the tests are always false. Could we add a test 
format that extends `NativeTableFormat` under another name, with cells for 
"built RLI, key in table, no policy, fails" and "key deleted in a MOR log, 
insert succeeds"?



##########
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:
   **blocker:** A keyed MERGE INTO with only a NOT MATCHED clause and no 
ordering field is written as INSERT 
(`MergeIntoHoodieTableCommand.getOperationType`), so this check counts source 
rows whose insert condition is false, which `ExpressionPayload` would skip. On 
a non-native table, source rows `(1,'a','I')`, `(1,'b','D')` with `when not 
matched and s.op = 'I' then insert` fail with `HoodieDuplicateKeyException` 
(and INSERT INTO advice); a native table inserts `[1,a]`. Could the default 
skip MERGE INTO writes (`SQL_MERGE_INTO_WRITES=true`), or run after the insert 
condition is applied?



##########
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:
   **minor:** With the bucket index (which tags inserts) or `fail` with 
`combine.before.insert=true`, the write persists a different RDD than this one, 
so two serialized copies of the input stay cached until commit, where master 
kept one. Could the check persist only the keys it shuffles, or release its 
copy once the write has its own? Not blocking.



##########
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:
   **blocker:** `fail` now also rejects a key repeated within the batch, on 
native tables too, but that change is untested: every `fail` test (here, 
`TestInsertTable.scala:447`, `TestInsertTable4.scala:738`) includes a key the 
table already holds, so passing `checkIncomingRecords=false` from the `fail` 
branch keeps the suite green. Could we add a native-table `fail` cell inserting 
`(5,'a'),(5,'b')` with no existing key, asserting "More than one inserted 
record has this key", plus a `combine.before.insert=true` twin that keeps one 
row?



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