ayushtkn commented on code in PR #6981:
URL: https://github.com/apache/hive/pull/6981#discussion_r4768382658


##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########
@@ -5277,7 +5295,46 @@ private static Path mvFile(HiveConf conf, FileSystem 
sourceFs, Path sourcePath,
         isRenameAllowed);
 
     if (isRenameAllowed) {
-      destFs.rename(sourcePath, destFilePath);
+      // Filesystems that take the per-query _copy_<tag> name do not use a 
numeric _copy_N
+      // counter. Parsing that tag as a counter throws or rewrites the name, 
so rename once.
+      if (FileUtils.isNonAtomicRenameFs(destFs)) {
+        destFs.rename(sourcePath, destFilePath);

Review Comment:
   The query tag only addresses name collisions. `rename` can also return 
`false` for a missing `source`, a missing parent, or a partial failure on 
`S3A`/`ABFS`, and that is still silently ignored here, so `copyFiles` reports 
success with the file left in staging.
   
   Also, `pickDestFilePath` only returns the tagged name when `taskId == -1 && 
isRenameAllowed && !isOverwrite`, the source is a file, and the tag is 
non-empty. Overwrite, ACID (taskId != -1) and directory sources on these 
filesystems still use the legacy counter name but end up in this branch.
   
   Please check the result and fail, e.g. 
   ```
   if (!destFs.rename(sourcePath, destFilePath)) { throw moveFailure("Unable to 
rename %s to %s; rename returned false", sourcePath, destFilePath); }
   ```



##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########
@@ -5277,7 +5295,46 @@ private static Path mvFile(HiveConf conf, FileSystem 
sourceFs, Path sourcePath,
         isRenameAllowed);
 
     if (isRenameAllowed) {
-      destFs.rename(sourcePath, destFilePath);
+      // Filesystems that take the per-query _copy_<tag> name do not use a 
numeric _copy_N
+      // counter. Parsing that tag as a counter throws or rewrites the name, 
so rename once.
+      if (FileUtils.isNonAtomicRenameFs(destFs)) {
+        destFs.rename(sourcePath, destFilePath);
+      } else {
+        // HDFS rename returns false (and leaves the source in place) when the 
destination
+        // already exists. Concurrent inserts can all choose the same name. 
Overwrite deletes
+        // that file and retries the same name; otherwise advance or introduce 
_copy_N.
+        String name = taskId == -1 ? 
FilenameUtils.getBaseName(sourcePath.getName()) : getPathName(taskId);
+        String currentDestFileName = destFilePath.getName();
+        Integer counterEndIdx = copyCounterEndIndex(name, currentDestFileName);
+        int counter;
+        final String prefix = name + Utilities.COPY_KEYWORD;
+        final String suffix;
+        if (counterEndIdx == null) {
+          counter = 0;
+          suffix = currentDestFileName.substring(name.length());
+        } else {
+          counter = counterEndIdx == -1 ? -1
+              : 
Integer.parseInt(currentDestFileName.substring(prefix.length(), counterEndIdx + 
1));
+          suffix = currentDestFileName.substring(counterEndIdx + 1);
+        }

Review Comment:
   This re-derives name, prefix, suffix and counter by parsing _copy_N back out 
of destFilePath, which duplicates the naming logic in pickDestFilePath (lines 
5206–5242), including the extension handling. If that logic changes, the two 
will drift.
   
   Could we instead call pickDestFilePath again when rename returns false? It 
already re-probes exists() and handles overwrite, ACID names and extensions. A 
bounded retry count that throws when exhausted would keep this a few lines and 
remove copyCounterEndIndex and the -1 sentinel.



##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########
@@ -5277,7 +5295,46 @@ private static Path mvFile(HiveConf conf, FileSystem 
sourceFs, Path sourcePath,
         isRenameAllowed);
 
     if (isRenameAllowed) {
-      destFs.rename(sourcePath, destFilePath);
+      // Filesystems that take the per-query _copy_<tag> name do not use a 
numeric _copy_N
+      // counter. Parsing that tag as a counter throws or rewrites the name, 
so rename once.
+      if (FileUtils.isNonAtomicRenameFs(destFs)) {
+        destFs.rename(sourcePath, destFilePath);
+      } else {
+        // HDFS rename returns false (and leaves the source in place) when the 
destination
+        // already exists. Concurrent inserts can all choose the same name. 
Overwrite deletes
+        // that file and retries the same name; otherwise advance or introduce 
_copy_N.
+        String name = taskId == -1 ? 
FilenameUtils.getBaseName(sourcePath.getName()) : getPathName(taskId);
+        String currentDestFileName = destFilePath.getName();
+        Integer counterEndIdx = copyCounterEndIndex(name, currentDestFileName);
+        int counter;
+        final String prefix = name + Utilities.COPY_KEYWORD;
+        final String suffix;
+        if (counterEndIdx == null) {
+          counter = 0;
+          suffix = currentDestFileName.substring(name.length());
+        } else {
+          counter = counterEndIdx == -1 ? -1
+              : 
Integer.parseInt(currentDestFileName.substring(prefix.length(), counterEndIdx + 
1));
+          suffix = currentDestFileName.substring(counterEndIdx + 1);
+        }
+        while (!destFs.rename(sourcePath, destFilePath)) {
+          if (!destFs.exists(destFilePath) || counter < 0) {
+            throw moveFailure("Unable to rename %s to %s; rename returned 
false", sourcePath, destFilePath);

Review Comment:
   This changes behaviour: a `false` from rename used to be ignored and now 
throws `IOException`. Is that intentional? 



##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########
@@ -5277,7 +5295,46 @@ private static Path mvFile(HiveConf conf, FileSystem 
sourceFs, Path sourcePath,
         isRenameAllowed);
 
     if (isRenameAllowed) {
-      destFs.rename(sourcePath, destFilePath);
+      // Filesystems that take the per-query _copy_<tag> name do not use a 
numeric _copy_N
+      // counter. Parsing that tag as a counter throws or rewrites the name, 
so rename once.
+      if (FileUtils.isNonAtomicRenameFs(destFs)) {
+        destFs.rename(sourcePath, destFilePath);
+      } else {
+        // HDFS rename returns false (and leaves the source in place) when the 
destination
+        // already exists. Concurrent inserts can all choose the same name. 
Overwrite deletes
+        // that file and retries the same name; otherwise advance or introduce 
_copy_N.
+        String name = taskId == -1 ? 
FilenameUtils.getBaseName(sourcePath.getName()) : getPathName(taskId);
+        String currentDestFileName = destFilePath.getName();
+        Integer counterEndIdx = copyCounterEndIndex(name, currentDestFileName);
+        int counter;
+        final String prefix = name + Utilities.COPY_KEYWORD;
+        final String suffix;
+        if (counterEndIdx == null) {
+          counter = 0;
+          suffix = currentDestFileName.substring(name.length());
+        } else {
+          counter = counterEndIdx == -1 ? -1
+              : 
Integer.parseInt(currentDestFileName.substring(prefix.length(), counterEndIdx + 
1));
+          suffix = currentDestFileName.substring(counterEndIdx + 1);
+        }
+        while (!destFs.rename(sourcePath, destFilePath)) {
+          if (!destFs.exists(destFilePath) || counter < 0) {
+            throw moveFailure("Unable to rename %s to %s; rename returned 
false", sourcePath, destFilePath);
+          }
+          if (isOverwrite) {
+            if (!destFs.delete(destFilePath, false)) {
+              throw moveFailure("Unable to delete %2$s to overwrite it with 
%1$s", sourcePath, destFilePath);
+            }
+            continue;
+          }

Review Comment:
   Two things on the overwrite branch. The loop is unbounded, so a persistent 
loser would spin. And on a concurrent overwrite it can delete a file another 
writer has just published. If last-writer-wins is intended, please add a 
comment saying so and cap the attempts.



##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########


Review Comment:
   The Javadoc doesn't describe the retry. Please document that the _copy_N 
retry applies only to filesystems whose rename returns false when the target 
exists (HDFS). Filesystems that overwrite on rename, such as local, are not 
covered.



##########
ql/src/test/org/apache/hadoop/hive/ql/metadata/TestHiveCopyFilesConcurrentInsert.java:
##########
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hadoop.hive.ql.metadata;
+
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RawLocalFileSystem;
+import org.apache.hadoop.hive.common.FileUtils;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.conf.HiveConfForTest;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Two inserts move a staged {@code 000000_0} into the same directory. Both 
pass the
+ * destination {@code exists()} check before either renames, which is the HDFS 
race
+ * {@link Hive#copyFiles} must recover from by publishing the loser as {@code 
_copy_N}.
+ */
+public class TestHiveCopyFilesConcurrentInsert {
+
+  private static final int WRITERS = 2;
+  private static final String STAGED_FILE_NAME = "000000_0";
+
+  private static HiveConf hiveConf;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  @BeforeClass
+  public static void setUpClass() {
+    hiveConf = new HiveConfForTest(TestHiveCopyFilesConcurrentInsert.class);
+    SessionState.start(hiveConf);
+  }
+
+  @Before
+  public void setUp() {
+    hiveConf.setIntVar(HiveConf.ConfVars.HIVE_MOVE_FILES_THREAD_COUNT, 0);
+  }
+
+  @Test
+  public void testBaseNameToCopy1() throws Exception {
+    Set<String> names = moveBoth(STAGED_FILE_NAME);
+    assertEquals(names.toString(), WRITERS, names.size());
+    assertTrue(names.contains(STAGED_FILE_NAME));
+    assertTrue(names.contains(STAGED_FILE_NAME + "_copy_1"));
+  }
+
+  /**
+   * The destination already holds {@code 000000_0} and {@code 
000000_0_copy_1}, so both writers
+   * choose {@code 000000_0_copy_2}. The loser of that rename must be 
published as
+   * {@code 000000_0_copy_3}.
+   */
+  @Test
+  public void testAdvancementToNextCopy() throws Exception {
+    String copy2 = STAGED_FILE_NAME + "_copy_2";
+    Set<String> names = moveBoth(copy2, STAGED_FILE_NAME, STAGED_FILE_NAME + 
"_copy_1");
+    assertEquals(names.toString(),
+        new HashSet<>(Arrays.asList(
+            STAGED_FILE_NAME, STAGED_FILE_NAME + "_copy_1", copy2, 
STAGED_FILE_NAME + "_copy_3")),
+        names);
+  }
+

Review Comment:
   Please add coverage for the other branches changed here:
   
   isOverwrite = true, where both writers should succeed and one file should 
remain
   a staged file with an extension (e.g. 000000_0.gz), to check that suffix is 
preserved
   a rename that returns false with no existing destination, which should throw
   Once rename is checked in the non-atomic branch, add a case for that branch 
too.



##########
ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java:
##########
@@ -5277,7 +5295,46 @@ private static Path mvFile(HiveConf conf, FileSystem 
sourceFs, Path sourcePath,
         isRenameAllowed);
 
     if (isRenameAllowed) {
-      destFs.rename(sourcePath, destFilePath);
+      // Filesystems that take the per-query _copy_<tag> name do not use a 
numeric _copy_N
+      // counter. Parsing that tag as a counter throws or rewrites the name, 
so rename once.

Review Comment:
   This comment is only true when the tagged name was actually used (see my 
comment on line 5301). Please reword it, or gate this branch on whether the tag 
was applied rather than on the filesystem alone.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to