This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 94cd9fbb9e6 Bound archive extraction for controller segment uploads 
(#20458)
94cd9fbb9e6 is described below

commit 94cd9fbb9e637b4ee64e9dc135a49e95816d617b
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Dec 4 21:04:32 2026 -0800

    Bound archive extraction for controller segment uploads (#20458)
    
    * Bound batch segment metadata archive extraction
    
    * Honor inclusive batch metadata limits
    
    Check the entry count independently from byte accounting and size the batch 
default for wide tables. TarCompressionUtilsTest exercises a normal metadata 
archive at and immediately above the byte limit.
    
    * Apply archive limits to controller segment uploads
    
    Use separate metadata and full-segment limits, validate them at startup, 
and document HTTP 413 across the upload routes.
---
 .../pinot/common/utils/TarCompressionUtils.java    |  75 +++++++++++--
 .../common/utils/TarCompressionUtilsTest.java      |  21 ++++
 .../pinot/controller/BaseControllerStarter.java    |   2 +-
 .../apache/pinot/controller/ControllerConf.java    |  81 +++++++++++--
 .../PinotSegmentUploadDownloadRestletResource.java |  51 ++++++---
 .../pinot/controller/ControllerConfTest.java       |  32 ++++++
 .../api/PinotSegmentUploadAuthorizationTest.java   |  52 +++++++++
 ...otSegmentUploadDownloadRestletResourceTest.java | 125 ++++++++++++++++-----
 .../core/metadata/DefaultMetadataExtractor.java    |  16 ++-
 9 files changed, 392 insertions(+), 63 deletions(-)

diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
index a1fd4bf0571..b5de8f06e7d 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
@@ -44,6 +44,7 @@ import org.apache.commons.compress.archivers.tar.TarConstants;
 import org.apache.commons.compress.compressors.CompressorException;
 import org.apache.commons.compress.compressors.CompressorStreamFactory;
 import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.input.BoundedInputStream;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.pinot.common.compression.Lz4CompressorStreamProvider;
 
@@ -199,7 +200,25 @@ public class TarCompressionUtils {
   public static List<File> untar(File inputFile, File outputDir, @Nullable 
ArchivePathBudget pathBudget)
       throws IOException {
     try (InputStream fileIn = Files.newInputStream(inputFile.toPath())) {
-      return untarWithRateLimiter(fileIn, outputDir, NO_DISK_WRITE_RATE_LIMIT, 
pathBudget);
+      return untar(fileIn, outputDir, NO_DISK_WRITE_RATE_LIMIT, -1, -1, 
pathBudget);
+    }
+  }
+
+  /// Extracts a compressed TAR with positive limits on decompressed bytes and 
file/directory entries.
+  /// The byte limit applies to both the TAR stream and the total size of the 
extracted files.
+  public static List<File> untarWithLimits(File inputFile, File outputDir, 
long maxExpandedBytes, int maxEntries)
+      throws IOException {
+    return untarWithLimits(inputFile, outputDir, maxExpandedBytes, maxEntries, 
null);
+  }
+
+  /// Extracts a compressed TAR with byte and entry limits and an optional 
shared path budget.
+  public static List<File> untarWithLimits(File inputFile, File outputDir, 
long maxExpandedBytes, int maxEntries,
+      @Nullable ArchivePathBudget pathBudget)
+      throws IOException {
+    Preconditions.checkArgument(maxExpandedBytes > 0, "Archive byte limit must 
be positive");
+    Preconditions.checkArgument(maxEntries > 0, "Archive entry limit must be 
positive");
+    try (InputStream fileIn = Files.newInputStream(inputFile.toPath())) {
+      return untar(fileIn, outputDir, NO_DISK_WRITE_RATE_LIMIT, 
maxExpandedBytes, maxEntries, pathBudget);
     }
   }
 
@@ -217,11 +236,11 @@ public class TarCompressionUtils {
   /// For security reason, the untarred files must reside in the output 
directory.
   public static List<File> untarWithRateLimiter(InputStream inputStream, File 
outputDir, long maxStreamRateInByte)
       throws IOException {
-    return untarWithRateLimiter(inputStream, outputDir, maxStreamRateInByte, 
null);
+    return untar(inputStream, outputDir, maxStreamRateInByte, -1, -1, null);
   }
 
-  private static List<File> untarWithRateLimiter(InputStream inputStream, File 
outputDir, long maxStreamRateInByte,
-      @Nullable ArchivePathBudget pathBudget)
+  private static List<File> untar(InputStream inputStream, File outputDir, 
long maxStreamRateInByte,
+      long maxExpandedBytes, int maxEntries, @Nullable ArchivePathBudget 
pathBudget)
       throws IOException {
     String outputDirCanonicalPath = outputDir.getCanonicalPath();
     // Prevent partial path traversal
@@ -229,12 +248,26 @@ public class TarCompressionUtils {
       outputDirCanonicalPath += File.separator;
     }
     List<File> untarredFiles = new ArrayList<>();
+    long remainingFileBytes = maxExpandedBytes;
     try (InputStream bufferedIn = new BufferedInputStream(inputStream);
         InputStream compressorIn = 
COMPRESSOR_STREAM_FACTORY.createCompressorInputStream(bufferedIn);
-        TarArchiveInputStream tarIn = pathBudget == null ? new 
TarArchiveInputStream(compressorIn)
-            : new PathBudgetTarInputStream(compressorIn, pathBudget)) {
-      ArchiveEntry entry;
+        TarArchiveInputStream tarIn = newTarInputStream(compressorIn, 
maxExpandedBytes, pathBudget)) {
+      TarArchiveEntry entry;
       while ((entry = tarIn.getNextEntry()) != null) {
+        if (maxEntries > 0 && untarredFiles.size() == maxEntries) {
+          throw new ArchiveExtractionLimitException("Archive exceeds the entry 
limit");
+        }
+        if (maxExpandedBytes > 0) {
+          // The logical size can exceed the TAR stream size for sparse files.
+          long fileBytes = entry.getRealSize();
+          if (fileBytes < 0) {
+            throw new IOException("Invalid archive entry size");
+          }
+          if (fileBytes > remainingFileBytes) {
+            throw new ArchiveExtractionLimitException("Archive exceeds the 
expanded byte limit");
+          }
+          remainingFileBytes -= fileBytes;
+        }
         String entryName = entry.getName();
         if (pathBudget != null) {
           pathBudget.charge(entryName);
@@ -287,6 +320,32 @@ public class TarCompressionUtils {
     return untarredFiles;
   }
 
+  private static TarArchiveInputStream newTarInputStream(InputStream 
inputStream, long maxExpandedBytes,
+      @Nullable ArchivePathBudget pathBudget)
+      throws IOException {
+    InputStream tarStream = inputStream;
+    if (maxExpandedBytes > 0) {
+      tarStream = 
BoundedInputStream.builder().setInputStream(inputStream).setMaxCount(maxExpandedBytes)
+          .setPropagateClose(false).setOnMaxCount((max, count) -> {
+            // A read at the limit can be the TAR reader checking for the end 
of the stream.
+            if (inputStream.read() != -1) {
+              throw new ArchiveExtractionLimitException("Archive exceeds the 
expanded byte limit");
+            }
+          }).get();
+    }
+    return pathBudget == null ? new TarArchiveInputStream(tarStream)
+        : new PathBudgetTarInputStream(tarStream, pathBudget);
+  }
+
+  /// The archive exceeded a byte, entry, or path limit supplied by its caller.
+  public static class ArchiveExtractionLimitException extends IOException {
+    private static final long serialVersionUID = 1L;
+
+    private ArchiveExtractionLimitException(String message) {
+      super(message);
+    }
+  }
+
   /// Enforces the path budget on extension headers that Commons Compress 
handles inside getNextEntry().
   /// Like the underlying TAR reader, this stream is not thread-safe.
   private static final class PathBudgetTarInputStream extends 
TarArchiveInputStream {
@@ -369,7 +428,7 @@ public class TarCompressionUtils {
   }
 
   /// Signals that an archive entry exceeded a path limit.
-  public static final class ArchivePathLimitException extends IOException {
+  public static final class ArchivePathLimitException extends 
ArchiveExtractionLimitException {
     private static final long serialVersionUID = 1L;
 
     private ArchivePathLimitException(String message) {
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
index c8203689e49..f448b572774 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
@@ -113,6 +113,27 @@ public class TarCompressionUtilsTest {
     assertEquals(FileUtils.readFileToString(untarredFile, 
StandardCharsets.UTF_8), fileContent);
   }
 
+  @Test
+  public void testExpandedByteLimitIsInclusive()
+      throws IOException, CompressorException {
+    File metadata = new File(DATA_DIR, "metadata.properties");
+    FileUtils.writeStringToFile(metadata, "segment.name=testSegment", 
StandardCharsets.UTF_8);
+    for (String extension : 
TarCompressionUtils.COMPRESSOR_NAME_BY_FILE_EXTENSIONS.keySet()) {
+      File archive = new File(TAR_DIR, "metadata" + extension);
+      TarCompressionUtils.createCompressedTarFile(metadata, archive);
+      long expandedBytes;
+      try (InputStream bufferedIn = new 
BufferedInputStream(Files.newInputStream(archive.toPath()));
+          InputStream in = 
COMPRESSOR_STREAM_FACTORY.createCompressorInputStream(bufferedIn)) {
+        expandedBytes = in.transferTo(OutputStream.nullOutputStream());
+      }
+
+      assertEquals(TarCompressionUtils.untarWithLimits(archive, UNTAR_DIR, 
expandedBytes, 1),
+          List.of(new File(UNTAR_DIR, metadata.getName())));
+      expectThrows(TarCompressionUtils.ArchiveExtractionLimitException.class,
+          () -> TarCompressionUtils.untarWithLimits(archive, UNTAR_DIR, 
expandedBytes - 1, 1));
+    }
+  }
+
   @DataProvider(name = "lz4Implementations")
   public Object[][] lz4Implementations() {
     return new Object[][]{{CompressorStreamFactory.LZ4_FRAMED}, {LZ4_FAST}, 
{LZ4_HC}};
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
index 89cca1828bd..26755c670f1 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
@@ -266,7 +266,7 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
         ControllerConf.DEFAULT_DISABLE_GROOVY);
     applyCustomConfigs(_config);
     _config.validateSegmentMetadataEntryLimits();
-    _config.validateSegmentUploadArchivePathLimits();
+    _config.validateSegmentUploadArchiveLimits();
     SegmentUploadSourcePolicy.validateConfiguredSources(_config);
     _config.setClusterIngestionGroovyDisabled(ingestionGroovyDisabled);
 
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
index 48e8e8a25cf..c49fbab6aac 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
@@ -28,9 +28,11 @@ import java.util.Optional;
 import java.util.Random;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
+import java.util.function.LongSupplier;
 import java.util.stream.Collectors;
 import javax.annotation.Nullable;
 import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.ex.ConversionException;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.helix.controller.rebalancer.strategy.AutoRebalanceStrategy;
 import org.apache.pinot.common.protocols.SegmentCompletionProtocol;
@@ -383,6 +385,26 @@ public class ControllerConf extends PinotConfiguration {
   /// Match the stored raw table name exactly, including case, even when table 
lookup is case-insensitive.
   /// Percent-encode commas in directory URI paths as %2C.
   public static final String SEGMENT_UPLOAD_ALLOWED_SOURCES = 
"controller.segment.upload.allowedSources";
+  /// Maximum bytes for both the expanded metadata TAR (including framing) and 
the total extracted file size of
+  /// each batch segment upload. Defaults to 512 MiB. Larger batches return 
HTTP 413 and must be submitted as smaller
+  /// jobs or use a higher controller limit.
+  public static final String BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES =
+      "controller.segment.upload.batch.metadata.max.expanded.bytes";
+  /// Maximum number of files and directories in each batch upload metadata 
TAR. Defaults to 100,000.
+  public static final String BATCH_SEGMENT_METADATA_MAX_ENTRIES =
+      "controller.segment.upload.batch.metadata.max.entries";
+  /// Maximum bytes for both the expanded TAR (including framing) and the 
total extracted file size of a single
+  /// metadata archive, including reingest and per-segment metadata within a 
batch. Defaults to 512 MiB.
+  public static final String SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES =
+      "controller.segment.upload.metadata.max.expanded.bytes";
+  /// Maximum number of files and directories in each single segment metadata 
TAR. Defaults to 100,000.
+  public static final String SEGMENT_UPLOAD_METADATA_MAX_ENTRIES = 
"controller.segment.upload.metadata.max.entries";
+  /// Maximum bytes for both the expanded TAR (including framing) and the 
total extracted file size of a full
+  /// segment archive in SEGMENT or URI mode. Defaults to 16 GiB. Increase it 
if valid uploads return HTTP 413.
+  public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES =
+      "controller.segment.upload.archive.max.expanded.bytes";
+  /// Maximum number of files and directories in each full segment TAR. 
Defaults to 100,000.
+  public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES = 
"controller.segment.upload.archive.max.entries";
   /// Positive maximum number of path components in a segment upload archive 
entry.
   public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH =
       "controller.segment.upload.archive.max.path.depth";
@@ -454,6 +476,12 @@ public class ControllerConf extends PinotConfiguration {
   public static final String DEFAULT_REBALANCE_PRE_CHECKER =
       
"org.apache.pinot.controller.helix.core.rebalance.DefaultRebalancePreChecker";
   public static final long DEFAULT_SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS = 
600_000L; // 10 minutes
+  public static final long DEFAULT_BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES = 
512L * 1024 * 1024;
+  public static final int DEFAULT_BATCH_SEGMENT_METADATA_MAX_ENTRIES = 100_000;
+  public static final long DEFAULT_SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES 
= 512L * 1024 * 1024;
+  public static final int DEFAULT_SEGMENT_UPLOAD_METADATA_MAX_ENTRIES = 
100_000;
+  public static final long DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES = 
16L * 1024 * 1024 * 1024;
+  public static final int DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES = 100_000;
   public static final int DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH = 32;
   public static final int DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH 
= 4_096;
   public static final long DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK = 64L 
* 1024 * 1024;
@@ -1311,6 +1339,30 @@ public class ControllerConf extends PinotConfiguration {
     return getProperty(SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS, 
DEFAULT_SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS);
   }
 
+  public long getBatchSegmentMetadataMaxExpandedBytes() {
+    return getProperty(BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES, 
DEFAULT_BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES);
+  }
+
+  public int getBatchSegmentMetadataMaxEntries() {
+    return getProperty(BATCH_SEGMENT_METADATA_MAX_ENTRIES, 
DEFAULT_BATCH_SEGMENT_METADATA_MAX_ENTRIES);
+  }
+
+  public long getSegmentUploadMetadataMaxExpandedBytes() {
+    return getProperty(SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES, 
DEFAULT_SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES);
+  }
+
+  public int getSegmentUploadMetadataMaxEntries() {
+    return getProperty(SEGMENT_UPLOAD_METADATA_MAX_ENTRIES, 
DEFAULT_SEGMENT_UPLOAD_METADATA_MAX_ENTRIES);
+  }
+
+  public long getSegmentUploadArchiveMaxExpandedBytes() {
+    return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES);
+  }
+
+  public int getSegmentUploadArchiveMaxEntries() {
+    return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES);
+  }
+
   public int getSegmentUploadArchiveMaxPathDepth() {
     return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH);
   }
@@ -1324,14 +1376,27 @@ public class ControllerConf extends PinotConfiguration {
     return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK);
   }
 
-  /// Validates the archive path limits after applying controller 
configuration overrides.
-  public void validateSegmentUploadArchivePathLimits() {
-    Preconditions.checkState(getSegmentUploadArchiveMaxPathDepth() > 0, "%s 
must be positive",
-        SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH);
-    Preconditions.checkState(getSegmentUploadArchiveMaxEntryNameLength() > 0, 
"%s must be positive",
-        SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH);
-    Preconditions.checkState(getSegmentUploadArchiveMaxPathWork() > 0, "%s 
must be positive",
-        SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK);
+  /// Validates all segment upload archive limits after applying controller 
configuration overrides.
+  public void validateSegmentUploadArchiveLimits() {
+    validateArchiveLimit(BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES, 
this::getBatchSegmentMetadataMaxExpandedBytes);
+    validateArchiveLimit(BATCH_SEGMENT_METADATA_MAX_ENTRIES, 
this::getBatchSegmentMetadataMaxEntries);
+    validateArchiveLimit(SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES, 
this::getSegmentUploadMetadataMaxExpandedBytes);
+    validateArchiveLimit(SEGMENT_UPLOAD_METADATA_MAX_ENTRIES, 
this::getSegmentUploadMetadataMaxEntries);
+    validateArchiveLimit(SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES, 
this::getSegmentUploadArchiveMaxExpandedBytes);
+    validateArchiveLimit(SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES, 
this::getSegmentUploadArchiveMaxEntries);
+    validateArchiveLimit(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH, 
this::getSegmentUploadArchiveMaxPathDepth);
+    validateArchiveLimit(SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH, 
this::getSegmentUploadArchiveMaxEntryNameLength);
+    validateArchiveLimit(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK, 
this::getSegmentUploadArchiveMaxPathWork);
+  }
+
+  private static void validateArchiveLimit(String key, LongSupplier 
configuredLimit) {
+    long limit;
+    try {
+      limit = configuredLimit.getAsLong();
+    } catch (NumberFormatException | ConversionException e) {
+      throw new IllegalStateException(key + " must be a positive integer", e);
+    }
+    Preconditions.checkState(limit > 0, "%s must be positive", key);
   }
 
   public int getMinNumCharsInISToTurnOnCompression() {
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
index 4f83874bfd6..0d33d5c08b0 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
@@ -83,8 +83,8 @@ import org.apache.pinot.common.utils.DatabaseUtils;
 import org.apache.pinot.common.utils.FileUploadDownloadClient;
 import org.apache.pinot.common.utils.FileUploadDownloadClient.FileUploadType;
 import org.apache.pinot.common.utils.TarCompressionUtils;
+import 
org.apache.pinot.common.utils.TarCompressionUtils.ArchiveExtractionLimitException;
 import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
-import 
org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathLimitException;
 import org.apache.pinot.common.utils.URIUtils;
 import org.apache.pinot.common.utils.UploadedRealtimeSegmentName;
 import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
@@ -150,6 +150,7 @@ public class PinotSegmentUploadDownloadRestletResource {
   private static final Logger LOGGER = 
LoggerFactory.getLogger(PinotSegmentUploadDownloadRestletResource.class);
   private static final String TMP_DIR_PREFIX = "tmp-";
   private static final String ENCRYPTED_SUFFIX = "_encrypted";
+  private static final String ARCHIVE_LIMIT_RESPONSE = "Upload archive exceeds 
a configured byte, entry, or path limit";
 
   @Inject
   PinotHelixResourceManager _pinotHelixResourceManager;
@@ -354,7 +355,7 @@ public class PinotSegmentUploadDownloadRestletResource {
         decryptFile(crypterClassNameInHeader, tempEncryptedFile, 
tempDecryptedFile);
       }
 
-      SegmentMetadata segmentMetadata = getSegmentMetadata(tempDecryptedFile, 
tempSegmentDir);
+      SegmentMetadata segmentMetadata = getSegmentMetadata(tempDecryptedFile, 
tempSegmentDir, uploadType);
 
       // Fetch segment name
       String segmentName = segmentMetadata.getName();
@@ -514,7 +515,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       tempSegmentDir = new File(provider.getUntarredFileTempDir(), 
tempFileName);
 
       createSegmentFileFromMultipart(multiPart, tempTarFile);
-      SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir);
+      SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir, FileUploadType.METADATA);
       String segmentName = segmentMetadata.getName();
 
       String clientAddress = 
InetAddress.getByName(request.getRemoteAddr()).getHostName();
@@ -608,7 +609,7 @@ public class PinotSegmentUploadDownloadRestletResource {
     try {
       ArchivePathBudget pathBudget = newArchivePathBudget();
       Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
-          createSegmentsMetadataInfoMap(multiPart, tempFiles, pathBudget);
+          createSegmentsMetadataInfoMap(multiPart, tempFiles, _controllerConf, 
pathBudget);
       LOGGER.info("Uploading segments in batch mode of size: {}", 
segmentsMetadataInfoMap.size());
       boolean copySegmentToFinalLocation = Boolean.parseBoolean(
           extractHttpHeader(headers, 
FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE));
@@ -646,7 +647,7 @@ public class PinotSegmentUploadDownloadRestletResource {
           decryptFile(crypterClassNameInHeader, tempEncryptedFile, 
tempDecryptedFile);
         }
 
-        SegmentMetadata segmentMetadata = 
getSegmentMetadata(tempDecryptedFile, tempSegmentDir, pathBudget);
+        SegmentMetadata segmentMetadata = 
getSegmentMetadata(tempDecryptedFile, tempSegmentDir, uploadType, pathBudget);
         String segmentMetadataTableName =
             normalizeTableName(segmentMetadata.getTableName(), tableType, 
headers, "segment metadata table name");
         validateMatchingTableName(rawTableName, segmentMetadataTableName, 
"segment metadata table name");
@@ -924,20 +925,31 @@ public class PinotSegmentUploadDownloadRestletResource {
   }
 
   @VisibleForTesting
-  SegmentMetadata getSegmentMetadata(File archive, File tempSegmentDir)
+  SegmentMetadata getSegmentMetadata(File archive, File tempSegmentDir, 
FileUploadType uploadType)
       throws Exception {
-    return getSegmentMetadata(archive, tempSegmentDir, newArchivePathBudget());
+    return getSegmentMetadata(archive, tempSegmentDir, uploadType, 
newArchivePathBudget());
   }
 
-  private static SegmentMetadata getSegmentMetadata(File archive, File 
tempSegmentDir, ArchivePathBudget pathBudget)
+  private SegmentMetadata getSegmentMetadata(File archive, File 
tempSegmentDir, FileUploadType uploadType,
+      ArchivePathBudget pathBudget)
       throws Exception {
+    boolean metadataOnly = uploadType == FileUploadType.METADATA;
+    long maxExpandedBytes = metadataOnly ? 
_controllerConf.getSegmentUploadMetadataMaxExpandedBytes()
+        : _controllerConf.getSegmentUploadArchiveMaxExpandedBytes();
+    int maxEntries = metadataOnly ? 
_controllerConf.getSegmentUploadMetadataMaxEntries()
+        : _controllerConf.getSegmentUploadArchiveMaxEntries();
     try {
-      return new DefaultMetadataExtractor().extractMetadata(archive, 
tempSegmentDir, pathBudget);
-    } catch (ArchivePathLimitException e) {
-      throw new ControllerApplicationException(LOGGER, e.getMessage(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE);
+      return new DefaultMetadataExtractor().extractMetadata(archive, 
tempSegmentDir, maxExpandedBytes, maxEntries,
+          pathBudget);
+    } catch (ArchiveExtractionLimitException e) {
+      throw archiveLimitExceeded(e);
     }
   }
 
+  private static ControllerApplicationException 
archiveLimitExceeded(ArchiveExtractionLimitException e) {
+    return new ControllerApplicationException(LOGGER, e.getMessage(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE);
+  }
+
   private void decryptFile(String crypterClassName, File tempEncryptedFile, 
File tempDecryptedFile) {
     PinotCrypter pinotCrypter = PinotCrypterFactory.create(crypterClassName);
     LOGGER.info("Using crypter class {} for decrypting {} to {}", 
pinotCrypter.getClass().getName(), tempEncryptedFile,
@@ -960,6 +972,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 410, message = "Segment to refresh does not exist"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1003,6 +1016,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 410, message = "Segment to refresh does not exist"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1044,6 +1058,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 410, message = "Segment to refresh does not exist"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1105,6 +1120,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 410, message = "Segment to refresh does not exist"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1148,6 +1164,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 410, message = "Segment to refresh does not exist"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1300,6 +1317,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       @ApiResponse(code = 403, message = "Segment validation fails"),
       @ApiResponse(code = 409, message = "Segment already exists or another 
parallel push in progress"),
       @ApiResponse(code = 412, message = "CRC check fails"),
+      @ApiResponse(code = 413, message = ARCHIVE_LIMIT_RESPONSE),
       @ApiResponse(code = 500, message = "Internal error")
   })
   @TrackInflightRequestMetrics
@@ -1375,7 +1393,7 @@ public class PinotSegmentUploadDownloadRestletResource {
 // would contain the mappings from segment names to segment download URI's.
   @VisibleForTesting
   static Map<String, SegmentMetadataInfo> 
createSegmentsMetadataInfoMap(FormDataMultiPart multiPart,
-      List<File> tempFiles, ArchivePathBudget pathBudget) {
+      List<File> tempFiles, ControllerConf controllerConf, ArchivePathBudget 
pathBudget) {
     List<BodyPart> bodyParts = multiPart.getBodyParts();
     validateMultiPartForBatchSegmentUpload(bodyParts);
     FormDataBodyPart bodyPartFromReq = (FormDataBodyPart) bodyParts.get(0);
@@ -1400,13 +1418,14 @@ public class PinotSegmentUploadDownloadRestletResource {
     tempFiles.add(allSegmentsMetadataDir);
     try {
       FileUtils.forceMkdir(allSegmentsMetadataDir);
-      List<File> metadataFiles =
-          TarCompressionUtils.untar(allSegmentsMetadataTarFile, 
allSegmentsMetadataDir, pathBudget);
+      List<File> metadataFiles = 
TarCompressionUtils.untarWithLimits(allSegmentsMetadataTarFile, 
allSegmentsMetadataDir,
+          controllerConf.getBatchSegmentMetadataMaxExpandedBytes(), 
controllerConf.getBatchSegmentMetadataMaxEntries(),
+          pathBudget);
       if (!metadataFiles.isEmpty()) {
         segmentsMetadataFiles.addAll(metadataFiles);
       }
-    } catch (ArchivePathLimitException e) {
-      throw new ControllerApplicationException(LOGGER, e.getMessage(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE);
+    } catch (ArchiveExtractionLimitException e) {
+      throw archiveLimitExceeded(e);
     } catch (IOException e) {
       throw new ControllerApplicationException(LOGGER, "Failed to unzip the 
segment metadata files. ",
           Response.Status.INTERNAL_SERVER_ERROR, e);
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerConfTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerConfTest.java
index 61e29405b78..be1ddbb72d2 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerConfTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerConfTest.java
@@ -335,6 +335,38 @@ public class ControllerConfTest {
     expectThrows(IllegalStateException.class, 
conf::validateSegmentMetadataEntryLimits);
   }
 
+  @Test
+  public void testSegmentUploadArchiveLimitDefaults() {
+    ControllerConf conf = new ControllerConf();
+    conf.validateSegmentUploadArchiveLimits();
+    Assert.assertEquals(conf.getSegmentUploadMetadataMaxExpandedBytes(), 512L 
* 1024 * 1024);
+    Assert.assertEquals(conf.getSegmentUploadMetadataMaxEntries(), 100_000);
+    Assert.assertEquals(conf.getSegmentUploadArchiveMaxExpandedBytes(), 16L * 
1024 * 1024 * 1024);
+    Assert.assertEquals(conf.getSegmentUploadArchiveMaxEntries(), 100_000);
+  }
+
+  @Test
+  public void testSegmentUploadArchiveLimitValidation() {
+    for (String key : 
List.of(ControllerConf.BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES,
+        ControllerConf.BATCH_SEGMENT_METADATA_MAX_ENTRIES, 
ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES,
+        ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_ENTRIES, 
ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES,
+        ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES, 
ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH,
+        ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH,
+        ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK)) {
+      ControllerConf conf = new ControllerConf(Map.of(key, 0));
+      IllegalStateException zero = expectThrows(IllegalStateException.class, 
conf::validateSegmentUploadArchiveLimits);
+      assertTrue(zero.getMessage().startsWith(key), zero.getMessage());
+
+      conf.setProperty(key, "invalid");
+      IllegalStateException malformed =
+          expectThrows(IllegalStateException.class, 
conf::validateSegmentUploadArchiveLimits);
+      assertTrue(malformed.getMessage().startsWith(key), 
malformed.getMessage());
+
+      conf.setProperty(key, 1);
+      conf.validateSegmentUploadArchiveLimits();
+    }
+  }
+
   @Test
   public void testSegmentUploadRejectOutOfRetentionDefault() {
     ControllerConf conf = new ControllerConf();
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
index 1c5e0068d46..0726d8bdef8 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
@@ -290,6 +290,58 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
     }
   }
 
+  @Test
+  public void testArchiveLimitsReturnHttp413()
+      throws Exception {
+    String baseUrl = getControllerBaseApiUrl();
+    HttpServer segmentServer = startSegmentServer(Map.of(SEGMENT_A, 
_segmentA), new AtomicInteger());
+    String httpSegmentUri = segmentUrl(segmentServer, SEGMENT_A);
+    String stagingSegmentUri = _segmentA.toURI().toString();
+    Response.Status limitStatus = Response.Status.REQUEST_ENTITY_TOO_LARGE;
+    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        segmentUrl(segmentServer, "") + "," + _testDir.toURI());
+    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES,
 1L);
+    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES,
 1L);
+    try (FileUploadDownloadClient client = new FileUploadDownloadClient()) {
+      URI uploadUri = URI.create(baseUrl + "/segments");
+      URI v2UploadUri = URI.create(baseUrl + "/v2/segments");
+      for (URI uri : List.of(uploadUri, v2UploadUri)) {
+        assertHttpStatus(limitStatus, () -> uploadMultipart(client, uri, 
_segmentA, TABLE_A, List.of()));
+      }
+      assertHttpStatus(Response.Status.BAD_REQUEST,
+          () -> uploadJson(client, uploadUri, httpSegmentUri, TABLE_A, 
List.of()));
+      assertHttpStatus(limitStatus, () -> uploadJson(client, v2UploadUri, 
httpSegmentUri, TABLE_A, List.of()));
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES);
+
+      List<Header> metadataHeaders = List.of(
+          new BasicHeader(FileUploadDownloadClient.CustomHeaders.UPLOAD_TYPE, 
"METADATA"),
+          new BasicHeader(FileUploadDownloadClient.CustomHeaders.DOWNLOAD_URI, 
stagingSegmentUri),
+          new 
BasicHeader(FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE, 
"true"));
+      for (String path : List.of("/v2/segments", "/segments/reingested")) {
+        assertHttpStatus(limitStatus,
+            () -> client.uploadSegmentMetadata(URI.create(baseUrl + path), 
SEGMENT_A, _segmentA, metadataHeaders,
+                uploadParameters(TABLE_A), 
HttpClient.DEFAULT_SOCKET_TIMEOUT_MS));
+      }
+
+      File batchTar = createBatchMetadataTar(_segmentA, SEGMENT_A, 
stagingSegmentUri);
+      URI batchUri = URI.create(baseUrl + "/segments/batchUpload");
+      List<Header> batchHeaders = List.of(new 
BasicHeader(FileUploadDownloadClient.CustomHeaders.UPLOAD_TYPE,
+          "METADATA"));
+      assertHttpStatus(limitStatus, () -> 
client.uploadSegmentMetadata(batchUri, batchTar.getName(), batchTar,
+          batchHeaders, uploadParameters(TABLE_A), 
HttpClient.DEFAULT_SOCKET_TIMEOUT_MS));
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES);
+      
_controllerConfig.setProperty(ControllerConf.BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES,
 1L);
+      assertHttpStatus(limitStatus, () -> 
client.uploadSegmentMetadata(batchUri, batchTar.getName(), batchTar,
+          batchHeaders, uploadParameters(TABLE_A), 
HttpClient.DEFAULT_SOCKET_TIMEOUT_MS));
+    } finally {
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES);
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES);
+      
_controllerConfig.clearProperty(ControllerConf.BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES);
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
+      segmentServer.stop(0);
+    }
+  }
+
   private void addTable(String tableName)
       throws Exception {
     Schema schema = new Schema.SchemaBuilder().setSchemaName(tableName)
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
index 16fecffa901..045b2a95d33 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
@@ -24,8 +24,11 @@ import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.lang.reflect.Method;
 import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -34,10 +37,12 @@ import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
 import java.util.stream.Collectors;
+import java.util.zip.GZIPInputStream;
 import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.Response;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.tuple.Pair;
+import org.apache.pinot.common.utils.FileUploadDownloadClient.FileUploadType;
 import org.apache.pinot.common.utils.TarCompressionUtils;
 import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
 import org.apache.pinot.controller.ControllerConf;
@@ -60,6 +65,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
 import static org.mockito.Mockito.doAnswer;
@@ -263,15 +269,77 @@ public class 
PinotSegmentUploadDownloadRestletResourceTest {
         new 
ControllerConf(Map.of(ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH, 
"2"));
 
     ControllerApplicationException failure = 
expectThrows(ControllerApplicationException.class,
-        () -> resource.getSegmentMetadata(archive, outputDir));
+        () -> resource.getSegmentMetadata(archive, outputDir, 
FileUploadType.SEGMENT));
     assertEquals(failure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
     File allowedDir = new File(outputDir, "segment/index");
     Assert.assertTrue(allowedDir.isDirectory());
     Assert.assertFalse(new File(allowedDir, "column").exists());
   }
 
-  @Test
-  public void testCreateSegmentsMetadataInfoMapRegistersTempFilesForCleanup()
+  @DataProvider
+  public Object[][] segmentArchiveLimits() {
+    return new Object[][]{
+        {FileUploadType.METADATA, 
ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES,
+            ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_ENTRIES},
+        {FileUploadType.SEGMENT, 
ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES,
+            ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES},
+        {FileUploadType.URI, 
ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES,
+            ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES}
+    };
+  }
+
+  @Test(dataProvider = "segmentArchiveLimits")
+  public void testGetSegmentMetadataUsesUploadTypeArchiveLimits(FileUploadType 
uploadType, String bytesKey,
+      String entriesKey)
+      throws Exception {
+    File segmentDir = new File(_tempDir, SEGMENT_NAME);
+    FileUtils.writeStringToFile(new File(segmentDir, "metadata.properties"),
+        "segment.name=" + SEGMENT_NAME + "\nsegment.total.docs=0\n", 
StandardCharsets.UTF_8);
+    File archive = new File(_tempDir, "segment.tar.gz");
+    TarCompressionUtils.createCompressedTarFile(segmentDir, archive);
+    long expandedBytes;
+    try (InputStream input = new 
GZIPInputStream(Files.newInputStream(archive.toPath()))) {
+      expandedBytes = input.transferTo(OutputStream.nullOutputStream());
+    }
+
+    PinotSegmentUploadDownloadRestletResource resource = new 
PinotSegmentUploadDownloadRestletResource();
+    resource._controllerConf = new ControllerConf(Map.of(
+        ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_EXPANDED_BYTES, 1,
+        ControllerConf.SEGMENT_UPLOAD_METADATA_MAX_ENTRIES, 1,
+        ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_EXPANDED_BYTES, 1,
+        ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRIES, 1));
+    resource._controllerConf.setProperty(bytesKey, expandedBytes);
+    resource._controllerConf.setProperty(entriesKey, 2);
+    assertEquals(resource.getSegmentMetadata(archive, new File(_tempDir, 
"accepted"), uploadType).getName(),
+        SEGMENT_NAME);
+
+    resource._controllerConf.setProperty(bytesKey, expandedBytes - 1);
+    ControllerApplicationException byteFailure = 
expectThrows(ControllerApplicationException.class,
+        () -> resource.getSegmentMetadata(archive, new File(_tempDir, 
"bytesRejected"), uploadType));
+    assertEquals(byteFailure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+    Assert.assertTrue(byteFailure.getMessage().contains("byte limit"), 
byteFailure.getMessage());
+
+    resource._controllerConf.setProperty(bytesKey, expandedBytes);
+    resource._controllerConf.setProperty(entriesKey, 1);
+    ControllerApplicationException entryFailure = 
expectThrows(ControllerApplicationException.class,
+        () -> resource.getSegmentMetadata(archive, new File(_tempDir, 
"entriesRejected"), uploadType));
+    assertEquals(entryFailure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+    Assert.assertTrue(entryFailure.getMessage().contains("entry limit"), 
entryFailure.getMessage());
+  }
+
+  @DataProvider
+  public Object[][] batchMetadataLimits() {
+    return new Object[][]{
+        {32_768L, 4, 2, null},
+        {32_768L, 3, 2, "entry limit"},
+        {2_048L, 4, 2, "byte limit"},
+        {32_768L, 4, 1, "path depth"}
+    };
+  }
+
+  @Test(dataProvider = "batchMetadataLimits")
+  public void 
testCreateSegmentsMetadataInfoMapRegistersTempFilesForCleanup(long maxBytes, 
int maxEntries,
+      int maxPathDepth, String rejectedLimit)
       throws IOException {
     // setup: an uber tar holding the metadata files of a single segment plus 
the download URI mapping file
     String segmentName = "mySegmentName";
@@ -292,37 +360,36 @@ public class 
PinotSegmentUploadDownloadRestletResourceTest {
 
     Set<String> tempEntriesBefore = 
listTempEntries(SegmentUploadConstants.ALL_SEGMENTS_METADATA_TAR_FILE_PREFIX,
         SegmentUploadConstants.ALL_SEGMENTS_METADATA_DIR_PREFIX);
+    ControllerConf controllerConf = new ControllerConf();
+    
controllerConf.setProperty(ControllerConf.BATCH_SEGMENT_METADATA_MAX_EXPANDED_BYTES,
 maxBytes);
+    
controllerConf.setProperty(ControllerConf.BATCH_SEGMENT_METADATA_MAX_ENTRIES, 
maxEntries);
+    ArchivePathBudget pathBudget = new ArchivePathBudget(maxPathDepth, 256, 
1024);
     List<File> tempFiles = new ArrayList<>();
 
-    // test
-    Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
-        
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
-            new ArchivePathBudget(2, 256, 1024));
-
-    // verify the map is built and its file handles are still readable, i.e. 
cleanup was deferred to the caller
-    assertEquals(segmentsMetadataInfoMap.size(), 1);
-    SegmentMetadataInfo metadataInfo = 
segmentsMetadataInfoMap.get(segmentName);
-    assertEquals(metadataInfo.getSegmentDownloadURI(), downloadURI);
-    Assert.assertTrue(metadataInfo.getSegmentCreationMetaFile().exists());
-    
Assert.assertTrue(metadataInfo.getSegmentMetadataPropertiesFile().exists());
-
-    // verify both request-scoped temp files were handed to the caller, and 
that cleaning them leaves nothing behind
-    assertEquals(tempFiles.size(), 2);
-    tempFiles.forEach(FileUtils::deleteQuietly);
-    
assertEquals(listTempEntries(SegmentUploadConstants.ALL_SEGMENTS_METADATA_TAR_FILE_PREFIX,
-        SegmentUploadConstants.ALL_SEGMENTS_METADATA_DIR_PREFIX), 
tempEntriesBefore);
-
-    // A rejected archive uses the same cleanup path and reports a 
request-size error.
-    tempFiles.clear();
-    try (InputStream retryInput = FileUtils.openInputStream(uberTarFile)) {
-      when(mockBodyPart.getValueAs(InputStream.class)).thenReturn(retryInput);
-      ControllerApplicationException failure = 
expectThrows(ControllerApplicationException.class,
-          () -> 
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
-              new ArchivePathBudget(1, 256, 1024)));
-      assertEquals(failure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+    try {
+      if (rejectedLimit == null) {
+        Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
+            
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
+                controllerConf, pathBudget);
+        assertEquals(segmentsMetadataInfoMap.size(), 1);
+        SegmentMetadataInfo metadataInfo = 
segmentsMetadataInfoMap.get(segmentName);
+        assertEquals(metadataInfo.getSegmentDownloadURI(), downloadURI);
+        Assert.assertTrue(metadataInfo.getSegmentCreationMetaFile().exists());
+        
Assert.assertTrue(metadataInfo.getSegmentMetadataPropertiesFile().exists());
+      } else {
+        ControllerApplicationException exception = 
expectThrows(ControllerApplicationException.class,
+            () -> 
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
+                controllerConf, pathBudget));
+        assertEquals(exception.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+        Assert.assertTrue(exception.getMessage().contains(rejectedLimit), 
exception.getMessage());
+      }
+      // Verify both request-scoped temp files were handed to the caller on 
success and on rejection.
+      assertEquals(tempFiles.size(), 2);
     } finally {
       tempFiles.forEach(FileUtils::deleteQuietly);
     }
+    
assertEquals(listTempEntries(SegmentUploadConstants.ALL_SEGMENTS_METADATA_TAR_FILE_PREFIX,
+        SegmentUploadConstants.ALL_SEGMENTS_METADATA_DIR_PREFIX), 
tempEntriesBefore);
   }
 
   /// Names of the entries directly under the JVM temp directory that start 
with any of the given prefixes. Used to
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
index 69addf19e99..d07b7f9a28b 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
@@ -22,6 +22,7 @@ import java.io.File;
 import java.io.IOException;
 import java.util.List;
 import javax.annotation.Nullable;
+import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.apache.commons.io.FileUtils;
 import org.apache.pinot.common.utils.TarCompressionUtils;
 import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
@@ -45,7 +46,20 @@ public class DefaultMetadataExtractor implements 
MetadataExtractor {
       @Nullable ArchivePathBudget pathBudget)
       throws Exception {
     // Unpack all files so extraction fails if the archive is corrupt.
-    List<File> untarredFiles = TarCompressionUtils.untar(tarredSegmentFile, 
unzippedSegmentDir, pathBudget);
+    return readMetadata(TarCompressionUtils.untar(tarredSegmentFile, 
unzippedSegmentDir, pathBudget),
+        unzippedSegmentDir);
+  }
+
+  /// Extracts metadata after unpacking the archive with limits on expanded 
bytes, entries, and path work.
+  public SegmentMetadata extractMetadata(File tarredSegmentFile, File 
unzippedSegmentDir, long maxExpandedBytes,
+      int maxEntries, ArchivePathBudget pathBudget)
+      throws IOException, ConfigurationException {
+    return readMetadata(TarCompressionUtils.untarWithLimits(tarredSegmentFile, 
unzippedSegmentDir, maxExpandedBytes,
+        maxEntries, pathBudget), unzippedSegmentDir);
+  }
+
+  private static SegmentMetadata readMetadata(List<File> untarredFiles, File 
unzippedSegmentDir)
+      throws IOException, ConfigurationException {
     File indexDir = untarredFiles.get(0);
     if (indexDir.isDirectory()) {
       return new SegmentMetadataImpl(indexDir);


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

Reply via email to