diff --git a/docs/generated/core_configuration.html b/docs/generated/core_configuration.html index 2578dd8560d5..d5d6d9e6f1cc 100644 --- a/docs/generated/core_configuration.html +++ b/docs/generated/core_configuration.html @@ -654,7 +654,7 @@
data-file.external-paths.strategy
none

Enum

- The strategy of selecting an external path when writing data.

Possible values: + The strategy of selecting an external path when writing data.

Possible values:
data-file.external-paths.weights
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index aa511a20e1b9..faaeeb9b7e73 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -6061,6 +6061,13 @@ public enum ExternalPathStrategy implements DescribedEnum { "entropy-inject", "When writing a new file, a path is chosen based on the hash value of the file's content."), + ENTROPY_INJECT_TEMPLATE( + "entropy-inject-template", + "Uses a single path template in data-file.external-paths containing a '{hash}' placeholder. " + + "The placeholder is replaced in place by hash directories computed from the file name. " + + "Place '{hash}' before the database and table directories to share object storage prefixes across tables. " + + "This strategy cannot be enabled or disabled on an existing table."), + WEIGHTED( "weight-robin", "When writing a new file, a path is chosen based on configured weights."); diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/EntropyInjectExternalPathProvider.java b/paimon-common/src/main/java/org/apache/paimon/fs/EntropyInjectExternalPathProvider.java index da4409979335..4cbf392f6359 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/EntropyInjectExternalPathProvider.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/EntropyInjectExternalPathProvider.java @@ -57,7 +57,7 @@ public Path getNextExternalDataPath(String fileName) { return new Path(externalTablePaths.get(position), filePathWithHashDirs); } - public String computeHash(String fileName) { + public static String computeHash(String fileName) { HashCode hashCode = HASH_FUNC.hashString(fileName, StandardCharsets.UTF_8); String hashAsBinaryString = Integer.toBinaryString(hashCode.asInt() | Integer.MIN_VALUE); String hash = @@ -71,7 +71,7 @@ public String computeHash(String fileName) { * @param hash 10011001100110011001 * @return 1001/1001/1001/10011001 with depth 3 and length 4 */ - private String dirsFromHash(String hash) { + private static String dirsFromHash(String hash) { StringBuilder hashWithDirs = new StringBuilder(); for (int i = 0; i < ENTROPY_DIR_DEPTH * ENTROPY_DIR_LENGTH; i += ENTROPY_DIR_LENGTH) { diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/ExternalPathProvider.java b/paimon-common/src/main/java/org/apache/paimon/fs/ExternalPathProvider.java index 8ad617f8a771..efcb1515a69a 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/ExternalPathProvider.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/ExternalPathProvider.java @@ -40,6 +40,9 @@ static ExternalPathProvider create( case ENTROPY_INJECT: return new EntropyInjectExternalPathProvider( externalTablePaths, relativeBucketPath); + case ENTROPY_INJECT_TEMPLATE: + return new TemplateEntropyInjectExternalPathProvider( + externalTablePaths, relativeBucketPath); case SPECIFIC_FS: // specific fs can use round-robin with only one path case ROUND_ROBIN: diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java b/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java new file mode 100644 index 000000000000..6542c2759417 --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java @@ -0,0 +1,88 @@ +/* + * 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.paimon.fs; + +import javax.annotation.concurrent.ThreadSafe; + +import java.util.List; + +import static org.apache.paimon.fs.EntropyInjectExternalPathProvider.computeHash; +import static org.apache.paimon.utils.Preconditions.checkArgument; + +/** + * Provider for external data paths which injects the hash directories into a path template. + * + *

{@link EntropyInjectExternalPathProvider} appends the hash directories after the table + * context, so the object keys of a table all share one table-specific prefix and the storage + * partitions warmed up for that prefix cannot be shared with other tables. This provider instead + * replaces the {@value #HASH_PLACEHOLDER} placeholder inside the configured template, which lets + * the hash appear before the database and table directories: + * + *

+ * template: s3://bucket-a/{hash}/my_db.db/my_table
+ * expanded: s3://bucket-a/1001/1001/1001/10011001/my_db.db/my_table
+ * file:     s3://bucket-a/1001/1001/1001/10011001/my_db.db/my_table/dt=2026-11-02/bucket-0/data-xxx.parquet
+ * 
+ * + *

Multiple databases and tables pointing at the same template root therefore share the same hash + * prefixes. + * + *

Only a single template is accepted. The placeholder is replaced in place with hash directories + * computed from the file name. No path rotation or mutable state is needed. + */ +@ThreadSafe +public class TemplateEntropyInjectExternalPathProvider implements ExternalPathProvider { + + public static final String HASH_PLACEHOLDER = "{hash}"; + + private final Path externalTablePathTemplate; + private final Path relativeBucketPath; + + public TemplateEntropyInjectExternalPathProvider( + List externalTablePathTemplates, Path relativeBucketPath) { + checkArgument( + externalTablePathTemplates.size() == 1, + "Only a single external path template is supported, but got %s.", + externalTablePathTemplates); + Path template = externalTablePathTemplates.get(0); + checkTemplate(template); + this.externalTablePathTemplate = template; + this.relativeBucketPath = relativeBucketPath; + } + + @Override + public Path getNextExternalDataPath(String fileName) { + Path externalTablePath = expand(externalTablePathTemplate, fileName); + return new Path(new Path(externalTablePath, relativeBucketPath), fileName); + } + + /** Validates that the normalized URI path contains the hash placeholder. */ + public static void checkTemplate(Path template) { + String path = template.toUri().getPath(); + checkArgument( + path != null && path.contains(HASH_PLACEHOLDER), + "External path '%s' must contain the '%s' placeholder.", + template, + HASH_PLACEHOLDER); + } + + private static Path expand(Path template, String fileName) { + return new Path(template.toString().replace(HASH_PLACEHOLDER, computeHash(fileName))); + } +} diff --git a/paimon-common/src/test/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProviderTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProviderTest.java new file mode 100644 index 000000000000..705a5b695f3e --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProviderTest.java @@ -0,0 +1,105 @@ +/* + * 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.paimon.fs; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Tests for {@link TemplateEntropyInjectExternalPathProvider}. */ +public class TemplateEntropyInjectExternalPathProviderTest { + + private static final Path RELATIVE_BUCKET_PATH = new Path("dt=2026-11-02/bucket-0"); + + @Test + public void testHashIsInjectedBeforeTableContext() { + TemplateEntropyInjectExternalPathProvider provider = + new TemplateEntropyInjectExternalPathProvider( + Collections.singletonList( + new Path("s3://bucket-a/{hash}/my_db.db/my_table")), + RELATIVE_BUCKET_PATH); + + for (int i = 0; i < 20; i++) { + String fileName = "data-" + i + ".parquet"; + String hashDirs = EntropyInjectExternalPathProvider.computeHash(fileName); + assertThat(provider.getNextExternalDataPath(fileName)) + .isEqualTo( + new Path( + "s3://bucket-a/" + + hashDirs + + "/my_db.db/my_table/dt=2026-11-02/bucket-0/" + + fileName)); + } + } + + @Test + public void testTablesShareTheSamePrefix() { + String fileName = "data-0.parquet"; + String hashDirs = EntropyInjectExternalPathProvider.computeHash(fileName); + + Path first = + new TemplateEntropyInjectExternalPathProvider( + Collections.singletonList( + new Path("s3://bucket-a/{hash}/db1.db/table1")), + new Path("bucket-0")) + .getNextExternalDataPath(fileName); + Path second = + new TemplateEntropyInjectExternalPathProvider( + Collections.singletonList( + new Path("s3://bucket-a/{hash}/db2.db/table2")), + new Path("bucket-0")) + .getNextExternalDataPath(fileName); + + String sharedPrefix = "s3://bucket-a/" + hashDirs; + assertThat(first.toString()).startsWith(sharedPrefix + "/db1.db/table1/"); + assertThat(second.toString()).startsWith(sharedPrefix + "/db2.db/table2/"); + } + + @Test + public void testMultipleTemplatesRejected() { + List templates = + Arrays.asList( + new Path("s3://bucket-a/{hash}/my_db.db/my_table"), + new Path("s3://bucket-b/{hash}/my_db.db/my_table")); + + assertThatThrownBy( + () -> + new TemplateEntropyInjectExternalPathProvider( + templates, new Path("bucket-0"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("a single external path template"); + } + + @Test + public void testTemplateWithoutPlaceholder() { + assertThatThrownBy( + () -> + new TemplateEntropyInjectExternalPathProvider( + Collections.singletonList( + new Path("s3://bucket-a/my_db.db/my_table")), + RELATIVE_BUCKET_PATH)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("{hash}"); + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/AbstractCatalog.java b/paimon-core/src/main/java/org/apache/paimon/catalog/AbstractCatalog.java index f0e3064693f2..abd7f285b84e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/AbstractCatalog.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/AbstractCatalog.java @@ -30,6 +30,7 @@ import org.apache.paimon.function.Function; import org.apache.paimon.function.FunctionChange; import org.apache.paimon.operation.Lock; +import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.options.Options; import org.apache.paimon.partition.Partition; import org.apache.paimon.partition.PartitionStatistics; @@ -38,6 +39,7 @@ import org.apache.paimon.schema.Schema; import org.apache.paimon.schema.SchemaChange; import org.apache.paimon.schema.SchemaManager; +import org.apache.paimon.schema.SchemaValidation; import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.FormatTable; @@ -71,6 +73,7 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.DATA_FILE_EXTERNAL_PATHS; +import static org.apache.paimon.CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY; import static org.apache.paimon.CoreOptions.GLOBAL_INDEX_EXTERNAL_PATH; import static org.apache.paimon.CoreOptions.PATH; import static org.apache.paimon.CoreOptions.TYPE; @@ -387,15 +390,25 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) Set externalPaths = new HashSet<>(); Path tablePath = getTableLocation(identifier); if (tableExistsInFileSystem(tablePath, DEFAULT_MAIN_BRANCH)) { - TableType tableType = CoreOptions.fromMap(loadTableSchema(identifier).options()).type(); - if (tableType == TableType.TABLE || tableType == TableType.MATERIALIZED_TABLE) { - // Cleanup only needs persisted metadata, even if runtime options are invalid. + CoreOptions options = CoreOptions.fromMap(loadTableSchema(identifier).options()); + if (options.type() == TableType.TABLE + || options.type() == TableType.MATERIALIZED_TABLE) { FileIO tableFileIO = fileIO(tablePath); SchemaManager schemaManager = new FileSystemSchemaManager(tableFileIO, tablePath); - externalPaths.addAll(getSchemaExternalPaths(schemaManager.listAll())); - for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) { - externalPaths.addAll( - getSchemaExternalPaths(schemaManager.copyWithBranch(branch).listAll())); + boolean isExternal = loadTableMetadata(identifier).isExternal(); + List branches = new ArrayList<>(); + branches.add(DEFAULT_MAIN_BRANCH); + branches.addAll(FileSystemBranchManager.branches(tableFileIO, tablePath)); + for (String branch : branches) { + SchemaManager branchSchema = schemaManager.copyWithBranch(branch); + externalPaths.addAll(getSchemaExternalPaths(branchSchema.listAll())); + Optional latest = branchSchema.latest(); + if (!isExternal + && latest.isPresent() + && TemplateFileDeletionPlan.isTemplate(latest.get())) { + TemplateFileDeletionPlan.save( + tableFileIO, tablePath, branch, latest.get(), false); + } } } } @@ -417,7 +430,9 @@ private List getSchemaExternalPaths(List schemas) { Map options = schema.toSchema().options(); return Arrays.stream( new String[] { - options.get(DATA_FILE_EXTERNAL_PATHS.key()), + TemplateFileDeletionPlan.isTemplate(schema) + ? null + : options.get(DATA_FILE_EXTERNAL_PATHS.key()), options.get(GLOBAL_INDEX_EXTERNAL_PATH.key()) }); }) @@ -450,6 +465,8 @@ public void createTable(Identifier identifier, Schema schema, boolean ignoreIfEx } catch (TableNotExistException ignored) { } + Path tablePath = getTableLocation(identifier); + TemplateFileDeletionPlan.checkCanCreateTable(fileIO(tablePath), tablePath); copyTableDefaultOptions(schema.options()); validateCreateTable(schema, false); @@ -560,6 +577,9 @@ public void replaceTable(Identifier identifier, Schema newSchema, boolean ignore + "). Drop and re-create the table instead."); } + String strategy = DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(); + SchemaValidation.validateExternalPathStrategyChange( + existing.options().get(strategy), newSchema.options().get(strategy)); replaceTableImpl(identifier, (FileStoreTable) existing, newSchema); } diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/FileSystemCatalog.java b/paimon-core/src/main/java/org/apache/paimon/catalog/FileSystemCatalog.java index 2a20e4883617..06daa0bdf6e3 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/FileSystemCatalog.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/FileSystemCatalog.java @@ -21,6 +21,7 @@ import org.apache.paimon.fs.FileIO; import org.apache.paimon.fs.Path; import org.apache.paimon.operation.Lock; +import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.options.Options; import org.apache.paimon.schema.FileSystemSchemaManager; import org.apache.paimon.schema.Schema; @@ -122,6 +123,7 @@ public TableSchema loadTableSchema(Identifier identifier) throws TableNotExistEx @Override protected void dropTableImpl(Identifier identifier, List externalPaths) { Path path = getTableLocation(identifier); + TemplateFileDeletionPlan.init(fileIO(path), path).execute(); deleteDirectory(path); // The drop cannot be retried once the table is gone, so attempt every external path. RuntimeException failure = null; diff --git a/paimon-core/src/main/java/org/apache/paimon/jdbc/JdbcCatalog.java b/paimon-core/src/main/java/org/apache/paimon/jdbc/JdbcCatalog.java index 8d94e943a3fa..364314f4f619 100644 --- a/paimon-core/src/main/java/org/apache/paimon/jdbc/JdbcCatalog.java +++ b/paimon-core/src/main/java/org/apache/paimon/jdbc/JdbcCatalog.java @@ -36,6 +36,7 @@ import org.apache.paimon.jdbc.JdbcUtils.JdbcViewConflictException; import org.apache.paimon.jdbc.JdbcUtils.JdbcViewConflictKind; import org.apache.paimon.operation.Lock; +import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.options.CatalogOptions; import org.apache.paimon.options.Options; import org.apache.paimon.schema.FileSystemSchemaManager; @@ -487,6 +488,9 @@ public void createObjectTable(Identifier identifier, Schema schema) { @Override protected void dropTableImpl(Identifier identifier, List externalPaths) { try { + Path path = getTableLocation(identifier); + TemplateFileDeletionPlan.init(fileIO, path).execute(); + int deletedRecords = execute( connections, @@ -507,7 +511,7 @@ protected void dropTableImpl(Identifier identifier, List externalPaths) { identifier.getDatabaseName(), identifier.getTableName()); } - Path path = getTableLocation(identifier); + try { if (fileIO.exists(path)) { fileIO.deleteDirectoryQuietly(path); @@ -587,6 +591,8 @@ private boolean validateTableNotExists(Identifier identifier, boolean ignoreIfEx } throw new TableAlreadyExistException(identifier); } + Path tablePath = getTableLocation(identifier); + TemplateFileDeletionPlan.checkCanCreateTable(fileIO(tablePath), tablePath); return true; } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/OrphanFilesClean.java b/paimon-core/src/main/java/org/apache/paimon/operation/OrphanFilesClean.java index 31d80bf519e8..be18ef7aaaf2 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/OrphanFilesClean.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/OrphanFilesClean.java @@ -18,6 +18,8 @@ package org.apache.paimon.operation; +import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.ExternalPathStrategy; import org.apache.paimon.Snapshot; import org.apache.paimon.blob.ManagedBlobReferenceFile; import org.apache.paimon.data.Timestamp; @@ -100,6 +102,7 @@ public abstract class OrphanFilesClean implements Serializable { protected final Path location; public OrphanFilesClean(FileStoreTable table, long olderThanMillis, boolean dryRun) { + checkExternalPathStrategySupported(table); this.table = table; this.fileIO = table.fileIO(); this.partitionKeysNum = table.partitionKeys().size(); @@ -108,6 +111,26 @@ public OrphanFilesClean(FileStoreTable table, long olderThanMillis, boolean dryR this.dryRun = dryRun; } + /** + * Candidate collection lists the partition and bucket directories under every external path. + * The {@link ExternalPathStrategy#ENTROPY_INJECT_TEMPLATE} layout puts the hash directories + * before the table context, so those directories are not reachable by such a listing and are + * shared with other tables. Cleaning is therefore refused instead of silently skipping the data + * files. + */ + private static void checkExternalPathStrategySupported(FileStoreTable table) { + ExternalPathStrategy strategy = table.store().options().externalPathStrategy(); + if (strategy == ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE) { + throw new UnsupportedOperationException( + String.format( + "Removing orphan files is not supported for table %s, " + + "because its '%s' is '%s'.", + table.fullName(), + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + strategy)); + } + } + protected List validBranches() { List branches = table.branchManager().branches(); diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java b/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java new file mode 100644 index 000000000000..8dfc52bc786b --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java @@ -0,0 +1,336 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.ExternalPathStrategy; +import org.apache.paimon.Snapshot; +import org.apache.paimon.data.BinaryString; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.format.FileFormat; +import org.apache.paimon.format.FormatReaderFactory; +import org.apache.paimon.format.FormatWriterFactory; +import org.apache.paimon.format.avro.AvroFileFormat; +import org.apache.paimon.fs.FileIO; +import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.Path; +import org.apache.paimon.index.IndexFileHandler; +import org.apache.paimon.io.RollingFileWriter; +import org.apache.paimon.io.RollingFileWriterImpl; +import org.apache.paimon.io.SingleFileWriter; +import org.apache.paimon.manifest.IndexManifestEntry; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.ManifestFile; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.ManifestList; +import org.apache.paimon.options.Options; +import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.table.CatalogEnvironment; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.FileStoreTableFactory; +import org.apache.paimon.types.DataField; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.DataFilePathFactories; +import org.apache.paimon.utils.FileUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.NoSuchFileException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; + +/** Persists exact template file paths in branch cleanup manifests under the table directory. */ +public final class TemplateFileDeletionPlan { + + private static final Logger LOG = LoggerFactory.getLogger(TemplateFileDeletionPlan.class); + private static final String CLEANUP_DIRECTORY = ".paimon-template-drops"; + private static final String BRANCH_PREFIX = "branch-"; + private static final String MANIFEST_PREFIX = "manifest-"; + private static final RowType PATH_ROW = + RowType.of(new DataField(0, "path", DataTypes.STRING())); + + private final FileIO fileIO; + private final Path tablePath; + + private TemplateFileDeletionPlan(FileIO fileIO, Path tablePath) { + this.fileIO = fileIO; + this.tablePath = tablePath; + } + + public static boolean isTemplate(TableSchema schema) { + String strategy = schema.options().get(CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key()); + return ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString().equalsIgnoreCase(strategy); + } + + /** Archives dropped branches separately so reusing a branch name preserves its old files. */ + public static void save( + FileIO fileIO, Path tablePath, String branch, TableSchema schema, boolean archive) { + if (!isTemplate(schema)) { + return; + } + Path root = cleanupPath(tablePath); + String prefix = + archive + ? BRANCH_PREFIX + : BRANCH_PREFIX + + UUID.nameUUIDFromBytes(branch.getBytes(StandardCharsets.UTF_8)) + + "-"; + try { + List previous = + archive + ? Collections.emptyList() + : FileUtils.listVersionedDirectories(fileIO, root, prefix) + .map(FileStatus::getPath) + .collect(Collectors.toList()); + writePlan( + fileIO, tablePath, branch, schema, new Path(root, prefix + UUID.randomUUID())); + for (Path path : previous) { + fileIO.delete(path, true); + } + } catch (IOException e) { + throw new UncheckedIOException("Cannot replace cleanup plan for branch " + branch, e); + } + } + + private static void writePlan( + FileIO fileIO, Path tablePath, String branch, TableSchema schema, Path plan) { + RollingFileWriter writer = + newManifestWriter(fileIO, plan, CoreOptions.fromMap(schema.options())); + boolean saved = false; + try { + FileStoreTable table = + FileStoreTableFactory.createWithoutFallbackBranch( + fileIO, + tablePath, + schema, + new Options().set(CoreOptions.BRANCH, branch), + CatalogEnvironment.empty()); + collectFiles(table, writer); + writer.close(); + saved = true; + } catch (IOException e) { + throw new UncheckedIOException("Cannot write template cleanup plan " + plan, e); + } finally { + if (!saved) { + writer.abort(); + fileIO.deleteDirectoryQuietly(plan); + } + } + } + + public static TemplateFileDeletionPlan init(FileIO fileIO, Path tablePath) { + return new TemplateFileDeletionPlan(fileIO, tablePath); + } + + public static void checkCanCreateTable(FileIO fileIO, Path tablePath) { + try { + if (fileIO.exists(cleanupPath(tablePath))) { + throw new IllegalStateException( + "Resume the saved cleanup plan for " + + tablePath + + " before recreating the table."); + } + } catch (IOException e) { + throw new UncheckedIOException("Cannot check cleanup directory for " + tablePath, e); + } + } + + /** Deletes the files recorded in each cleanup manifest, then the manifest itself. */ + public void execute() { + Path root = cleanupPath(tablePath); + try { + if (fileIO.exists(root)) { + reclaimFiles(root); + deleteIfEmpty(root); + } + } catch (IOException | RuntimeException e) { + throw new IllegalStateException( + "Template file cleanup is incomplete for " + + tablePath + + ". Resume the saved cleanup plan at the table path.", + e); + } + } + + private void deleteIfEmpty(Path directory) throws IOException { + if (fileIO.exists(directory) + && fileIO.listStatus(directory).length == 0 + && !fileIO.delete(directory, false) + && fileIO.exists(directory)) { + throw new IOException("Cannot remove empty cleanup directory " + directory); + } + } + + private void reclaimFiles(Path root) throws IOException { + FormatReaderFactory reader = + FileFormat.manifestFormat(new CoreOptions(new Options())) + .createReaderFactory(PATH_ROW, PATH_ROW, null); + ThreadPoolExecutor executor = + createCachedThreadPool( + Runtime.getRuntime().availableProcessors(), "TEMPLATE_DROP_FILES"); + boolean complete = true; + try { + for (FileStatus branch : fileIO.listDirectories(root)) { + Path plan = branch.getPath(); + if (!plan.getName().startsWith(BRANCH_PREFIX)) { + continue; + } + for (FileStatus manifest : fileIO.listStatus(plan)) { + if (!manifest.isDir() + && manifest.getPath().getName().startsWith(MANIFEST_PREFIX) + && !reclaimManifest(reader, executor, manifest)) { + complete = false; + } + } + deleteIfEmpty(plan); + } + } finally { + executor.shutdownNow(); + } + if (!complete) { + throw new IOException("Some template files could not be deleted."); + } + } + + private boolean reclaimManifest( + FormatReaderFactory reader, ThreadPoolExecutor executor, FileStatus manifest) + throws IOException { + List files = new ArrayList<>(); + try { + FileUtils.createFormatReader(fileIO, reader, manifest.getPath(), manifest.getLen()) + .forEachRemaining(row -> files.add(new Path(row.getString(0).toString()))); + } catch (IOException | RuntimeException e) { + if (AvroFileFormat.isIncompleteFile(e)) { + LOG.warn( + "Skipping incomplete cleanup manifest {}. Its files may remain after DROP.", + manifest.getPath(), + e); + return true; + } + throw new IOException("Cannot read cleanup manifest " + manifest.getPath(), e); + } + AtomicBoolean deleted = new AtomicBoolean(true); + randomlyOnlyExecute( + executor, + path -> { + if (!deleteFile(path)) { + deleted.set(false); + } + }, + files); + return deleted.get() && deleteFile(manifest.getPath()); + } + + private boolean deleteFile(Path path) { + try { + if (!fileIO.exists(path) || fileIO.delete(path, false) || !fileIO.exists(path)) { + return true; + } + LOG.warn("Cannot remove template file {}", path); + } catch (FileNotFoundException | NoSuchFileException e) { + return true; + } catch (IOException e) { + LOG.warn("Cannot remove template file {}", path, e); + } + return false; + } + + private static Path cleanupPath(Path tablePath) { + return new Path(tablePath, CLEANUP_DIRECTORY); + } + + static RollingFileWriter newManifestWriter( + FileIO fileIO, Path plan, CoreOptions options) { + FormatWriterFactory factory = + FileFormat.manifestFormat(options).createWriterFactory(PATH_ROW); + return new RollingFileWriterImpl<>( + () -> + new SingleFileWriter( + fileIO, + factory, + new Path(plan, MANIFEST_PREFIX + UUID.randomUUID() + ".avro"), + path -> GenericRow.of(BinaryString.fromString(path.toString())), + options.manifestCompression(), + false) { + @Override + public Path result() { + return path; + } + }, + options.manifestTargetSize().getBytes(), + Long.MAX_VALUE); + } + + // Include ADD and DELETE entries, even if a file is absent from the latest snapshot. + private static void collectFiles(FileStoreTable table, RollingFileWriter writer) + throws IOException { + ManifestList manifestList = table.store().manifestListFactory().create(); + Set dataManifests = new LinkedHashSet<>(); + Set indexManifests = new LinkedHashSet<>(); + Set snapshots = + new LinkedHashSet<>(table.snapshotManager().safelyGetAllSnapshots()); + snapshots.addAll(table.tagManager().taggedSnapshots()); + snapshots.addAll(table.changelogManager().safelyGetAllChangelogs()); + for (Snapshot snapshot : snapshots) { + for (ManifestFileMeta meta : manifestList.readAllManifests(snapshot)) { + dataManifests.add(meta.fileName()); + } + if (snapshot.indexManifest() != null) { + indexManifests.add(snapshot.indexManifest()); + } + } + + ManifestFile manifestFile = table.store().manifestFileFactory().create(); + DataFilePathFactories factories = new DataFilePathFactories(table.store().pathFactory()); + for (String name : dataManifests) { + for (ManifestEntry entry : manifestFile.readWithIOException(name)) { + for (Path file : + entry.file() + .collectFiles(factories.get(entry.partition(), entry.bucket()))) { + writer.write(file); + } + } + } + + IndexFileHandler indexes = table.store().newIndexFileHandler(); + for (String name : indexManifests) { + if (indexes.existsManifest(name)) { + for (IndexManifestEntry entry : indexes.readManifestWithIOException(name)) { + writer.write(indexes.filePath(entry)); + } + } + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/schema/FileSystemSchemaManager.java b/paimon-core/src/main/java/org/apache/paimon/schema/FileSystemSchemaManager.java index 8eb6ecec9bb7..85e5c62eeb31 100644 --- a/paimon-core/src/main/java/org/apache/paimon/schema/FileSystemSchemaManager.java +++ b/paimon-core/src/main/java/org/apache/paimon/schema/FileSystemSchemaManager.java @@ -277,6 +277,9 @@ public boolean mergeSchema( public boolean commit(TableSchema newSchema) throws Exception { Optional previous = latest(); if (previous.isPresent()) { + String strategy = CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(); + SchemaValidation.validateExternalPathStrategyChange( + previous.get().options().get(strategy), newSchema.options().get(strategy)); SchemaValidation.validateGeneratedColumnEvolution(previous.get(), newSchema); } SchemaValidation.validateTableSchema(newSchema); diff --git a/paimon-core/src/main/java/org/apache/paimon/schema/SchemaManagerUtils.java b/paimon-core/src/main/java/org/apache/paimon/schema/SchemaManagerUtils.java index e6021a24480c..43fdb65f7f32 100644 --- a/paimon-core/src/main/java/org/apache/paimon/schema/SchemaManagerUtils.java +++ b/paimon-core/src/main/java/org/apache/paimon/schema/SchemaManagerUtils.java @@ -74,6 +74,7 @@ import static org.apache.paimon.CoreOptions.AGG_FUNCTION; import static org.apache.paimon.CoreOptions.BUCKET_KEY; import static org.apache.paimon.CoreOptions.CLUSTERING_COLUMNS; +import static org.apache.paimon.CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY; import static org.apache.paimon.CoreOptions.DELETION_VECTORS_ENABLED; import static org.apache.paimon.CoreOptions.DELETION_VECTORS_MODIFIABLE; import static org.apache.paimon.CoreOptions.DISTINCT; @@ -468,6 +469,9 @@ protected void updateLastColumn( newSchema.primaryKeys(), newSchema.options(), newSchema.comment()); + String strategy = DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(); + SchemaValidation.validateExternalPathStrategyChange( + oldOptions.get(strategy), newTableSchema.options().get(strategy)); SchemaValidation.validateGeneratedColumnEvolution(oldTableSchema, newTableSchema); SchemaValidation.validateTableSchema(newTableSchema); return newTableSchema; @@ -1065,6 +1069,10 @@ static void checkAlterTableOption( String.format("Change '%s' is not supported yet.", key)); } + if (DATA_FILE_EXTERNAL_PATHS_STRATEGY.key().equals(key)) { + SchemaValidation.validateExternalPathStrategyChange(oldValue, newValue); + } + if (CoreOptions.DATA_EVOLUTION_NESTED_FIELD_ENABLED.key().equals(key)) { boolean oldEnabled = oldValue == null diff --git a/paimon-core/src/main/java/org/apache/paimon/schema/SchemaValidation.java b/paimon-core/src/main/java/org/apache/paimon/schema/SchemaValidation.java index 3416d66f9f56..66ceb822f0c1 100644 --- a/paimon-core/src/main/java/org/apache/paimon/schema/SchemaValidation.java +++ b/paimon-core/src/main/java/org/apache/paimon/schema/SchemaValidation.java @@ -20,6 +20,7 @@ import org.apache.paimon.CoreOptions; import org.apache.paimon.CoreOptions.ChangelogProducer; +import org.apache.paimon.CoreOptions.ExternalPathStrategy; import org.apache.paimon.CoreOptions.MapStorageLayout; import org.apache.paimon.CoreOptions.MergeEngine; import org.apache.paimon.TableType; @@ -31,6 +32,8 @@ import org.apache.paimon.fileindex.FileIndexerFactoryUtils; import org.apache.paimon.format.FileFormat; import org.apache.paimon.format.csv.CsvOptions; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.TemplateEntropyInjectExternalPathProvider; import org.apache.paimon.iceberg.IcebergOptions; import org.apache.paimon.mergetree.compact.PartialUpdateMergeFunction; import org.apache.paimon.mergetree.compact.aggregate.AggregateMergeFunction; @@ -445,6 +448,44 @@ public static void validateTableSchema(TableSchema schema, Set dynamicOp validatePkClusteringOverride(options); validateManifestSort(schema, options); + + validateExternalPathTemplate(options); + } + + public static void validateExternalPathStrategyChange( + @Nullable String previous, @Nullable String next) { + String template = ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString(); + if (template.equalsIgnoreCase(previous) != template.equalsIgnoreCase(next)) { + throw new UnsupportedOperationException( + "Switching to or from " + template + " is not supported."); + } + } + + private static void validateExternalPathTemplate(CoreOptions options) { + if (options.externalPathStrategy() != ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE) { + return; + } + + checkArgument( + !options.isChainTable(), + "Chain tables do not support the '%s' external path strategy.", + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE); + String externalPaths = options.dataFileExternalPaths(); + checkArgument( + externalPaths != null && !externalPaths.trim().isEmpty(), + "'%s' requires a non-empty template when '%s' is '%s'.", + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE); + String[] paths = externalPaths.split(",", -1); + checkArgument( + paths.length == 1, + "'%s' only accepts a single path when '%s' is '%s', but got %s.", + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE, + paths.length); + TemplateEntropyInjectExternalPathProvider.checkTemplate(new Path(paths[0].trim())); } /** diff --git a/paimon-core/src/main/java/org/apache/paimon/utils/FileSystemBranchManager.java b/paimon-core/src/main/java/org/apache/paimon/utils/FileSystemBranchManager.java index aa7b238895c5..cb9f42bb7533 100644 --- a/paimon-core/src/main/java/org/apache/paimon/utils/FileSystemBranchManager.java +++ b/paimon-core/src/main/java/org/apache/paimon/utils/FileSystemBranchManager.java @@ -27,6 +27,7 @@ import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.operation.Lock; +import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.schema.FileSystemSchemaManager; import org.apache.paimon.schema.SchemaManager; import org.apache.paimon.schema.TableSchema; @@ -48,6 +49,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; @@ -179,6 +181,10 @@ public void dropBranch(String branchName) { checkArgument( !BranchManager.isMainBranch(branchName), "The main branch cannot be deleted."); checkArgument(branchExists(branchName), "Branch name '%s' doesn't exist.", branchName); + Optional schema = schemaManager.copyWithBranch(branchName).latest(); + if (schema.isPresent() && TemplateFileDeletionPlan.isTemplate(schema.get())) { + TemplateFileDeletionPlan.save(fileIO, tablePath, branchName, schema.get(), true); + } try { // Delete branch directory fileIO.delete(branchPath(branchName), true); diff --git a/paimon-core/src/test/java/org/apache/paimon/catalog/FileSystemCatalogTest.java b/paimon-core/src/test/java/org/apache/paimon/catalog/FileSystemCatalogTest.java index 0e180938a160..8c05656e042a 100644 --- a/paimon-core/src/test/java/org/apache/paimon/catalog/FileSystemCatalogTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/catalog/FileSystemCatalogTest.java @@ -49,6 +49,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -289,6 +290,92 @@ public void testAlterTableWithInvalidOptionsOnBranch(boolean cacheEnabled) throw .isInstanceOf(IllegalArgumentException.class); } + @Test + public void testDropTableWithTemplateBranch() throws Exception { + catalog.createDatabase("template_db", false); + Identifier identifier = Identifier.create("template_db", "dropped"); + java.nio.file.Path sharedRoot = tempFile.resolve("shared-data"); + catalog.createTable( + identifier, + Schema.newBuilder() + .column("id", DataTypes.INT()) + .option(CoreOptions.BUCKET.key(), "-1") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + sharedRoot.toUri() + "/{hash}/dropped") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + "entropy-inject-template") + .build(), + false); + ((FileStoreTable) catalog.getTable(identifier)).createBranch("dev"); + Identifier branchIdentifier = new Identifier("template_db", "dropped", "dev"); + for (Identifier id : Arrays.asList(identifier, branchIdentifier)) { + FileStoreTable table = (FileStoreTable) catalog.getTable(id); + BatchWriteBuilder builder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = builder.newWrite(); + BatchTableCommit commit = builder.newCommit()) { + write.write(GenericRow.of(1)); + commit.commit(write.prepareCommit()); + } + } + try (Stream files = Files.walk(sharedRoot)) { + assertThat(files.filter(Files::isRegularFile).count()).isEqualTo(2); + } + + catalog.dropTable(identifier, false); + + try (Stream files = Files.walk(sharedRoot)) { + assertThat(files.filter(Files::isRegularFile).count()).isZero(); + } + } + + @Test + public void testDropTableWithMissingChainBranch() throws Exception { + catalog.createDatabase("chain_db", false); + Identifier identifier = Identifier.create("chain_db", "chained"); + catalog.createTable( + identifier, + Schema.newBuilder() + .column("k", DataTypes.BIGINT()) + .column("seq", DataTypes.BIGINT()) + .column("dt", DataTypes.STRING()) + .partitionKeys("dt") + .primaryKey("dt", "k") + .option(CoreOptions.BUCKET.key(), "1") + .option(CoreOptions.BUCKET_KEY.key(), "k") + .option(CoreOptions.SEQUENCE_FIELD.key(), "seq") + .option(CoreOptions.CHAIN_TABLE_ENABLED.key(), "true") + .option(CoreOptions.PARTITION_TIMESTAMP_PATTERN.key(), "$dt") + .option(CoreOptions.PARTITION_TIMESTAMP_FORMATTER.key(), "yyyyMMdd") + .option(CoreOptions.CHAIN_TABLE_CHAIN_PARTITION_KEYS.key(), "dt") + .build(), + false); + FileStoreTable table = (FileStoreTable) catalog.getTable(identifier); + table.createBranch("snapshot"); + table.createBranch("delta"); + Path tablePath = + ((FileSystemCatalog) DelegateCatalog.rootCatalog(catalog)) + .getTableLocation(identifier); + for (String branch : Arrays.asList(Identifier.DEFAULT_MAIN_BRANCH, "snapshot", "delta")) { + new FileSystemSchemaManager(fileIO, tablePath, branch) + .commitChanges( + SchemaChange.setOption( + CoreOptions.SCAN_FALLBACK_SNAPSHOT_BRANCH.key(), "snapshot"), + SchemaChange.setOption( + CoreOptions.SCAN_FALLBACK_DELTA_BRANCH.key(), "delta")); + } + // the chain loads while both branches are there + assertThat(catalog.getTable(identifier)).isNotNull(); + + table.branchManager().dropBranch("snapshot"); + + catalog.dropTable(identifier, false); + + assertThatThrownBy(() -> catalog.getTable(identifier)) + .isInstanceOf(Catalog.TableNotExistException.class); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) public void testDropTableWithInvalidOptions(boolean cacheEnabled) throws Exception { diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java new file mode 100644 index 000000000000..47e54269e709 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -0,0 +1,723 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.ExternalPathStrategy; +import org.apache.paimon.Snapshot; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.Catalog.TableNotExistException; +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.catalog.CatalogFactory; +import org.apache.paimon.catalog.FileSystemCatalog; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.catalog.TableMetadata; +import org.apache.paimon.data.BinaryString; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.SeekableInputStream; +import org.apache.paimon.fs.local.LocalFileIO; +import org.apache.paimon.io.RollingFileWriter; +import org.apache.paimon.manifest.ManifestList; +import org.apache.paimon.options.ExpireConfig; +import org.apache.paimon.options.MemorySize; +import org.apache.paimon.options.Options; +import org.apache.paimon.schema.FileSystemSchemaManager; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.schema.SchemaChange; +import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.sink.BatchTableCommit; +import org.apache.paimon.table.sink.BatchTableWrite; +import org.apache.paimon.table.sink.BatchWriteBuilder; +import org.apache.paimon.types.DataTypes; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Tests for tables using {@link ExternalPathStrategy#ENTROPY_INJECT_TEMPLATE}, whose data files + * live in external paths shared with other tables. + */ +public class EntropyInjectTemplateTest { + + private static final String DATABASE = "shared_db"; + + @TempDir java.nio.file.Path tempPath; + + private Catalog catalog; + private java.nio.file.Path sharedRoot; + + @BeforeEach + public void before() throws Exception { + catalog = + CatalogFactory.createCatalog( + CatalogContext.create(new Path("file://" + tempPath + "/warehouse"))); + catalog.createDatabase(DATABASE, true); + sharedRoot = tempPath.resolve("shared"); + } + + @Test + public void testTablesShareHashPrefixes() throws Exception { + FileStoreTable t1 = createTable("t1"); + FileStoreTable t2 = createTable("t2"); + write(t1, 1, "a"); + write(t2, 2, "b"); + + // every data file is laid out as /.db//bucket-0/ + for (String file : listSharedFiles()) { + assertThat(file) + .matches( + "[01]{4}/[01]{4}/[01]{4}/[01]{8}/" + + DATABASE + + "\\.db/t[12]/bucket-0/.+"); + } + assertThat(sharedTableFiles("t1")).hasSize(1); + assertThat(sharedTableFiles("t2")).hasSize(1); + } + + @Test + public void testExpireSnapshotsDeletesSharedFiles() throws Exception { + FileStoreTable table = createTable("t1"); + write(table, 1, "a"); + write(table, 2, "b"); + write(table, 3, "c"); + assertThat(sharedTableFiles("t1")).hasSize(3); + + // the overwrite makes the three files unreferenced by the latest snapshot + overwrite(table, 4, "d"); + assertThat(sharedTableFiles("t1")).hasSize(4); + + table.newExpireSnapshots() + .config(ExpireConfig.builder().snapshotRetainMax(1).snapshotRetainMin(1).build()) + .expire(); + + // expiration locates the files by their full external path, the overwritten ones are gone + assertThat(sharedTableFiles("t1")).hasSize(1); + } + + @Test + public void testDropTableOnlyDeletesItsOwnFiles() throws Exception { + FileStoreTable t1 = createTable("t1"); + FileStoreTable t2 = createTable("t2"); + write(t1, 1, "a"); + write(t1, 2, "b"); + write(t2, 3, "c"); + Set t2Files = sharedTableFiles("t2"); + assertThat(sharedTableFiles("t1")).hasSize(2); + assertThat(t2Files).hasSize(1); + + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + + assertThat(sharedTableFiles("t1")).isEmpty(); + // the shared hash directories and the files of the other table are untouched + assertThat(sharedTableFiles("t2")).isEqualTo(t2Files); + } + + /** + * Deletion walks one manifest at a time, and a file overwritten by a later snapshot is recorded + * as an {@code ADD} entry in one manifest and as a {@code DELETE} entry in another. Both kinds + * have to be followed, and following the same file twice has to stay harmless. + */ + @Test + public void testDropTableAcrossManyManifests() throws Exception { + FileStoreTable t1 = createTable("t1"); + FileStoreTable t2 = createTable("t2"); + write(t2, 0, "keep"); + Set t2Files = sharedTableFiles("t2"); + + for (int i = 1; i <= 6; i++) { + write(t1, i, "v" + i); + } + overwrite(t1, 7, "v7"); + for (int i = 8; i <= 10; i++) { + write(t1, i, "v" + i); + } + assertThat(sharedTableFiles("t1")).hasSize(10); + assertThat(manifestCount(t1)).isGreaterThan(1); + + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + + assertThat(sharedTableFiles("t1")).isEmpty(); + assertThat(sharedTableFiles("t2")).isEqualTo(t2Files); + } + + /** The number of distinct manifests the deletion walks over. */ + private int manifestCount(FileStoreTable t) throws Exception { + ManifestList manifestList = t.store().manifestListFactory().create(); + Set names = new HashSet<>(); + for (Snapshot snapshot : t.snapshotManager().safelyGetAllSnapshots()) { + manifestList.readAllManifests(snapshot).forEach(meta -> names.add(meta.fileName())); + } + return names.size(); + } + + /** The literal template path is excluded from recursive directory cleanup. */ + @Test + public void testDropTablePreservesTheLiteralPlaceholderDirectory() throws Exception { + FileStoreTable t1 = createTable("t1"); + FileStoreTable t2 = createTable("t2"); + write(t1, 1, "a"); + write(t2, 2, "b"); + Set t2Files = sharedTableFiles("t2"); + + java.nio.file.Path literal = + sharedRoot.resolve("{hash}").resolve(DATABASE + ".db").resolve("t1"); + Files.createDirectories(literal); + Files.write(literal.resolve("legacy.parquet"), new byte[] {1}); + + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + + assertThat(sharedTableFiles("t1")) + .containsExactly( + sharedRoot.relativize(literal.resolve("legacy.parquet")).toString()); + assertThat(sharedTableFiles("t2")).isEqualTo(t2Files); + } + + /** + * An external table keeps its data, the way {@code HiveCatalog} leaves the directories of one + * alone. Dropping then leaves the files behind, and because they sit under prefixes shared with + * other tables they can no longer be told apart by path alone. + */ + @Test + public void testDropTableKeepsTheFilesOfAnExternalTable() throws Exception { + java.nio.file.Path warehouse = tempPath.resolve("external-warehouse"); + try (Catalog external = + new FileSystemCatalog(LocalFileIO.create(), new Path("file://" + warehouse)) { + @Override + protected TableMetadata loadTableMetadata(Identifier identifier) + throws TableNotExistException { + return new TableMetadata(loadTableSchema(identifier), true, null); + } + }) { + external.createDatabase(DATABASE, true); + Identifier id = Identifier.create(DATABASE, "kept"); + external.createTable(id, sharedSchema("kept"), false); + FileStoreTable t = (FileStoreTable) external.getTable(id); + write(t, 1, "a"); + Set files = sharedTableFiles("kept"); + assertThat(files).hasSize(1); + + external.dropTable(id, false); + + assertThat(sharedTableFiles("kept")).isEqualTo(files); + } + } + + @Test + public void testExecuteWithoutCleanupDirectoryPreservesTable() throws Exception { + FileStoreTable table = createTable("kept"); + write(table, 1, "a"); + Set files = sharedTableFiles("kept"); + TemplateFileDeletionPlan.init(table.fileIO(), table.location()).execute(); + assertThat(catalog.getTable(Identifier.create(DATABASE, "kept"))) + .isInstanceOf(FileStoreTable.class); + assertThat(sharedTableFiles("kept")).hasSize(1).isEqualTo(files); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testCannotSwitchTemplateStrategy(boolean withData) throws Exception { + String strategy = CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(); + String paths = CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(); + String template = ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString(); + String roundRobin = ExternalPathStrategy.ROUND_ROBIN.toString(); + String templatePath = "file://" + sharedRoot + "/{hash}/template"; + String normalPath = "file://" + tempPath.resolve("normal"); + Identifier templateId = Identifier.create(DATABASE, "template"); + Identifier normalId = Identifier.create(DATABASE, "normal"); + catalog.createTable(templateId, sharedSchema("template"), false); + Schema normalSchema = + schemaBuilder().option(paths, normalPath).option(strategy, roundRobin).build(); + catalog.createTable(normalId, normalSchema, false); + FileStoreTable templateTable = (FileStoreTable) catalog.getTable(templateId); + FileStoreTable normalTable = (FileStoreTable) catalog.getTable(normalId); + if (withData) { + write(templateTable, 1, "template"); + write(normalTable, 2, "normal"); + } + + assertThatThrownBy( + () -> + catalog.alterTable( + normalId, + Arrays.asList( + SchemaChange.setOption(paths, templatePath), + SchemaChange.setOption(strategy, template)), + false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + assertThatThrownBy( + () -> + catalog.alterTable( + templateId, + Arrays.asList( + SchemaChange.setOption(paths, normalPath), + SchemaChange.setOption(strategy, roundRobin)), + false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + assertThatThrownBy( + () -> + catalog.alterTable( + templateId, + Collections.singletonList( + SchemaChange.removeOption(strategy)), + false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + assertThatThrownBy(() -> normalTable.copy(Collections.singletonMap(strategy, template))) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + assertThatThrownBy(() -> templateTable.copy(Collections.singletonMap(strategy, roundRobin))) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + + assertThatThrownBy(() -> catalog.replaceTable(templateId, normalSchema, false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + assertThatThrownBy(() -> catalog.replaceTable(normalId, sharedSchema("normal"), false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(template); + if (withData) { + assertThat( + ((FileStoreTable) catalog.getTable(templateId)) + .snapshotManager() + .latestSnapshotId()) + .isEqualTo(1L); + assertThat( + ((FileStoreTable) catalog.getTable(normalId)) + .snapshotManager() + .latestSnapshotId()) + .isEqualTo(1L); + } + } + + @Test + public void testDropTableReclaimsFilesFromDroppedBranch() throws Exception { + FileStoreTable table = createTable("t1"); + write(table, 1, "main"); + table.createTag("fork"); + table.createBranch("dev", "fork"); + write(table.switchToBranch("dev"), 2, "dev"); + Set files = sharedTableFiles("t1"); + assertThat(files).hasSize(2); + + table.branchManager().dropBranch("dev"); + + assertThat(table.branchManager().branches()).doesNotContain("dev"); + assertThat(sharedTableFiles("t1")).isEqualTo(files); + table.createBranch("dev", "fork"); + write(table.switchToBranch("dev"), 3, "new dev"); + table.branchManager().dropBranch("dev"); + assertThat(sharedTableFiles("t1")).hasSize(3); + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + assertThat(sharedTableFiles("t1")).isEmpty(); + } + + @Test + public void testDropSkipsTruncatedCleanupManifest() throws Exception { + FileStoreTable table = createTable("truncated"); + write(table, 1, "main"); + java.nio.file.Path plan = + java.nio.file.Paths.get(table.location().toUri()) + .resolve(".paimon-template-drops/branch-interrupted"); + Files.createDirectories(plan); + Files.write(plan.resolve("manifest-incomplete.avro"), new byte[] {'O', 'b', 'j', 1}); + assertThat(sharedTableFiles("truncated")).hasSize(1); + + LocalFileIO unavailable = + new LocalFileIO() { + @Override + public SeekableInputStream newInputStream(Path path) throws IOException { + throw new IOException("storage unavailable"); + } + }; + assertThatThrownBy( + () -> + TemplateFileDeletionPlan.init(unavailable, table.location()) + .execute()) + .hasRootCauseMessage("storage unavailable"); + assertThat(sharedTableFiles("truncated")).hasSize(1); + + catalog.dropTable(Identifier.create(DATABASE, "truncated"), false); + + assertThat(sharedTableFiles("truncated")).isEmpty(); + assertThat(table.fileIO().exists(table.location())).isFalse(); + } + + @Test + public void testDropPlanRollsAtManifestTargetSize() throws Exception { + FileStoreTable table = createTable("batched"); + CoreOptions options = + new CoreOptions( + new Options() + .set(CoreOptions.MANIFEST_TARGET_FILE_SIZE, MemorySize.ofBytes(1))); + RollingFileWriter plan = + TemplateFileDeletionPlan.newManifestWriter( + table.fileIO(), + new Path(table.location(), ".paimon-template-drops/branch-batched"), + options); + for (int i = 0; i < 20_000; i++) { + plan.write(new Path("file://" + sharedRoot.resolve("file-" + i))); + } + plan.close(); + try (Stream files = + Files.walk(java.nio.file.Paths.get(table.location().toUri()))) { + assertThat( + files.filter(path -> path.getFileName().toString().endsWith(".avro")) + .count()) + .isGreaterThan(1); + } + catalog.dropTable(Identifier.create(DATABASE, "batched"), false); + assertThat(table.fileIO().exists(table.location())).isFalse(); + } + + @Test + public void testEmptyCleanupDirectoryBlocksCreateUntilCleaned() throws Exception { + Path path = new Path(tempPath.toUri()); + LocalFileIO io = LocalFileIO.create(); + io.mkdirs(new Path(path, ".paimon-template-drops")); + assertThatThrownBy(() -> TemplateFileDeletionPlan.checkCanCreateTable(io, path)) + .hasMessageContaining("before recreating the table"); + TemplateFileDeletionPlan.init(io, path).execute(); + TemplateFileDeletionPlan.checkCanCreateTable(io, path); + } + + @Test + public void testResumeFailedTemplateDeletionFromTablePath() throws Exception { + Path warehouse = new Path("file://" + tempPath.resolve("retry-warehouse")); + LocalFileIO failingFileIO = + new LocalFileIO() { + @Override + public boolean delete(Path path, boolean recursive) throws IOException { + if (path.getName().equals("already-deleted")) { + throw new AssertionError( + "Missing file should be skipped before delete"); + } + if (!recursive + && path.toUri().getPath().startsWith(sharedRoot.toString() + "/")) { + throw new IOException("transient data deletion failure"); + } + return super.delete(path, recursive); + } + }; + Identifier identifier = Identifier.create(DATABASE, "retry"); + Path tablePath = new Path(warehouse, DATABASE + ".db/retry"); + try (Catalog retrying = new FileSystemCatalog(failingFileIO, warehouse)) { + retrying.createDatabase(DATABASE, true); + retrying.createTable(identifier, sharedSchema("retry"), false); + FileStoreTable table = (FileStoreTable) retrying.getTable(identifier); + write(table, 1, "a"); + + // A plan from an earlier branch drop can be reclaimed independently. + RollingFileWriter branchPlan = + TemplateFileDeletionPlan.newManifestWriter( + failingFileIO, + new Path(table.location(), ".paimon-template-drops/branch-archived"), + table.coreOptions()); + branchPlan.write(new Path(warehouse, "already-deleted")); + branchPlan.close(); + + assertThatThrownBy(() -> retrying.dropTable(identifier, false)) + .hasMessageContaining("file cleanup is incomplete") + .hasMessageContaining("saved cleanup plan"); + + assertThat(retrying.listTables(DATABASE)).contains("retry"); + assertThat(failingFileIO.exists(table.location())).isTrue(); + assertThat(failingFileIO.exists(new Path(warehouse, ".paimon-template-drops"))) + .isFalse(); + assertThat(sharedTableFiles("retry")).hasSize(1); + try (Stream files = + Files.walk( + java.nio.file.Paths.get(tablePath.toUri()) + .resolve(".paimon-template-drops"))) { + assertThat( + files.filter( + path -> + path.getFileName() + .toString() + .endsWith(".avro")) + .count()) + .isEqualTo(1); + } + + assertThatThrownBy( + () -> TemplateFileDeletionPlan.init(failingFileIO, tablePath).execute()) + .hasMessageContaining("file cleanup is incomplete"); + } + + TemplateFileDeletionPlan saved = + TemplateFileDeletionPlan.init(LocalFileIO.create(), tablePath); + saved.execute(); + assertThat(LocalFileIO.create().exists(new Path(tablePath, "schema"))).isTrue(); + TemplateFileDeletionPlan.checkCanCreateTable(LocalFileIO.create(), tablePath); + assertThat(sharedTableFiles("retry")).isEmpty(); + try (Stream files = + Files.walk(java.nio.file.Paths.get(warehouse.toUri()))) { + assertThat(files.noneMatch(path -> path.getFileName().toString().endsWith(".avro"))) + .isTrue(); + } + } + + @Test + public void testRemoveOrphanFilesIsNotSupported() throws Exception { + FileStoreTable table = createTable("t1"); + write(table, 1, "a"); + + assertThatThrownBy(() -> new LocalOrphanFilesClean(table)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining(CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key()); + } + + @ParameterizedTest + @ValueSource(strings = {"/bad", "/{hash}/.."}) + public void testExternalPathMustContainPlaceholder(String suffix) { + assertThatThrownBy( + () -> + catalog.createTable( + Identifier.create(DATABASE, "bad"), + schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + sharedRoot + suffix) + .option( + CoreOptions + .DATA_FILE_EXTERNAL_PATHS_STRATEGY + .key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE + .toString()) + .build(), + false)) + .rootCause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("{hash}"); + } + + @Test + public void testRoundRobinAcceptsLiteralPlaceholderDirectory() throws Exception { + Identifier identifier = Identifier.create(DATABASE, "literal"); + catalog.createTable( + identifier, + schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + sharedRoot + "/{hash}/literal") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ROUND_ROBIN.toString()) + .build(), + false); + FileStoreTable table = (FileStoreTable) catalog.getTable(identifier); + write(table, 1, "a"); + + assertThat(table.newReadBuilder().newScan().plan().splits()).isNotEmpty(); + assertThat(Files.isDirectory(sharedRoot.resolve("{hash}").resolve("literal"))).isTrue(); + } + + @Test + public void testRejectsChainTableWithTemplateStrategy() throws Exception { + Identifier identifier = Identifier.create(DATABASE, "chain_template"); + String chainEnabled = CoreOptions.CHAIN_TABLE_ENABLED.key(); + Schema schema = + schemaBuilder() + .partitionKeys("name") + .primaryKey("name", "id") + .option(CoreOptions.BUCKET.key(), "1") + .option(CoreOptions.SEQUENCE_FIELD.key(), "id") + .option(CoreOptions.PARTITION_TIMESTAMP_PATTERN.key(), "$name") + .option(CoreOptions.PARTITION_TIMESTAMP_FORMATTER.key(), "yyyy-MM-dd") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + + sharedRoot + + "/{hash}/" + + DATABASE + + ".db/chain_template") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString()) + .option(chainEnabled, "true") + .build(); + String message = "Chain tables do not support the 'entropy-inject-template'"; + assertThatThrownBy(() -> catalog.createTable(identifier, schema, false)) + .rootCause() + .hasMessageContaining(message); + + schema.options().remove(chainEnabled); + catalog.createTable(identifier, schema, false); + FileStoreTable table = (FileStoreTable) catalog.getTable(identifier); + write(table, 1, "2026-11-19"); + assertThat(sharedTableFiles("chain_template")).hasSize(1); + assertThatThrownBy( + () -> + catalog.alterTable( + identifier, + Collections.singletonList( + SchemaChange.setOption(chainEnabled, "true")), + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + + // Simulate an existing table whose schema was persisted before validation. + schema.options().put(chainEnabled, "true"); + long legacySchemaId = table.schema().id() + 1; + FileSystemSchemaManager schemaManager = + new FileSystemSchemaManager(table.fileIO(), table.location()); + assertThat( + table.fileIO() + .tryToWriteAtomic( + schemaManager.toSchemaPath(legacySchemaId), + TableSchema.create(legacySchemaId, schema).toString())) + .isTrue(); + + assertThatThrownBy(() -> catalog.dropTable(identifier, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + assertThat(sharedTableFiles("chain_template")).hasSize(1); + } + + @Test + public void testTemplateRequiresAnExternalPathOnCreateAndAlter() throws Exception { + String strategy = CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(); + String template = ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString(); + Identifier identifier = Identifier.create(DATABASE, "missing_path"); + assertThatThrownBy( + () -> + catalog.createTable( + identifier, + schemaBuilder().option(strategy, template).build(), + false)) + .rootCause() + .hasMessageContaining("requires a non-empty template"); + catalog.createTable(identifier, sharedSchema("missing_path"), false); + assertThatThrownBy( + () -> + catalog.alterTable( + identifier, + Collections.singletonList( + SchemaChange.removeOption( + CoreOptions.DATA_FILE_EXTERNAL_PATHS + .key())), + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires a non-empty template"); + } + + @Test + public void testOnlyOneTemplateIsAllowed() { + assertThatThrownBy( + () -> + catalog.createTable( + Identifier.create(DATABASE, "bad"), + schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + + sharedRoot + + "/a/{hash}/bad,file://" + + sharedRoot + + "/b/{hash}/bad") + .option( + CoreOptions + .DATA_FILE_EXTERNAL_PATHS_STRATEGY + .key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE + .toString()) + .build(), + false)) + .rootCause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("only accepts a single path"); + } + + private Schema.Builder schemaBuilder() { + return Schema.newBuilder() + .column("id", DataTypes.INT()) + .column("name", DataTypes.STRING()) + .option(CoreOptions.BUCKET.key(), "-1"); + } + + private Schema sharedSchema(String tableName) { + return schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + sharedRoot + "/{hash}/" + DATABASE + ".db/" + tableName) + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString()) + .build(); + } + + private FileStoreTable createTable(String tableName) throws Exception { + Identifier identifier = Identifier.create(DATABASE, tableName); + catalog.createTable(identifier, sharedSchema(tableName), false); + return (FileStoreTable) catalog.getTable(identifier); + } + + private void write(FileStoreTable table, int id, String name) throws Exception { + write(table.newBatchWriteBuilder(), id, name); + } + + private void overwrite(FileStoreTable table, int id, String name) throws Exception { + write(table.newBatchWriteBuilder().withOverwrite(), id, name); + } + + private void write(BatchWriteBuilder builder, int id, String name) throws Exception { + try (BatchTableWrite write = builder.newWrite(); + BatchTableCommit commit = builder.newCommit()) { + write.write(GenericRow.of(id, BinaryString.fromString(name))); + commit.commit(write.prepareCommit()); + } + } + + /** All data file paths under the shared root, relative to it. */ + private Set listSharedFiles() throws IOException { + if (!Files.exists(sharedRoot)) { + return Collections.emptySet(); + } + try (Stream files = Files.walk(sharedRoot)) { + return files.filter(Files::isRegularFile) + .map(sharedRoot::relativize) + .map(java.nio.file.Path::toString) + .collect(Collectors.toSet()); + } + } + + private Set sharedTableFiles(String tableName) throws IOException { + return listSharedFiles().stream() + .filter(file -> file.contains("/" + DATABASE + ".db/" + tableName + "/")) + .collect(Collectors.toSet()); + } +} diff --git a/paimon-format/src/main/java/org/apache/paimon/format/avro/AvroFileFormat.java b/paimon-format/src/main/java/org/apache/paimon/format/avro/AvroFileFormat.java index aa03f1f8628e..9be386321eca 100644 --- a/paimon-format/src/main/java/org/apache/paimon/format/avro/AvroFileFormat.java +++ b/paimon-format/src/main/java/org/apache/paimon/format/avro/AvroFileFormat.java @@ -36,7 +36,9 @@ import org.apache.paimon.statistics.SimpleColStatsCollector; import org.apache.paimon.types.DataType; import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.ExceptionUtils; +import org.apache.avro.InvalidAvroMagicException; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileWriter; @@ -44,6 +46,7 @@ import javax.annotation.Nullable; +import java.io.EOFException; import java.io.IOException; import java.util.HashMap; import java.util.List; @@ -83,6 +86,12 @@ public AvroFileFormat(FormatContext context) { this.blockSize = context.blockSize(); } + /** Whether a reader found an incomplete Avro file or an invalid file header. */ + public static boolean isIncompleteFile(Throwable error) { + return ExceptionUtils.findThrowable(error, EOFException.class).isPresent() + || ExceptionUtils.findThrowable(error, InvalidAvroMagicException.class).isPresent(); + } + @Override public FormatReaderFactory createReaderFactory( RowType dataSchemaRowType, diff --git a/paimon-hive/paimon-hive-catalog/src/main/java/org/apache/paimon/hive/HiveCatalog.java b/paimon-hive/paimon-hive-catalog/src/main/java/org/apache/paimon/hive/HiveCatalog.java index e2ca397882fd..351b39264a48 100644 --- a/paimon-hive/paimon-hive-catalog/src/main/java/org/apache/paimon/hive/HiveCatalog.java +++ b/paimon-hive/paimon-hive-catalog/src/main/java/org/apache/paimon/hive/HiveCatalog.java @@ -37,6 +37,7 @@ import org.apache.paimon.hive.pool.CachedClientPool; import org.apache.paimon.operation.FileStoreScan; import org.apache.paimon.operation.Lock; +import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.options.CatalogOptions; import org.apache.paimon.options.Options; import org.apache.paimon.options.OptionsUtils; @@ -1267,8 +1268,12 @@ private boolean usingExternalTable(Map tableOptions) { @Override protected void dropTableImpl(Identifier identifier, List externalPaths) { + Path path = getTableLocation(identifier); try { boolean externalTable = isExternalTable(getHmsTable(identifier)); + if (!externalTable) { + TemplateFileDeletionPlan.init(fileIO, path).execute(); + } clients() .execute( client -> @@ -1288,7 +1293,6 @@ protected void dropTableImpl(Identifier identifier, List externalPaths) { // Deletes table directory to avoid schema in filesystem exists after dropping hive // table successfully to keep the table consistency between which in filesystem and // which in Hive metastore. - Path path = getTableLocation(identifier); try { FileIO fileIO = fileIO(path); if (fileIO.exists(path)) { diff --git a/paimon-hive/paimon-hive-catalog/src/test/java/org/apache/paimon/hive/HiveCatalogTest.java b/paimon-hive/paimon-hive-catalog/src/test/java/org/apache/paimon/hive/HiveCatalogTest.java index ea8043171aba..f6fde9a89c74 100644 --- a/paimon-hive/paimon-hive-catalog/src/test/java/org/apache/paimon/hive/HiveCatalogTest.java +++ b/paimon-hive/paimon-hive-catalog/src/test/java/org/apache/paimon/hive/HiveCatalogTest.java @@ -64,6 +64,7 @@ import org.junit.jupiter.params.provider.ValueSource; import java.lang.reflect.Field; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -75,6 +76,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.METASTORECONNECTURLKEY; import static org.apache.paimon.CoreOptions.BUCKET; @@ -361,6 +363,44 @@ public void testAlterAndDropTableWithInvalidOptions(boolean external) throws Exc assertThat(fileIO.exists(externalPath)).isEqualTo(external); } + @Test + public void testDropManagedTableWithTemplateFiles() throws Exception { + Identifier id = Identifier.create("default", "template_drop"); + java.nio.file.Path shared = + Files.createTempDirectory( + java.nio.file.Paths.get(new Path(warehouse).toUri()), "template-files-"); + Schema schema = + Schema.newBuilder() + .column("id", DataTypes.INT()) + .option(CoreOptions.BUCKET.key(), "-1") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + "entropy-inject-template") + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + shared.toUri() + "{hash}") + .build(); + catalog.createTable(id, schema, false); + FileStoreTable table = (FileStoreTable) catalog.getTable(id); + BatchWriteBuilder builder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = builder.newWrite(); + BatchTableCommit commit = builder.newCommit()) { + write.write(GenericRow.of(1)); + commit.commit(write.prepareCommit()); + } + try (Stream files = Files.walk(shared)) { + assertThat(files.anyMatch(Files::isRegularFile)).isTrue(); + } + + catalog.dropTable(id, false); + + assertThat(catalog.listTables("default")).doesNotContain(id.getTableName()); + assertThat(table.fileIO().exists(table.location())).isFalse(); + try (Stream files = Files.walk(shared)) { + assertThat(files.noneMatch(Files::isRegularFile)).isTrue(); + } + } + @Test public void testDropTableWhenTablePathMissing() throws Exception { String databaseName = "test_db";