This is an automated email from the ASF dual-hosted git repository.
Gabriel39 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new dc5517d7afb [fix](tvf) Honor explicit compression when splitting files
(#70919)
dc5517d7afb is described below
commit dc5517d7afb706b023125f52d68135f751323bbb
Author: Gabriel <[email protected]>
AuthorDate: Mon Nov 30 18:02:29 2026 +0800
[fix](tvf) Honor explicit compression when splitting files (#70919)
### Background
File table-valued functions read external CSV, JSON and Hive Text files.
A compression property overrides the codec inferred from the file name;
the scan planner also divides splittable files into ranges for parallel
reading.
### What problem does this PR solve?
Issue Number: None
Related PR: #19530 (introduced explicit TVF compression)
PR Type: Bugfix
Problem Summary:
An explicitly compressed file without a compression suffix can be
divided into ranges, causing the BE to reject the scan with `For now we
do not support split compressed file.` Conversely, explicitly
uncompressed data named `.gz` cannot be split. This PR makes range
splitting use the same explicit compression choice as schema inference
and execution. It also keeps ranges whole when parsing needs quote,
document or multi-line prefix state. With 1-KiB splits, a two-row CSV
containing quoted embedded newlines can instead emit four rows.
### Details
- **Change map:** 52 changed lines align codec selection and format
eligibility; 443 lines cover planner matrices and SQL fixtures; 82 lines
are generated aggregate results.
- **Frequency:** Always for files above the split threshold when
codec/suffix conflicts or stateful formats are divided into byte ranges.
- **Root cause:** `FileSplitter` inferred compression from the path,
unlike schema inference and execution. Discovery also marks regular
files splittable without checking whether each range can decode
independently; fresh readers lose quote, document and prefix state.
- **Why existing tests missed it:** `FileSplitterTest` checks
suffix-based splitting and range boundaries; `TVFScanNodeTest`
previously covered coarse columnar ranges and count gates.
`test_s3_tvf_compression` and `test_hdfs_tvf_compression` use matching
suffixes and codec declarations; none forces conflicting codec choices
across multiple ranges. The original cases also omit enclosed fields,
document JSON and multi-record prefixes.
- **Fix:** Pass the TVF compression into a new splitter overload. Keep
the original overload's suffix inference and normalize the unset
envelope codec used by Parquet/ORC to that same behavior. Retain
metadata unsplittable and count pushdown gates. TVF format eligibility
independently keeps enclosed CSV, document JSON and CSV/Text prefixes of
more than one record whole, using analyzed defaults and header
precedence. Single-record prefixes and line-oriented JSON retain
splitting.
- **Other paths and branches:** The shared TVF path covers S3 and HDFS,
including CSV, JSON and Hive Text. Hive's connector has a separate
splitter. Parquet/ORC retain their existing coarse ranges because their
compression is internal. Static inspection found the same mismatch in
branch-3.1, branch-4.0, branch-4.1 and branch-4.2; no release-branch
runtime validation was performed.
### Testing
- Local FE unit tests: 86 tests passed with no failures, errors or
skips. The original codec baseline failed 12 cases; the review baseline
fails 20 new stateful-format/count-policy cases. Coverage includes
property defaults, codec/suffix combinations, header precedence and safe
splitting controls.
- Local SQL regression `test_tvf_explicit_compression_splits`: all 36 S3
variants passed full-row comparisons and normal result-file replay on an
ASAN BE. All 27 generated aggregate entries match independent row counts
and sums. The 12 codec variants compare all 4096 values; 24 additional
cases cover quotes, document JSON defaults, line arrays, prefixes and
headers, with and without a .gz suffix. The original baseline rejects
gzip without a suffix; the review baseline emits phantom rows, truncates
JSON and leaks prefixes.
### Notes for Reviewers
- Formats requiring parsing state deliberately use one range per file
until safe boundaries are available; this can reduce parallelism for
those inputs. The optional HDFS portion runs when the external test lane
enables Hive's HDFS service.
### Release note
Fix file TVF scans using an explicit compression type that differs from
the file suffix, preventing invalid compressed-file splits and allowing
explicitly uncompressed files to be split when their parsing mode
supports independent ranges.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: HDFS and Azure SQL variants
have not run locally
### AI Disclosure
- Tool: Codex (GPT-6)
- Generated: Code, unit tests, regression tests and this description
- Human review: not stated
---
.../doris/datasource/split/FileSplitter.java | 21 +-
.../doris/datasource/tvf/source/TVFScanNode.java | 31 ++-
.../datasource/tvf/source/TVFScanNodeTest.java | 214 +++++++++++++++++++
.../tvf/test_tvf_explicit_compression_splits.out | 82 ++++++++
.../test_tvf_explicit_compression_splits.groovy | 229 +++++++++++++++++++++
5 files changed, 575 insertions(+), 2 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/split/FileSplitter.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/split/FileSplitter.java
index 41bf5eaad6c..048369053f3 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/split/FileSplitter.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/split/FileSplitter.java
@@ -100,6 +100,21 @@ public class FileSplitter {
List<String> partitionValues,
SplitCreator splitCreator)
throws IOException {
+ return splitFile(path, specifiedFileSplitSize, blockLocations, length,
modificationTime,
+ splittable, TFileCompressType.UNKNOWN, partitionValues,
splitCreator);
+ }
+
+ public List<Split> splitFile(
+ LocationPath path,
+ long specifiedFileSplitSize,
+ FileBlockLocation[] blockLocations,
+ long length,
+ long modificationTime,
+ boolean splittable,
+ TFileCompressType configuredCompression,
+ List<String> partitionValues,
+ SplitCreator splitCreator)
+ throws IOException {
if (length <= 0) {
// Zero-length files contain no data; skip to avoid sending empty
splits to BE.
return Lists.newArrayList();
@@ -111,7 +126,11 @@ public class FileSplitter {
blockLocations[0] = new FileBlockLocation(null, 0L, length);
}
List<Split> result = Lists.newArrayList();
- TFileCompressType compressType =
Util.inferFileCompressTypeByPath(path.getNormalizedLocation());
+ // Match schema inference and BE ranges: explicit GZ may have no
suffix, and PLAIN may end in .gz.
+ // Parquet/ORC leave the envelope codec unset because their
compression is internal to the file.
+ TFileCompressType compressType = Util.getOrInferCompressType(
+ configuredCompression == null ? TFileCompressType.UNKNOWN :
configuredCompression,
+ path.getNormalizedLocation());
if (!splittable || compressType != TFileCompressType.PLAIN) {
if (LOG.isDebugEnabled()) {
LOG.debug("Path {} is not splittable.", path);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
index cc832c98c78..cc38a724012 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
@@ -28,6 +28,7 @@ import org.apache.doris.common.MetaNotFoundException;
import org.apache.doris.common.UserException;
import org.apache.doris.common.util.LocationPath;
import org.apache.doris.common.util.Util;
+import org.apache.doris.datasource.property.fileformat.FileFormatProperties;
import org.apache.doris.datasource.scan.FileQueryScanNode;
import org.apache.doris.datasource.scan.TableFormatType;
import org.apache.doris.datasource.split.FileSplit;
@@ -150,6 +151,7 @@ public class TVFScanNode extends FileQueryScanNode {
needSplit = FileSplitter.needSplitForCountPushdown(parallelNum,
numBackends, totalFileNum);
}
+ boolean formatSplittable = isFormatSplittable();
long targetFileSplitSize = determineTargetFileSplitSize(fileStatuses);
for (TBrokerFileStatus fileStatus : fileStatuses) {
@@ -160,7 +162,8 @@ public class TVFScanNode extends FileQueryScanNode {
null,
fileStatus.getSize(),
fileStatus.getModificationTime(),
- fileStatus.isSplitable && needSplit,
+ fileStatus.isSplitable && needSplit &&
formatSplittable,
+ tableValuedFunction.getTFileCompressType(),
null,
FileSplitCreator.DEFAULT));
} catch (IOException e) {
@@ -171,6 +174,32 @@ public class TVFScanNode extends FileQueryScanNode {
return splits;
}
+ private boolean isFormatSplittable() {
+ TFileFormatType format = tableValuedFunction.getTFileFormatType();
+ if (format == TFileFormatType.FORMAT_JSON) {
+ // Document mode parses each range as a complete JSON value,
including implicit array mode.
+ return getFileAttributes().isReadJsonByLine();
+ }
+ if (Util.isCsvFormat(format) || format == TFileFormatType.FORMAT_TEXT)
{
+ TFileAttributes attributes = getFileAttributes();
+ if (Util.isCsvFormat(format) &&
attributes.getTextParams().getEnclose() != 0) {
+ // A byte boundary may lie inside a quoted multiline field;
ranges cannot recover quote state.
+ return false;
+ }
+ int skippedLines = attributes.getSkipLines();
+ // Header modes override skip_lines in the reader.
+ if
(FileFormatProperties.FORMAT_CSV_WITH_NAMES.equalsIgnoreCase(attributes.getHeaderType()))
{
+ skippedLines = 1;
+ } else if (FileFormatProperties.FORMAT_CSV_WITH_NAMES_AND_TYPES
+ .equalsIgnoreCase(attributes.getHeaderType())) {
+ skippedLines = 2;
+ }
+ // Non-first ranges skip one partial record, but cannot consume a
remaining multi-record prefix.
+ return skippedLines <= 1;
+ }
+ return true;
+ }
+
@Override
protected TColumnCategory classifyColumn(SlotDescriptor slot, List<String>
partitionKeys) {
if (slot.getColumn().getName().startsWith(Column.GLOBAL_ROWID_COL)) {
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java
index 56db999894b..c3615ca9acd 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java
@@ -21,29 +21,226 @@ import org.apache.doris.analysis.SlotId;
import org.apache.doris.analysis.TupleDescriptor;
import org.apache.doris.analysis.TupleId;
import org.apache.doris.catalog.FunctionGenTable;
+import org.apache.doris.datasource.property.fileformat.FileFormatProperties;
import org.apache.doris.datasource.scan.FileQueryScanNode;
+import org.apache.doris.datasource.split.FileSplit;
import org.apache.doris.datasource.split.FileSplitter;
import org.apache.doris.planner.PlanNodeId;
import org.apache.doris.planner.ScanContext;
+import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.SessionVariable;
import org.apache.doris.spi.Split;
import org.apache.doris.tablefunction.ExternalFileTableValuedFunction;
import org.apache.doris.thrift.TBrokerFileStatus;
+import org.apache.doris.thrift.TFileAttributes;
+import org.apache.doris.thrift.TFileCompressType;
import org.apache.doris.thrift.TFileFormatType;
+import org.apache.doris.thrift.TFileTextScanRangeParams;
import org.apache.doris.thrift.TFileType;
import org.apache.doris.thrift.TPushAggOp;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import java.lang.reflect.Method;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
public class TVFScanNodeTest {
private static final long MB = 1024L * 1024L;
+ private ConnectContext previousContext;
+
+ @BeforeEach
+ public void setUpContext() {
+ previousContext = ConnectContext.get();
+ new ConnectContext().setThreadLocalInfo();
+ }
+
+ @AfterEach
+ public void restoreContext() {
+ ConnectContext.remove();
+ if (previousContext != null) {
+ previousContext.setThreadLocalInfo();
+ }
+ }
+
+ private static Stream<Arguments> formatCases() {
+ return Stream.of(
+ Arguments.of("csv", Map.of(), true),
+ Arguments.of("csv", Map.of("enclose", ""), true),
+ Arguments.of("csv", Map.of("enclose", "\""), false),
+ Arguments.of("csv", Map.of("enclose", "0"), false),
+ Arguments.of("csv", Map.of("skip_lines", "0"), true),
+ Arguments.of("csv", Map.of("skip_lines", "1"), true),
+ Arguments.of("csv", Map.of("skip_lines", "20"), false),
+ Arguments.of("hive_text", Map.of("skip_lines", "0"), true),
+ Arguments.of("hive_text", Map.of("skip_lines", "1"), true),
+ Arguments.of("hive_text", Map.of("skip_lines", "20"), false),
+ Arguments.of("csv_with_names", Map.of(), true),
+ Arguments.of("csv_with_names", Map.of("skip_lines", "20"),
true),
+ Arguments.of("csv_with_names_and_types", Map.of(), false),
+ Arguments.of("csv_with_names_and_types", Map.of("skip_lines",
"0"), false),
+ Arguments.of("csv_with_names_and_types", Map.of("skip_lines",
"1"), false),
+ Arguments.of("json", Map.of(), true),
+ Arguments.of("json", Map.of("read_json_by_line", "true"),
true),
+ Arguments.of("json", Map.of("read_json_by_line", "false"),
false),
+ Arguments.of("json", Map.of("strip_outer_array", "true"),
false),
+ Arguments.of("json", Map.of("strip_outer_array", "false"),
false),
+ Arguments.of("json", Map.of("read_json_by_line", "true",
"strip_outer_array", "true"), true));
+ }
+
+ @ParameterizedTest
+ @MethodSource("formatCases")
+ public void testSplitsPreserveFormatState(String format, Map<String,
String> options, boolean splittable)
+ throws Exception {
+ FileFormatProperties properties =
FileFormatProperties.createFileFormatProperties(format);
+ properties.analyzeFileFormatProperties(new HashMap<>(options), true);
+ TFileAttributes attributes = properties.toTFileAttributes();
+ for (TFileType storage : List.of(TFileType.FILE_S3,
TFileType.FILE_HDFS)) {
+ for (String suffix : List.of("", ".gz")) {
+ for (TFileCompressType compression :
List.of(TFileCompressType.PLAIN, TFileCompressType.UNKNOWN)) {
+ SessionVariable sv = new SessionVariable();
+ sv.setFileSplitSize(1024);
+ String path = (storage == TFileType.FILE_S3 ?
"s3://example-bucket/" : "hdfs://example.test/")
+ + "input" + suffix;
+ TVFScanNode node = fileScanNode(sv, storage,
properties.getFileFormatType(),
+ splittableFile(path, 4096), compression,
attributes);
+ List<Split> splits = node.getSplits(1);
+ boolean compressed = compression ==
TFileCompressType.UNKNOWN && suffix.equals(".gz");
+ int expected = splittable && !compressed ? 4 : 1;
+ Assertions.assertEquals(expected, splits.size(), format +
options + suffix + compression);
+ Assertions.assertEquals(0, splits.get(0).getStart());
+ Assertions.assertEquals(4096,
splits.stream().mapToLong(Split::getLength).sum());
+ if (expected == 1) {
+ Assertions.assertEquals(4096,
splits.get(0).getLength());
+ }
+ }
+ }
+ }
+ }
+
+ private static Stream<Arguments> statefulFormatCases() {
+ return formatCases().filter(args -> !(Boolean) args.get()[2]);
+ }
+
+ @ParameterizedTest
+ @MethodSource("statefulFormatCases")
+ public void testCountPushdownCannotEnableStatefulSplits(String format,
+ Map<String, String> options, boolean ignored) throws Exception {
+ FileFormatProperties properties =
FileFormatProperties.createFileFormatProperties(format);
+ properties.analyzeFileFormatProperties(new HashMap<>(options), true);
+ for (boolean countStar : List.of(false, true)) {
+ SessionVariable sv = new SessionVariable();
+ sv.setFileSplitSize(1024);
+ sv.parallelExecInstanceNum = 1;
+ TVFScanNode node = fileScanNode(sv, TFileType.FILE_S3,
properties.getFileFormatType(),
+ splittableFile("s3://example-bucket/input.gz", 4096),
TFileCompressType.PLAIN,
+ properties.toTFileAttributes());
+ node.setPushDownAggNoGrouping(TPushAggOp.COUNT);
+ node.setPushDownCountSlotIds(countStar ? Collections.emptyList() :
List.of(new SlotId(7)));
+ // Two backends make the independent COUNT(*) policy permit
splitting this one file.
+ Assertions.assertEquals(1, node.getSplits(2).size(), format +
options);
+ }
+ }
+
+ @Test
+ public void testStreamDoesNotInspectFileAttributesOrSplitFiles() throws
Exception {
+ TVFScanNode node = fileScanNode(new SessionVariable(),
TFileType.FILE_STREAM,
+ TFileFormatType.FORMAT_JSON, splittableFile("stream", 4096),
TFileCompressType.PLAIN, null);
+ Assertions.assertTrue(node.getSplits(1).isEmpty());
+ }
+
+ private static Stream<Arguments> compressionCases() {
+ Stream.Builder<Arguments> cases = Stream.builder();
+ for (TFileType storage : List.of(TFileType.FILE_S3,
TFileType.FILE_HDFS)) {
+ for (TFileFormatType format :
List.of(TFileFormatType.FORMAT_CSV_PLAIN,
+ TFileFormatType.FORMAT_JSON, TFileFormatType.FORMAT_TEXT))
{
+ for (String suffix : List.of("", ".gz")) {
+ for (TFileCompressType compression :
List.of(TFileCompressType.UNKNOWN,
+ TFileCompressType.PLAIN, TFileCompressType.GZ)) {
+ boolean gzip = compression == TFileCompressType.GZ
+ || (compression == TFileCompressType.UNKNOWN
&& suffix.equals(".gz"));
+ cases.add(Arguments.of(storage, format, suffix,
compression, gzip));
+ }
+ }
+ }
+ }
+ return cases.build();
+ }
+
+ @ParameterizedTest
+ @MethodSource("compressionCases")
+ public void testSplitsUseEffectiveCompression(TFileType storage,
TFileFormatType format,
+ String suffix, TFileCompressType compression, boolean gzip) throws
Exception {
+ SessionVariable sv = new SessionVariable();
+ sv.setFileSplitSize(1024);
+ String path = (storage == TFileType.FILE_S3 ? "s3://example-bucket/" :
"hdfs://example.test/")
+ + "input" + suffix;
+ TVFScanNode node = fileScanNode(sv, storage, format,
splittableFile(path, 4096), compression);
+ List<Split> splits = node.getSplits(1);
+ Assertions.assertEquals(gzip ? 1 : 4, splits.size());
+ long nextOffset = 0;
+ for (Split split : splits) {
+ Assertions.assertEquals(nextOffset, split.getStart());
+ Assertions.assertEquals(gzip ? 4096 : 1024, split.getLength());
+ Assertions.assertEquals(path, ((FileSplit) split).getPathString());
+ Assertions.assertEquals(gzip ? TFileCompressType.GZ :
TFileCompressType.PLAIN,
+ node.getFileCompressType((FileSplit) split));
+ nextOffset += split.getLength();
+ }
+ Assertions.assertEquals(4096, nextOffset);
+ }
+
+ @Test
+ public void testExplicitPlainPreservesUnsplittableAndCountStarGates()
throws Exception {
+ for (boolean countStar : List.of(false, true)) {
+ SessionVariable sv = new SessionVariable();
+ sv.setFileSplitSize(1024);
+ sv.parallelExecInstanceNum = 1;
+ TBrokerFileStatus file =
splittableFile("s3://example-bucket/input.gz", 4096);
+ file.setIsSplitable(countStar);
+ TVFScanNode node = fileScanNode(sv, TFileType.FILE_S3,
TFileFormatType.FORMAT_CSV_PLAIN,
+ file, TFileCompressType.PLAIN);
+ if (countStar) {
+ node.setPushDownAggNoGrouping(TPushAggOp.COUNT);
+ node.setPushDownCountSlotIds(Collections.emptyList());
+ }
+ List<Split> splits = node.getSplits(1);
+ Assertions.assertEquals(1, splits.size());
+ Assertions.assertEquals(0, splits.get(0).getStart());
+ Assertions.assertEquals(4096, splits.get(0).getLength());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = TFileFormatType.class, names = {"FORMAT_PARQUET",
"FORMAT_ORC"})
+ public void
testColumnarFilesWithoutEnvelopeCodecKeepCoarseSplits(TFileFormatType format)
throws Exception {
+ for (TFileType storage : List.of(TFileType.FILE_S3,
TFileType.FILE_HDFS)) {
+ SessionVariable sv = new SessionVariable();
+ sv.setFileSplitSize(16 * MB);
+ String path = storage == TFileType.FILE_S3
+ ? "s3://example-bucket/input" :
"hdfs://example.test/input";
+ TVFScanNode node = fileScanNode(sv, storage, format,
splittableFile(path, 1536 * MB), null);
+ List<Split> splits = node.getSplits(1);
+ Assertions.assertEquals(3, splits.size());
+ for (int i = 0; i < splits.size(); ++i) {
+ Assertions.assertEquals(i * 512 * MB,
splits.get(i).getStart());
+ Assertions.assertEquals(512 * MB, splits.get(i).getLength());
+ }
+ }
+ }
+
@Test
public void testCoarseRangesHonorMaxFileSplitNum() throws Exception {
for (TFileFormatType format : List.of(TFileFormatType.FORMAT_PARQUET,
TFileFormatType.FORMAT_ORC)) {
@@ -80,12 +277,28 @@ public class TVFScanNodeTest {
private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
TFileFormatType format, TBrokerFileStatus file) throws Exception {
+ return fileScanNode(sv, type, format, file, null);
+ }
+
+ private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
+ TFileFormatType format, TBrokerFileStatus file, TFileCompressType
compression) throws Exception {
+ TFileAttributes defaults = new TFileAttributes();
+ defaults.setReadJsonByLine(true);
+ defaults.setTextParams(new TFileTextScanRangeParams());
+ return fileScanNode(sv, type, format, file, compression, defaults);
+ }
+
+ private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
+ TFileFormatType format, TBrokerFileStatus file, TFileCompressType
compression,
+ TFileAttributes attributes) throws Exception {
TupleDescriptor desc = new TupleDescriptor(new TupleId(0));
FunctionGenTable table = Mockito.mock(FunctionGenTable.class);
ExternalFileTableValuedFunction tvf =
Mockito.mock(ExternalFileTableValuedFunction.class);
Mockito.when(table.getTvf()).thenReturn(tvf);
Mockito.when(tvf.getTFileType()).thenReturn(type);
Mockito.when(tvf.getTFileFormatType()).thenReturn(format);
+ Mockito.when(tvf.getTFileCompressType()).thenReturn(compression);
+ Mockito.when(tvf.getFileAttributes()).thenReturn(attributes);
Mockito.when(tvf.getFileStatuses()).thenReturn(List.of(file));
desc.setTable(table);
TVFScanNode node = new TVFScanNode(new PlanNodeId(0), desc, false, sv,
ScanContext.EMPTY);
@@ -122,6 +335,7 @@ public class TVFScanNodeTest {
ExternalFileTableValuedFunction tvf =
Mockito.mock(ExternalFileTableValuedFunction.class);
Mockito.when(table.getTvf()).thenReturn(tvf);
Mockito.when(tvf.getTFileType()).thenReturn(TFileType.FILE_LOCAL);
+
Mockito.when(tvf.getTFileCompressType()).thenReturn(TFileCompressType.UNKNOWN);
Mockito.when(tvf.getFileStatuses()).thenReturn(List.of(
splittableFile("file:///tmp/count_col_1.parquet", 128 * MB),
splittableFile("file:///tmp/count_col_2.parquet", 128 * MB)));
diff --git
a/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
b/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
new file mode 100644
index 00000000000..ff89a7134fb
--- /dev/null
+++
b/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
@@ -0,0 +1,82 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !count --
+4096 4096 8386560
+
+-- !count --
+4096 4096 8386560
+
+-- !count --
+4096 4096 8386560
+
+-- !quoted_csv_no_suffix --
+2 3
+
+-- !quoted_csv_gzip_suffix --
+2 3
+
+-- !json_array_explicit_no_suffix --
+128 8128
+
+-- !json_array_explicit_gzip_suffix --
+128 8128
+
+-- !json_array_implicit_no_suffix --
+128 8128
+
+-- !json_array_implicit_gzip_suffix --
+128 8128
+
+-- !json_document_explicit_no_suffix --
+1 7
+
+-- !json_document_explicit_gzip_suffix --
+1 7
+
+-- !json_document_implicit_no_suffix --
+1 7
+
+-- !json_document_implicit_gzip_suffix --
+1 7
+
+-- !json_line_arrays_no_suffix --
+128 8128
+
+-- !json_line_arrays_gzip_suffix --
+128 8128
+
+-- !csv_prefix_no_suffix --
+1 7
+
+-- !csv_prefix_gzip_suffix --
+1 7
+
+-- !text_prefix_no_suffix --
+1 7
+
+-- !text_prefix_gzip_suffix --
+1 7
+
+-- !csv_type_header_no_suffix --
+1 7
+
+-- !csv_type_header_gzip_suffix --
+1 7
+
+-- !csv_name_header_no_suffix --
+1 7
+
+-- !csv_name_header_gzip_suffix --
+1 7
+
+-- !csv_single_prefix_no_suffix --
+1 7
+
+-- !csv_single_prefix_gzip_suffix --
+1 7
+
+-- !text_single_prefix_no_suffix --
+1 7
+
+-- !text_single_prefix_gzip_suffix --
+1 7
+
diff --git
a/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
b/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
new file mode 100644
index 00000000000..29d83268ce3
--- /dev/null
+++
b/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
@@ -0,0 +1,229 @@
+// 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.
+
+import com.amazonaws.services.s3.model.ObjectMetadata
+import com.azure.storage.blob.BlobClientBuilder
+import com.azure.storage.common.StorageSharedKeyCredential
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.FileSystem
+import org.apache.hadoop.fs.Path
+
+import java.nio.charset.StandardCharsets
+import java.util.zip.GZIPOutputStream
+
+suite("test_tvf_explicit_compression_splits", "p0,external") {
+ String provider = getS3Provider()
+ String endpoint = getS3Endpoint()
+ boolean azure = provider.equalsIgnoreCase("AZURE")
+ if (azure) {
+ endpoint = endpoint == "azure-endpoint" ?
"https://${getS3AK()}.blob.core.windows.net" : endpoint
+ if (!endpoint.contains("://")) {
+ endpoint = "https://${endpoint}"
+ }
+ }
+ String bucket = context.config.otherConfigs.get("s3BucketName")
+ String prefix = "tvf_compression_split/${UUID.randomUUID()}/"
+ def s3Client = azure ? null : getS3Client()
+ def blob = { String key ->
+ new
BlobClientBuilder().endpoint(endpoint).containerName(bucket).blobName(key)
+ .credential(new StorageSharedKeyCredential(getS3AK(),
getS3SK())).buildClient()
+ }
+ List<String> keys = []
+ def hdfs = null
+ boolean hdfsDirectoryCreated = false
+ String hdfsUri = null
+ String hdfsUser = context.config.otherConfigs.get("hdfsUser") ?: "hadoop"
+ Path hdfsDirectory = new Path("/tmp/${prefix}")
+ Map<String, String> original = [:]
+ for (String variable : ["file_split_size", "enable_sql_cache",
"enable_query_cache"]) {
+ original[variable] = sql("SHOW VARIABLES LIKE
'${variable}'")[0][1].toString()
+ }
+ try {
+ // The external lane enables Hive's HDFS, while its standalone
enableHdfs flag is false.
+ if
(context.config.otherConfigs.get("enableHiveTest")?.toString()?.equalsIgnoreCase("true"))
{
+ hdfsUri =
"hdfs://${context.config.otherConfigs.get('externalEnvIp')}:" +
+ context.config.otherConfigs.get("hive2HdfsPort")
+ Configuration configuration = new Configuration()
+ configuration.set("fs.defaultFS", hdfsUri)
+ configuration.set("fs.hdfs.impl",
"org.apache.hadoop.hdfs.DistributedFileSystem")
+ hdfs = FileSystem.newInstance(new URI(hdfsUri), configuration,
hdfsUser)
+ assertTrue(hdfs.mkdirs(hdfsDirectory))
+ hdfsDirectoryCreated = true
+ }
+ sql "SET file_split_size = 1024"
+ sql "SET enable_sql_cache = false"
+ sql "SET enable_query_cache = false"
+ String expected = """SELECT number AS id, concat('payload_',
CAST(number AS STRING), '_汉字') AS payload
+ FROM numbers("number"="4096")"""
+ def writeFixture = { String key, byte[] bytes, String hdfsName ->
+ keys.add(key)
+ if (azure) {
+ new ByteArrayInputStream(bytes).withCloseable {
+ blob(key).upload(it, (long) bytes.length, true)
+ }
+ } else {
+ ObjectMetadata metadata = new ObjectMetadata()
+ metadata.setContentLength(bytes.length)
+ new ByteArrayInputStream(bytes).withCloseable {
s3Client.putObject(bucket, key, it, metadata) }
+ }
+ if (hdfs != null) {
+ hdfs.create(new Path(hdfsDirectory, hdfsName),
true).withCloseable { it.write(bytes) }
+ }
+ }
+ def fixtureSources = { String key, String format, String options,
String hdfsName ->
+ String source = """S3("uri"="s3://${bucket}/${key}",
"format"="${format}", ${options},
+ "provider"="${provider}", "s3.endpoint"="${endpoint}",
"s3.region"="${getS3Region()}",
+ "s3.access_key"="${getS3AK()}",
"s3.secret_key"="${getS3SK()}")"""
+ def sources = [s3: source]
+ if (hdfs != null) {
+ sources.hdfs =
"""HDFS("uri"="${hdfsUri}${hdfsDirectory}/${hdfsName}",
+ "hadoop.username"="${hdfsUser}", "format"="${format}",
${options})"""
+ }
+ return sources
+ }
+ for (String format : ["csv", "json", "hive_text"]) {
+ StringBuilder contents = new StringBuilder()
+ for (int i = 0; i < 4096; ++i) {
+ String payload = "payload_${i}_汉字"
+ contents.append(format == "json" ?
"{\"id\":${i},\"payload\":\"${payload}\"}\n"
+ : "${i},${payload}\n")
+ }
+ byte[] plain = contents.toString().getBytes(StandardCharsets.UTF_8)
+ ByteArrayOutputStream output = new ByteArrayOutputStream()
+ new GZIPOutputStream(output).withCloseable { it.write(plain) }
+ byte[] gzip = output.toByteArray()
+ // A small gzip fixture can accidentally stay below the split
threshold and miss the defect.
+ assertTrue(gzip.length > 1024)
+ def variants = [
+ [name: "gzip_no_suffix", bytes: gzip, suffix: "",
compression: "GZ"],
+ [name: "gzip_inferred", bytes: gzip, suffix: ".gz",
compression: null],
+ [name: "plain_gzip_suffix", bytes: plain, suffix: ".gz",
compression: "PLAIN"],
+ [name: "plain_inferred", bytes: plain, suffix: "",
compression: null]]
+ String canonical = null
+ for (def variant : variants) {
+ String key =
"${prefix}${format}/${variant.name}${variant.suffix}"
+ byte[] bytes = variant.bytes
+ String hdfsName = "${format}_${variant.name}${variant.suffix}"
+ writeFixture(key, bytes, hdfsName)
+ String options = format == "json" ?
'"read_json_by_line"="true"'
+ : '"column_separator"=",",
"csv_schema"="id:int;payload:string"'
+ if (variant.compression != null) {
+ options += ", \"compress_type\"=\"${variant.compression}\""
+ }
+ def sources = fixtureSources(key, format, options, hdfsName)
+ sources.each { storage, table ->
+ // Project every row, without LIMIT: COUNT(*) alone may
suppress file splitting.
+ quickTest("${storage}_${format}_${variant.name}",
+ "SELECT CAST(id AS BIGINT), payload FROM ${table}
ORDER BY 1",
+ "SELECT id, payload FROM (${expected}) expected
ORDER BY 1")
+ quickTest("${storage}_${format}_${variant.name}_counts",
+ "SELECT count(*), count(id), sum(CAST(id AS
BIGINT)) FROM ${table}",
+ "SELECT count(*), count(id), sum(id) FROM
(${expected}) expected")
+ }
+ if (variant.name == "gzip_inferred") {
+ canonical = sources.s3
+ }
+ }
+ qt_count "SELECT count(*), count(id), sum(CAST(id AS BIGINT)) FROM
${canonical}"
+ }
+
+ String csvOptions = '"column_separator"=",",
"csv_schema"="id:int;payload:string"'
+ String stringCsvOptions = '"column_separator"=",",
"csv_schema"="id:string;payload:string"'
+ String quotedPayload = "a" * 1100 + "\n1,phantom\n2,tail"
+ String skippedPrefix = (0..<20).collect { "${1000 + it}," + "p" * 58 +
"\n" }.join("")
+ String longHeader = "n" * 1300 + ",payload\n"
+ String singlePrefix = "1000," + "p" * 1400 + "\n"
+ def documentRows = (0..<128).collect { [id: it, payload:
"doc_${it}_界".toString()] }
+ String document = groovy.json.JsonOutput.toJson(documentRows)
+ String singleDocument = groovy.json.JsonOutput.toJson([id: 7, payload:
"d" * 2048])
+ String lineArrays = documentRows.collect {
groovy.json.JsonOutput.toJson([it]) + "\n" }.join("")
+ String documentExpected = """SELECT number AS id,
concat('doc_',CAST(number AS STRING),'_界') AS payload
+ FROM numbers("number"="128")"""
+ def modes = [
+ [name: "quoted_csv", format: "csv", contents:
"0,\"${quotedPayload}\"\n3,real\n",
+ options: csvOptions + ', "enclose"=\'"\'',
+ expected: """SELECT 0 AS id,
concat(repeat('a',1100),char(10),'1,phantom',char(10),'2,tail') AS payload
+ UNION ALL SELECT 3,'real'"""],
+ [name: "json_array_explicit", format: "json", contents:
document,
+ options: '"read_json_by_line"="false",
"strip_outer_array"="true"', expected: documentExpected],
+ [name: "json_array_implicit", format: "json", contents:
document,
+ options: '"strip_outer_array"="true"', expected:
documentExpected],
+ [name: "json_document_explicit", format: "json", contents:
singleDocument,
+ options: '"read_json_by_line"="false"', expected: "SELECT 7
AS id,repeat('d',2048) AS payload"],
+ [name: "json_document_implicit", format: "json", contents:
singleDocument,
+ options: '"strip_outer_array"="false"', expected: "SELECT 7
AS id,repeat('d',2048) AS payload"],
+ [name: "json_line_arrays", format: "json", contents:
lineArrays,
+ options: '"read_json_by_line"="true",
"strip_outer_array"="true"', expected: documentExpected],
+ [name: "csv_prefix", format: "csv", contents: skippedPrefix +
"7,real\n",
+ options: csvOptions + ', "skip_lines"="20"', expected:
"SELECT 7 AS id,'real' AS payload"],
+ [name: "text_prefix", format: "hive_text", contents:
skippedPrefix + "7,real\n",
+ options: csvOptions + ', "skip_lines"="20"', expected:
"SELECT 7 AS id,'real' AS payload"],
+ [name: "csv_type_header", format: "csv_with_names_and_types",
+ contents: longHeader + "string,string\n7,real\n", options:
stringCsvOptions,
+ expected: "SELECT 7 AS id,'real' AS payload"],
+ [name: "csv_name_header", format: "csv_with_names", contents:
longHeader + "7,real\n",
+ options: stringCsvOptions + ', "skip_lines"="20"', expected:
"SELECT 7 AS id,'real' AS payload"],
+ [name: "csv_single_prefix", format: "csv", contents:
singlePrefix + "7,real\n",
+ options: csvOptions + ', "skip_lines"="1"', expected: "SELECT
7 AS id,'real' AS payload"],
+ [name: "text_single_prefix", format: "hive_text", contents:
singlePrefix + "7,real\n",
+ options: csvOptions + ', "skip_lines"="1"', expected: "SELECT
7 AS id,'real' AS payload"]]
+ for (def mode : modes) {
+ for (String suffix : ["", ".gz"]) {
+ String tag = "${mode.name}_${suffix.isEmpty() ? 'no_suffix' :
'gzip_suffix'}"
+ String key = "${prefix}modes/${mode.name}${suffix}"
+ byte[] bytes = mode.contents.getBytes(StandardCharsets.UTF_8)
+ assertTrue(bytes.length > 1126, "Fixture must produce multiple
1-KiB ranges before the fix")
+ writeFixture(key, bytes, tag)
+ def sources = fixtureSources(key, mode.format, mode.options +
', "compress_type"="PLAIN"', tag)
+ sources.each { storage, table ->
+ // Full rows detect phantom quoted/preamble records;
COUNT(*) may suppress splitting.
+ quickTest("${storage}_${tag}",
+ "SELECT CAST(id AS BIGINT),payload FROM ${table}
ORDER BY 1",
+ "SELECT id,payload FROM (${mode.expected})
expected ORDER BY 1")
+ }
+ "qt_${tag}" "SELECT count(*),sum(CAST(id AS BIGINT)) FROM
${sources.s3}"
+ }
+ }
+ } finally {
+ try {
+ original.each { variable, value -> sql "SET ${variable} =
${value}" }
+ } finally {
+ try {
+ keys.each { key ->
+ if (azure) {
+ blob(key).deleteIfExists()
+ } else {
+ s3Client.deleteObject(bucket, key)
+ }
+ }
+ } finally {
+ if (s3Client != null) {
+ s3Client.shutdown()
+ }
+ if (hdfs != null) {
+ try {
+ if (hdfsDirectoryCreated) {
+ assertTrue(hdfs.delete(hdfsDirectory, true))
+ }
+ } finally {
+ hdfs.close()
+ }
+ }
+ }
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]