From 100c2499a7ec7c5c727336610bab3190e4063ec0 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Tue, 3 Nov 2026 21:25:54 +0800 Subject: [PATCH 1/9] [core] Support entropy-inject-template external paths - CoreOptions.java, ExternalPathProvider.java and TemplateEntropyInjectExternalPathProvider.java: add a single path template with filename-based hash directories for shared object storage prefixes. - SchemaValidation.java and core_configuration.html: validate and document the new strategy. - AbstractCatalog.java and EntropyInjectTemplateFilesDeletion.java: delete manifest-referenced files for each template branch before dropping table metadata, while preserving external-table semantics. - OrphanFilesClean.java: reject orphan cleanup for the template strategy. - TemplateEntropyInjectExternalPathProviderTest.java, EntropyInjectTemplateTest.java and FileSystemCatalogTest.java: cover path generation, validation, snapshot expiration and table deletion across main and a branch. --- docs/generated/core_configuration.html | 2 +- .../java/org/apache/paimon/CoreOptions.java | 6 + .../fs/EntropyInjectExternalPathProvider.java | 4 +- .../paimon/fs/ExternalPathProvider.java | 3 + ...lateEntropyInjectExternalPathProvider.java | 91 +++++ ...EntropyInjectExternalPathProviderTest.java | 105 +++++ .../paimon/catalog/AbstractCatalog.java | 20 +- .../EntropyInjectTemplateFilesDeletion.java | 181 +++++++++ .../paimon/operation/OrphanFilesClean.java | 23 ++ .../paimon/schema/SchemaValidation.java | 48 +++ .../paimon/catalog/FileSystemCatalogTest.java | 41 ++ .../operation/EntropyInjectTemplateTest.java | 367 ++++++++++++++++++ 12 files changed, 886 insertions(+), 5 deletions(-) create mode 100644 paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java create mode 100644 paimon-common/src/test/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProviderTest.java create mode 100644 paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java create mode 100644 paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java diff --git a/docs/generated/core_configuration.html b/docs/generated/core_configuration.html index 2578dd8560d5..54d3dcc9d425 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..69754ce715d8 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,12 @@ 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."), + 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..a774c452ad2d --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java @@ -0,0 +1,91 @@ +/* + * 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); + } + + /** Whether the given external path is a template handled by this provider. */ + public static boolean isTemplate(String externalPath) { + return externalPath.contains(HASH_PLACEHOLDER); + } + + private static void checkTemplate(Path template) { + checkArgument( + isTemplate(template.toString()), + "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..1e9b07ea62e1 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 @@ -29,6 +29,7 @@ import org.apache.paimon.fs.cache.LocalCacheManager; import org.apache.paimon.function.Function; import org.apache.paimon.function.FunctionChange; +import org.apache.paimon.operation.EntropyInjectTemplateFilesDeletion; import org.apache.paimon.operation.Lock; import org.apache.paimon.options.Options; import org.apache.paimon.partition.Partition; @@ -393,9 +394,24 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) FileIO tableFileIO = fileIO(tablePath); SchemaManager schemaManager = new FileSystemSchemaManager(tableFileIO, tablePath); externalPaths.addAll(getSchemaExternalPaths(schemaManager.listAll())); + FileStoreTable table = (FileStoreTable) getTable(identifier); + boolean isExternal = loadTableMetadata(identifier).isExternal(); + Optional latestMainSchema = schemaManager.latest(); + if (!isExternal + && latestMainSchema.isPresent() + && EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) { + EntropyInjectTemplateFilesDeletion.delete(table); + } for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) { - externalPaths.addAll( - getSchemaExternalPaths(schemaManager.copyWithBranch(branch).listAll())); + SchemaManager schemaBranch = schemaManager.copyWithBranch(branch); + externalPaths.addAll(getSchemaExternalPaths(schemaBranch.listAll())); + Optional latestBranchSchema = schemaBranch.latest(); + if (!isExternal + && latestBranchSchema.isPresent() + && EntropyInjectTemplateFilesDeletion.isTemplate( + latestBranchSchema.get())) { + EntropyInjectTemplateFilesDeletion.delete(table.switchToBranch(branch)); + } } } } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java new file mode 100644 index 000000000000..cf956dee030c --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java @@ -0,0 +1,181 @@ +/* + * 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.fs.Path; +import org.apache.paimon.index.IndexFileHandler; +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.schema.TableSchema; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.utils.DataFilePathFactories; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.concurrent.ThreadPoolExecutor; + +import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; + +/** + * Deletes the data files of a single table branch using the {@link + * ExternalPathStrategy#ENTROPY_INJECT_TEMPLATE} strategy, whose external paths are shared with + * other tables. + * + *

For every other strategy the configured external paths belong to a single table, so dropping a + * table can simply delete these directories recursively. Templates can place hash directories + * before the database and table directories, allowing multiple tables to share a root. Files + * referenced by this branch are therefore collected from manifests and deleted one by one. + * + *

Collection takes every entry of every surviving manifest, both {@code ADD} and {@code DELETE}, + * without merging them. A file added by an older retained snapshot and removed by a newer one is + * still on disk when snapshot expiration has not caught up with it, and once the older snapshot is + * gone the file is only recorded as a {@code DELETE} entry. The merged view offered by {@link + * FileDeletionBase} contains only live files and would omit these pending deletions. Files absent + * from all retained manifests are not discovered by this cleanup. + * + *

Deletion collects file paths one manifest at a time instead of keeping a table-wide file set. + * Snapshot and manifest references are still collected for the branch. File paths are deduplicated + * within each manifest; references in different manifests may cause repeated deletion attempts, and + * missing files are ignored. + */ +public class EntropyInjectTemplateFilesDeletion { + + private static final Logger LOG = + LoggerFactory.getLogger(EntropyInjectTemplateFilesDeletion.class); + + private final FileStoreTable table; + private final ThreadPoolExecutor executor; + + private EntropyInjectTemplateFilesDeletion(FileStoreTable table) { + this.table = table; + this.executor = + createCachedThreadPool( + table.coreOptions().fileOperationThreadNum(), "ENTROPY_TEMPLATE_DELETE"); + } + + /** + * Deletes the data files of the supplied branch. Call it only for a branch with template paths + * in its current schema, and only from a catalog that deletes the data of a dropped table. + * + *

Manifest read failures abort the drop and retain metadata for retry. File deletion is + * best-effort: failures are logged and do not prevent metadata deletion. + */ + public static void delete(FileStoreTable table) { + EntropyInjectTemplateFilesDeletion deletion = new EntropyInjectTemplateFilesDeletion(table); + try { + long deleted = deletion.deleteFiles(); + LOG.info("Attempted to delete {} files of table branch {}.", deleted, table.fullName()); + } catch (IOException e) { + throw new UncheckedIOException( + "Failed to delete the external data files of table " + + table.fullName() + + ", the table is kept so that dropping it can be retried.", + e); + } finally { + deletion.executor.shutdownNow(); + } + } + + public static boolean isTemplate(TableSchema schema) { + // compare the raw value instead of parsing the enum, so that a schema written by a newer + // version with an unknown strategy does not fail the whole drop + String strategy = schema.options().get(CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key()); + return ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString().equalsIgnoreCase(strategy); + } + + /** Reads each referenced manifest once; a file may occur in more than one manifest. */ + private long deleteFiles() throws IOException { + ManifestList manifestList = table.store().manifestListFactory().create(); + Set dataManifests = new LinkedHashSet<>(); + Set indexManifests = new LinkedHashSet<>(); + for (Snapshot snapshot : allSnapshots()) { + for (ManifestFileMeta meta : manifestList.readAllManifests(snapshot)) { + dataManifests.add(meta.fileName()); + } + if (snapshot.indexManifest() != null) { + indexManifests.add(snapshot.indexManifest()); + } + } + + return deleteDataFiles(dataManifests) + deleteIndexFiles(indexManifests); + } + + private Set allSnapshots() throws IOException { + Set snapshots = + new LinkedHashSet<>(table.snapshotManager().safelyGetAllSnapshots()); + snapshots.addAll(table.tagManager().taggedSnapshots()); + snapshots.addAll(table.changelogManager().safelyGetAllChangelogs()); + return snapshots; + } + + private long deleteDataFiles(Set manifestNames) throws IOException { + ManifestFile manifestFile = table.store().manifestFileFactory().create(); + DataFilePathFactories factories = new DataFilePathFactories(table.store().pathFactory()); + + long deleted = 0; + for (String manifestName : manifestNames) { + Set files = new LinkedHashSet<>(); + for (ManifestEntry entry : manifestFile.readWithIOException(manifestName)) { + files.addAll( + entry.file() + .collectFiles(factories.get(entry.partition(), entry.bucket()))); + } + deleted += deleteAll(files); + } + return deleted; + } + + private long deleteIndexFiles(Set manifestNames) throws IOException { + IndexFileHandler indexFileHandler = table.store().newIndexFileHandler(); + + long deleted = 0; + for (String manifestName : manifestNames) { + if (!indexFileHandler.existsManifest(manifestName)) { + continue; + } + Set files = new LinkedHashSet<>(); + for (IndexManifestEntry entry : + indexFileHandler.readManifestWithIOException(manifestName)) { + files.add(indexFileHandler.filePath(entry)); + } + deleted += deleteAll(files); + } + return deleted; + } + + private long deleteAll(Set files) { + if (files.isEmpty()) { + return 0; + } + randomlyOnlyExecute(executor, table.fileIO()::deleteQuietly, files); + return files.size(); + } +} 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/schema/SchemaValidation.java b/paimon-core/src/main/java/org/apache/paimon/schema/SchemaValidation.java index 3416d66f9f56..55195ed3cae2 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,7 @@ import org.apache.paimon.fileindex.FileIndexerFactoryUtils; import org.apache.paimon.format.FileFormat; import org.apache.paimon.format.csv.CsvOptions; +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 +447,52 @@ public static void validateTableSchema(TableSchema schema, Set dynamicOp validatePkClusteringOverride(options); validateManifestSort(schema, options); + + validateExternalPaths(options); + } + + private static void validateExternalPaths(CoreOptions options) { + String externalPaths = options.dataFileExternalPaths(); + if (externalPaths == null || externalPaths.isEmpty()) { + return; + } + + boolean templateStrategy = + options.externalPathStrategy() == ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE; + String[] paths = externalPaths.split(","); + + if (templateStrategy && paths.length > 1) { + throw new IllegalArgumentException( + String.format( + "'%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)); + } + + for (String externalPath : paths) { + boolean isTemplate = TemplateEntropyInjectExternalPathProvider.isTemplate(externalPath); + if (templateStrategy && !isTemplate) { + throw new IllegalArgumentException( + String.format( + "External path '%s' must contain the '%s' placeholder when '%s' is '%s'.", + externalPath.trim(), + TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER, + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE)); + } + if (!templateStrategy && isTemplate) { + throw new IllegalArgumentException( + String.format( + "External path '%s' can only contain the '%s' placeholder when '%s' is '%s', but it is '%s'.", + externalPath.trim(), + TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER, + CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE, + options.externalPathStrategy())); + } + } } /** 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..2af7827312d0 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,46 @@ 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(); + } + } + @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..68d3841024ba --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -0,0 +1,367 @@ +/* + * 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.local.LocalFileIO; +import org.apache.paimon.manifest.ManifestList; +import org.apache.paimon.options.ExpireConfig; +import org.apache.paimon.schema.Schema; +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 java.io.IOException; +import java.nio.file.Files; +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 remains subject to the catalog's existing directory cleanup. */ + @Test + public void testDropTableRemovesTheLiteralPlaceholderDirectory() 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("data-from-an-older-version.parquet"), new byte[] {1}); + + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + + assertThat(Files.exists(literal)).isFalse(); + assertThat(sharedTableFiles("t1")).isEmpty(); + 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 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()); + } + + @Test + public void testExternalPathMustContainPlaceholder() { + assertThatThrownBy( + () -> + catalog.createTable( + Identifier.create(DATABASE, "bad"), + schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + sharedRoot + "/bad") + .option( + CoreOptions + .DATA_FILE_EXTERNAL_PATHS_STRATEGY + .key(), + ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE + .toString()) + .build(), + false)) + .rootCause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("{hash}"); + } + + @Test + public void testPlaceholderNeedsTemplateStrategy() { + assertThatThrownBy( + () -> + catalog.createTable( + Identifier.create(DATABASE, "bad"), + schemaBuilder() + .option( + CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), + "file://" + sharedRoot + "/{hash}/bad") + .option( + CoreOptions + .DATA_FILE_EXTERNAL_PATHS_STRATEGY + .key(), + ExternalPathStrategy.ROUND_ROBIN.toString()) + .build(), + false)) + .rootCause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("{hash}"); + } + + @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()); + } +} From 3e2062dfb8dbdd8584f6691a3dabad043fe18f73 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:47:27 +0800 Subject: [PATCH 2/9] fix(core): protect shared template roots during drop - SchemaValidation.java and TemplateEntropyInjectExternalPathProvider.java: require a placeholder in the normalized URI path. - AbstractCatalog.java: omit template data directories from recursive cleanup. - EntropyInjectTemplateTest.java: cover normalized-away placeholders and protect the literal directory. --- ...lateEntropyInjectExternalPathProvider.java | 11 ++++------ .../paimon/catalog/AbstractCatalog.java | 4 +++- .../paimon/schema/SchemaValidation.java | 17 ++++++---------- .../operation/EntropyInjectTemplateTest.java | 20 +++++++++++-------- 4 files changed, 25 insertions(+), 27 deletions(-) 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 index a774c452ad2d..6542c2759417 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/TemplateEntropyInjectExternalPathProvider.java @@ -72,14 +72,11 @@ public Path getNextExternalDataPath(String fileName) { return new Path(new Path(externalTablePath, relativeBucketPath), fileName); } - /** Whether the given external path is a template handled by this provider. */ - public static boolean isTemplate(String externalPath) { - return externalPath.contains(HASH_PLACEHOLDER); - } - - private static void checkTemplate(Path template) { + /** Validates that the normalized URI path contains the hash placeholder. */ + public static void checkTemplate(Path template) { + String path = template.toUri().getPath(); checkArgument( - isTemplate(template.toString()), + path != null && path.contains(HASH_PLACEHOLDER), "External path '%s' must contain the '%s' placeholder.", template, HASH_PLACEHOLDER); 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 1e9b07ea62e1..ecb1cc7ed3e1 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 @@ -433,7 +433,9 @@ private List getSchemaExternalPaths(List schemas) { Map options = schema.toSchema().options(); return Arrays.stream( new String[] { - options.get(DATA_FILE_EXTERNAL_PATHS.key()), + EntropyInjectTemplateFilesDeletion.isTemplate(schema) + ? null + : options.get(DATA_FILE_EXTERNAL_PATHS.key()), options.get(GLOBAL_INDEX_EXTERNAL_PATH.key()) }); }) 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 55195ed3cae2..4103f6a10f1f 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 @@ -32,6 +32,7 @@ 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; @@ -472,17 +473,11 @@ private static void validateExternalPaths(CoreOptions options) { } for (String externalPath : paths) { - boolean isTemplate = TemplateEntropyInjectExternalPathProvider.isTemplate(externalPath); - if (templateStrategy && !isTemplate) { - throw new IllegalArgumentException( - String.format( - "External path '%s' must contain the '%s' placeholder when '%s' is '%s'.", - externalPath.trim(), - TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER, - CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), - ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE)); - } - if (!templateStrategy && isTemplate) { + if (templateStrategy) { + TemplateEntropyInjectExternalPathProvider.checkTemplate( + new Path(externalPath.trim())); + } else if (externalPath.contains( + TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER)) { throw new IllegalArgumentException( String.format( "External path '%s' can only contain the '%s' placeholder when '%s' is '%s', but it is '%s'.", 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 index 68d3841024ba..a9dca3c0c310 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -44,6 +44,8 @@ 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; @@ -173,9 +175,9 @@ private int manifestCount(FileStoreTable t) throws Exception { return names.size(); } - /** The literal template path remains subject to the catalog's existing directory cleanup. */ + /** The literal template path is excluded from recursive directory cleanup. */ @Test - public void testDropTableRemovesTheLiteralPlaceholderDirectory() throws Exception { + public void testDropTablePreservesTheLiteralPlaceholderDirectory() throws Exception { FileStoreTable t1 = createTable("t1"); FileStoreTable t2 = createTable("t2"); write(t1, 1, "a"); @@ -185,12 +187,13 @@ public void testDropTableRemovesTheLiteralPlaceholderDirectory() throws Exceptio java.nio.file.Path literal = sharedRoot.resolve("{hash}").resolve(DATABASE + ".db").resolve("t1"); Files.createDirectories(literal); - Files.write(literal.resolve("data-from-an-older-version.parquet"), new byte[] {1}); + Files.write(literal.resolve("legacy.parquet"), new byte[] {1}); catalog.dropTable(Identifier.create(DATABASE, "t1"), false); - assertThat(Files.exists(literal)).isFalse(); - assertThat(sharedTableFiles("t1")).isEmpty(); + assertThat(sharedTableFiles("t1")) + .containsExactly( + sharedRoot.relativize(literal.resolve("legacy.parquet")).toString()); assertThat(sharedTableFiles("t2")).isEqualTo(t2Files); } @@ -234,8 +237,9 @@ public void testRemoveOrphanFilesIsNotSupported() throws Exception { .hasMessageContaining(CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key()); } - @Test - public void testExternalPathMustContainPlaceholder() { + @ParameterizedTest + @ValueSource(strings = {"/bad", "/{hash}/.."}) + public void testExternalPathMustContainPlaceholder(String suffix) { assertThatThrownBy( () -> catalog.createTable( @@ -243,7 +247,7 @@ public void testExternalPathMustContainPlaceholder() { schemaBuilder() .option( CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), - "file://" + sharedRoot + "/bad") + "file://" + sharedRoot + suffix) .option( CoreOptions .DATA_FILE_EXTERNAL_PATHS_STRATEGY From 5741072de270eb9d7ea4b0b4541f1d12a822113f Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:47:27 +0800 Subject: [PATCH 3/9] fix(core): keep literal hash paths for existing strategies - SchemaValidation.java: interpret the placeholder only for the template strategy. - EntropyInjectTemplateTest.java: verify a literal round-robin path can write and plan a scan. --- .../paimon/schema/SchemaValidation.java | 10 ----- .../operation/EntropyInjectTemplateTest.java | 37 +++++++++---------- 2 files changed, 18 insertions(+), 29 deletions(-) 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 4103f6a10f1f..a9757840d7e6 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 @@ -476,16 +476,6 @@ private static void validateExternalPaths(CoreOptions options) { if (templateStrategy) { TemplateEntropyInjectExternalPathProvider.checkTemplate( new Path(externalPath.trim())); - } else if (externalPath.contains( - TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER)) { - throw new IllegalArgumentException( - String.format( - "External path '%s' can only contain the '%s' placeholder when '%s' is '%s', but it is '%s'.", - externalPath.trim(), - TemplateEntropyInjectExternalPathProvider.HASH_PLACEHOLDER, - CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(), - ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE, - options.externalPathStrategy())); } } } 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 index a9dca3c0c310..92bbe68f5f09 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -262,25 +262,24 @@ public void testExternalPathMustContainPlaceholder(String suffix) { } @Test - public void testPlaceholderNeedsTemplateStrategy() { - assertThatThrownBy( - () -> - catalog.createTable( - Identifier.create(DATABASE, "bad"), - schemaBuilder() - .option( - CoreOptions.DATA_FILE_EXTERNAL_PATHS.key(), - "file://" + sharedRoot + "/{hash}/bad") - .option( - CoreOptions - .DATA_FILE_EXTERNAL_PATHS_STRATEGY - .key(), - ExternalPathStrategy.ROUND_ROBIN.toString()) - .build(), - false)) - .rootCause() - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("{hash}"); + 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 From d4db7a3bc0d0acefc71a6e35605f5840f70e6bc6 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:47:27 +0800 Subject: [PATCH 4/9] fix(core): require exactly one non-empty path template - SchemaValidation.java: reject missing, blank and multiple template paths during schema validation. - EntropyInjectTemplateTest.java: check CREATE and ALTER both require the path. --- .../paimon/schema/SchemaValidation.java | 43 ++++++++----------- .../operation/EntropyInjectTemplateTest.java | 26 +++++++++++ 2 files changed, 45 insertions(+), 24 deletions(-) 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 a9757840d7e6..7407619d7f83 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 @@ -449,35 +449,30 @@ public static void validateTableSchema(TableSchema schema, Set dynamicOp validateManifestSort(schema, options); - validateExternalPaths(options); + validateExternalPathTemplate(options); } - private static void validateExternalPaths(CoreOptions options) { - String externalPaths = options.dataFileExternalPaths(); - if (externalPaths == null || externalPaths.isEmpty()) { + private static void validateExternalPathTemplate(CoreOptions options) { + if (options.externalPathStrategy() != ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE) { return; } - boolean templateStrategy = - options.externalPathStrategy() == ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE; - String[] paths = externalPaths.split(","); - - if (templateStrategy && paths.length > 1) { - throw new IllegalArgumentException( - String.format( - "'%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)); - } - - for (String externalPath : paths) { - if (templateStrategy) { - TemplateEntropyInjectExternalPathProvider.checkTemplate( - new Path(externalPath.trim())); - } - } + 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/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java index 92bbe68f5f09..cea8336d421e 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -35,6 +35,7 @@ import org.apache.paimon.manifest.ManifestList; import org.apache.paimon.options.ExpireConfig; import org.apache.paimon.schema.Schema; +import org.apache.paimon.schema.SchemaChange; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.sink.BatchTableCommit; import org.apache.paimon.table.sink.BatchTableWrite; @@ -282,6 +283,31 @@ public void testRoundRobinAcceptsLiteralPlaceholderDirectory() throws Exception assertThat(Files.isDirectory(sharedRoot.resolve("{hash}").resolve("literal"))).isTrue(); } + @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, schemaBuilder().build(), false); + assertThatThrownBy( + () -> + catalog.alterTable( + identifier, + Collections.singletonList( + SchemaChange.setOption(strategy, template)), + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires a non-empty template"); + } + @Test public void testOnlyOneTemplateIsAllowed() { assertThatThrownBy( From f62241d6886322d085134f6ce6f0322d83b278a0 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:48:29 +0800 Subject: [PATCH 5/9] fix(core): avoid constructing read wrappers during drop - AbstractCatalog.java and EntropyInjectTemplateFilesDeletion.java: only construct a branch-local table when its schema needs template cleanup. - FileSystemCatalogTest.java: drop a chain table after removing its snapshot branch. --- .../paimon/catalog/AbstractCatalog.java | 7 +- .../EntropyInjectTemplateFilesDeletion.java | 13 +++- .../paimon/schema/SchemaValidation.java | 4 ++ .../paimon/catalog/FileSystemCatalogTest.java | 46 +++++++++++++ .../operation/EntropyInjectTemplateTest.java | 64 +++++++++++++++++++ 5 files changed, 130 insertions(+), 4 deletions(-) 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 ecb1cc7ed3e1..51de5e574493 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 @@ -394,13 +394,13 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) FileIO tableFileIO = fileIO(tablePath); SchemaManager schemaManager = new FileSystemSchemaManager(tableFileIO, tablePath); externalPaths.addAll(getSchemaExternalPaths(schemaManager.listAll())); - FileStoreTable table = (FileStoreTable) getTable(identifier); boolean isExternal = loadTableMetadata(identifier).isExternal(); Optional latestMainSchema = schemaManager.latest(); if (!isExternal && latestMainSchema.isPresent() && EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) { - EntropyInjectTemplateFilesDeletion.delete(table); + EntropyInjectTemplateFilesDeletion.delete( + tableFileIO, tablePath, DEFAULT_MAIN_BRANCH, latestMainSchema.get()); } for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) { SchemaManager schemaBranch = schemaManager.copyWithBranch(branch); @@ -410,7 +410,8 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) && latestBranchSchema.isPresent() && EntropyInjectTemplateFilesDeletion.isTemplate( latestBranchSchema.get())) { - EntropyInjectTemplateFilesDeletion.delete(table.switchToBranch(branch)); + EntropyInjectTemplateFilesDeletion.delete( + tableFileIO, tablePath, branch, latestBranchSchema.get()); } } } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java index cf956dee030c..713a117489bc 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java @@ -21,6 +21,7 @@ import org.apache.paimon.CoreOptions; import org.apache.paimon.CoreOptions.ExternalPathStrategy; import org.apache.paimon.Snapshot; +import org.apache.paimon.fs.FileIO; import org.apache.paimon.fs.Path; import org.apache.paimon.index.IndexFileHandler; import org.apache.paimon.manifest.IndexManifestEntry; @@ -28,8 +29,11 @@ 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.utils.DataFilePathFactories; import org.slf4j.Logger; @@ -88,7 +92,14 @@ private EntropyInjectTemplateFilesDeletion(FileStoreTable table) { *

Manifest read failures abort the drop and retain metadata for retry. File deletion is * best-effort: failures are logged and do not prevent metadata deletion. */ - public static void delete(FileStoreTable table) { + public static void delete(FileIO fileIO, Path tablePath, String branch, TableSchema schema) { + FileStoreTable table = + FileStoreTableFactory.createWithoutFallbackBranch( + fileIO, + tablePath, + schema, + new Options().set(CoreOptions.BRANCH, branch), + CatalogEnvironment.empty()); EntropyInjectTemplateFilesDeletion deletion = new EntropyInjectTemplateFilesDeletion(table); try { long deleted = deletion.deleteFiles(); 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 7407619d7f83..49f8623a7e0f 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 @@ -457,6 +457,10 @@ private static void validateExternalPathTemplate(CoreOptions options) { 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(), 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 2af7827312d0..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 @@ -330,6 +330,52 @@ public void testDropTableWithTemplateBranch() throws Exception { } } + @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 index cea8336d421e..97626c91b18d 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -34,8 +34,10 @@ import org.apache.paimon.fs.local.LocalFileIO; import org.apache.paimon.manifest.ManifestList; import org.apache.paimon.options.ExpireConfig; +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; @@ -283,6 +285,68 @@ public void testRoundRobinAcceptsLiteralPlaceholderDirectory() throws Exception 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(); From 70d8f0920fa9e548f93eac1fab1749cb3414cc07 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:48:29 +0800 Subject: [PATCH 6/9] fix(core): defer template file deletion until catalog drop succeeds - AbstractCatalog.java and TemplateFileDeletionPlan.java: stage bounded file lists under the table directory, archive them before the directory is removed, and confirm file cleanup after the catalog accepts the drop. - EntropyInjectTemplateFilesDeletion.java: stream manifest paths into the plan. - EntropyInjectTemplateTest.java: cover catalog refusal, table-local batching and retry after failed deletion. --- .../paimon/catalog/AbstractCatalog.java | 58 ++-- .../EntropyInjectTemplateFilesDeletion.java | 163 ++++------- .../operation/TemplateFileDeletionPlan.java | 259 ++++++++++++++++++ .../operation/EntropyInjectTemplateTest.java | 81 ++++++ 4 files changed, 427 insertions(+), 134 deletions(-) create mode 100644 paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java 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 51de5e574493..39d9d885c4e5 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 @@ -31,6 +31,7 @@ import org.apache.paimon.function.FunctionChange; import org.apache.paimon.operation.EntropyInjectTemplateFilesDeletion; 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; @@ -83,6 +84,7 @@ import static org.apache.paimon.catalog.CatalogUtils.listPartitionsFromFileSystem; import static org.apache.paimon.catalog.CatalogUtils.validateCreateTable; import static org.apache.paimon.catalog.Identifier.DEFAULT_MAIN_BRANCH; +import static org.apache.paimon.utils.Preconditions.checkState; /** Common implementation of {@link Catalog}. */ public abstract class AbstractCatalog implements Catalog { @@ -380,44 +382,60 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) if (!tableExists(identifier)) { if (ignoreIfNotExists) { + try { + Path tablePath = getTableLocation(identifier); + TemplateFileDeletionPlan.retryTableDrops( + fileIO(tablePath), + tablePath, + Runtime.getRuntime().availableProcessors()); + } catch (RuntimeException e) { + LOG.warn("Cannot retry file cleanup for {}", identifier, e); + } return; } throw new TableNotExistException(identifier); } Set externalPaths = new HashSet<>(); + TemplateFileDeletionPlan plan = null; + int cleanupThreads = 1; 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())); boolean isExternal = loadTableMetadata(identifier).isExternal(); - Optional latestMainSchema = schemaManager.latest(); - if (!isExternal - && latestMainSchema.isPresent() - && EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) { - EntropyInjectTemplateFilesDeletion.delete( - tableFileIO, tablePath, DEFAULT_MAIN_BRANCH, latestMainSchema.get()); - } - for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) { - SchemaManager schemaBranch = schemaManager.copyWithBranch(branch); - externalPaths.addAll(getSchemaExternalPaths(schemaBranch.listAll())); - Optional latestBranchSchema = schemaBranch.latest(); + 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 - && latestBranchSchema.isPresent() - && EntropyInjectTemplateFilesDeletion.isTemplate( - latestBranchSchema.get())) { - EntropyInjectTemplateFilesDeletion.delete( - tableFileIO, tablePath, branch, latestBranchSchema.get()); + && latest.isPresent() + && EntropyInjectTemplateFilesDeletion.isTemplate(latest.get())) { + if (plan == null) { + plan = TemplateFileDeletionPlan.prepare(tableFileIO, tablePath); + cleanupThreads = options.fileOperationThreadNum(); + } + EntropyInjectTemplateFilesDeletion.collect( + tableFileIO, tablePath, branch, latest.get(), plan); } } } } + if (plan != null) { + plan = plan.archiveForTableDrop(); + } dropTableImpl(identifier, new ArrayList<>(externalPaths)); + if (plan != null) { + checkState(!tableExists(identifier), "Table %s still exists after DROP.", identifier); + plan.confirmTableDrop(cleanupThreads); + } } protected boolean tableExists(Identifier identifier) { diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java index 713a117489bc..edf9458fead0 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java @@ -36,98 +36,60 @@ import org.apache.paimon.table.FileStoreTableFactory; import org.apache.paimon.utils.DataFilePathFactories; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.UncheckedIOException; import java.util.LinkedHashSet; import java.util.Set; -import java.util.concurrent.ThreadPoolExecutor; - -import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; -import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; - -/** - * Deletes the data files of a single table branch using the {@link - * ExternalPathStrategy#ENTROPY_INJECT_TEMPLATE} strategy, whose external paths are shared with - * other tables. - * - *

For every other strategy the configured external paths belong to a single table, so dropping a - * table can simply delete these directories recursively. Templates can place hash directories - * before the database and table directories, allowing multiple tables to share a root. Files - * referenced by this branch are therefore collected from manifests and deleted one by one. - * - *

Collection takes every entry of every surviving manifest, both {@code ADD} and {@code DELETE}, - * without merging them. A file added by an older retained snapshot and removed by a newer one is - * still on disk when snapshot expiration has not caught up with it, and once the older snapshot is - * gone the file is only recorded as a {@code DELETE} entry. The merged view offered by {@link - * FileDeletionBase} contains only live files and would omit these pending deletions. Files absent - * from all retained manifests are not discovered by this cleanup. - * - *

Deletion collects file paths one manifest at a time instead of keeping a table-wide file set. - * Snapshot and manifest references are still collected for the branch. File paths are deduplicated - * within each manifest; references in different manifests may cause repeated deletion attempts, and - * missing files are ignored. - */ -public class EntropyInjectTemplateFilesDeletion { - private static final Logger LOG = - LoggerFactory.getLogger(EntropyInjectTemplateFilesDeletion.class); +/** Collects exact file paths for tables with shared hash prefixes. */ +public final class EntropyInjectTemplateFilesDeletion { - private final FileStoreTable table; - private final ThreadPoolExecutor executor; + private EntropyInjectTemplateFilesDeletion() {} - private EntropyInjectTemplateFilesDeletion(FileStoreTable table) { - this.table = table; - this.executor = - createCachedThreadPool( - table.coreOptions().fileOperationThreadNum(), "ENTROPY_TEMPLATE_DELETE"); - } - - /** - * Deletes the data files of the supplied branch. Call it only for a branch with template paths - * in its current schema, and only from a catalog that deletes the data of a dropped table. - * - *

Manifest read failures abort the drop and retain metadata for retry. File deletion is - * best-effort: failures are logged and do not prevent metadata deletion. - */ - public static void delete(FileIO fileIO, Path tablePath, String branch, TableSchema schema) { - FileStoreTable table = - FileStoreTableFactory.createWithoutFallbackBranch( - fileIO, - tablePath, - schema, - new Options().set(CoreOptions.BRANCH, branch), - CatalogEnvironment.empty()); - EntropyInjectTemplateFilesDeletion deletion = new EntropyInjectTemplateFilesDeletion(table); + /** Reads one branch's manifests into the drop plan before metadata is removed. */ + public static void collect( + FileIO fileIO, + Path tablePath, + String branch, + TableSchema schema, + TemplateFileDeletionPlan plan) { try { - long deleted = deletion.deleteFiles(); - LOG.info("Attempted to delete {} files of table branch {}.", deleted, table.fullName()); + forEachFile(branchTable(fileIO, tablePath, branch, schema), plan::add); } catch (IOException e) { - throw new UncheckedIOException( - "Failed to delete the external data files of table " - + table.fullName() - + ", the table is kept so that dropping it can be retried.", - e); - } finally { - deletion.executor.shutdownNow(); + plan.discard(); + throw new UncheckedIOException("Cannot collect template files for " + tablePath, e); + } catch (RuntimeException e) { + plan.discard(); + throw e; } } public static boolean isTemplate(TableSchema schema) { - // compare the raw value instead of parsing the enum, so that a schema written by a newer - // version with an unknown strategy does not fail the whole drop String strategy = schema.options().get(CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key()); return ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE.toString().equalsIgnoreCase(strategy); } - /** Reads each referenced manifest once; a file may occur in more than one manifest. */ - private long deleteFiles() throws IOException { + private static FileStoreTable branchTable( + FileIO fileIO, Path tablePath, String branch, TableSchema schema) { + return FileStoreTableFactory.createWithoutFallbackBranch( + fileIO, + tablePath, + schema, + new Options().set(CoreOptions.BRANCH, branch), + CatalogEnvironment.empty()); + } + + // Include ADD and DELETE entries, even if a file is absent from the latest snapshot. + private static void forEachFile(FileStoreTable table, FileConsumer consumer) + throws IOException { ManifestList manifestList = table.store().manifestListFactory().create(); Set dataManifests = new LinkedHashSet<>(); Set indexManifests = new LinkedHashSet<>(); - for (Snapshot snapshot : allSnapshots()) { + 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()); } @@ -136,57 +98,30 @@ private long deleteFiles() throws IOException { } } - return deleteDataFiles(dataManifests) + deleteIndexFiles(indexManifests); - } - - private Set allSnapshots() throws IOException { - Set snapshots = - new LinkedHashSet<>(table.snapshotManager().safelyGetAllSnapshots()); - snapshots.addAll(table.tagManager().taggedSnapshots()); - snapshots.addAll(table.changelogManager().safelyGetAllChangelogs()); - return snapshots; - } - - private long deleteDataFiles(Set manifestNames) throws IOException { ManifestFile manifestFile = table.store().manifestFileFactory().create(); DataFilePathFactories factories = new DataFilePathFactories(table.store().pathFactory()); - - long deleted = 0; - for (String manifestName : manifestNames) { - Set files = new LinkedHashSet<>(); - for (ManifestEntry entry : manifestFile.readWithIOException(manifestName)) { - files.addAll( + for (String name : dataManifests) { + for (ManifestEntry entry : manifestFile.readWithIOException(name)) { + for (Path file : entry.file() - .collectFiles(factories.get(entry.partition(), entry.bucket()))); + .collectFiles(factories.get(entry.partition(), entry.bucket()))) { + consumer.accept(file); + } } - deleted += deleteAll(files); } - return deleted; - } - private long deleteIndexFiles(Set manifestNames) throws IOException { - IndexFileHandler indexFileHandler = table.store().newIndexFileHandler(); - - long deleted = 0; - for (String manifestName : manifestNames) { - if (!indexFileHandler.existsManifest(manifestName)) { - continue; - } - Set files = new LinkedHashSet<>(); - for (IndexManifestEntry entry : - indexFileHandler.readManifestWithIOException(manifestName)) { - files.add(indexFileHandler.filePath(entry)); + IndexFileHandler indexes = table.store().newIndexFileHandler(); + for (String name : indexManifests) { + if (indexes.existsManifest(name)) { + for (IndexManifestEntry entry : indexes.readManifestWithIOException(name)) { + consumer.accept(indexes.filePath(entry)); + } } - deleted += deleteAll(files); } - return deleted; } - private long deleteAll(Set files) { - if (files.isEmpty()) { - return 0; - } - randomlyOnlyExecute(executor, table.fileIO()::deleteQuietly, files); - return files.size(); + @FunctionalInterface + private interface FileConsumer { + void accept(Path path) throws IOException; } } 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..d6e42a63a30e --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java @@ -0,0 +1,259 @@ +/* + * 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.fs.FileIO; +import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.Path; +import org.apache.paimon.utils.JsonSerdeUtil; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; + +/** Batches the exact paths of template files recorded by DROP operations. */ +public final class TemplateFileDeletionPlan { + + private static final Logger LOG = LoggerFactory.getLogger(TemplateFileDeletionPlan.class); + private static final int BATCH_SIZE = 1024; + private static final String CLEANUP_DIRECTORY = ".paimon-template-drops"; + private static final String TABLE_PREFIX = "table-"; + private static final String SEALED = "sealed"; + private static final String TABLE_DROPPED = "table-dropped"; + + private final FileIO fileIO; + private final Path tablePath; + private final Path plan; + private final Set paths = new LinkedHashSet<>(); + private int batchCount; + + private TemplateFileDeletionPlan(FileIO fileIO, Path tablePath, Path directory, String prefix) { + this.fileIO = fileIO; + this.tablePath = tablePath; + this.plan = new Path(directory, prefix + UUID.randomUUID()); + } + + /** Collect a table's file paths under its own directory before the table is dropped. */ + public static TemplateFileDeletionPlan prepare(FileIO fileIO, Path tablePath) { + return new TemplateFileDeletionPlan( + fileIO, tablePath, tableCleanupPath(tablePath), TABLE_PREFIX); + } + + void add(Path path) throws IOException { + paths.add(path); + if (paths.size() == BATCH_SIZE) { + flush(); + } + } + + /** Complete the plan before deleting any metadata. */ + public void seal() { + try { + flush(); + publish(fileIO, new Path(plan, SEALED), Integer.toString(batchCount)); + } catch (IOException e) { + discard(); + throw new UncheckedIOException("Cannot seal file cleanup plan " + plan, e); + } + } + + void discard() { + fileIO.deleteDirectoryQuietly(plan); + } + + /** + * Preserve the table candidates before DROP removes their table directory. Returns an archived + * plan that can be confirmed after the catalog accepts the drop. + */ + public TemplateFileDeletionPlan archiveForTableDrop() { + TemplateFileDeletionPlan archived = + new TemplateFileDeletionPlan( + fileIO, tablePath, archivePath(tablePath), TABLE_PREFIX); + try { + seal(); + copyBatches(fileIO, plan, archived); + archived.seal(); + return archived; + } catch (IOException | RuntimeException e) { + archived.discard(); + throw new IllegalStateException("Cannot archive file cleanup plan " + plan, e); + } finally { + discard(); + } + } + + /** Call only after the catalog has accepted the table drop. */ + public void confirmTableDrop(int threads) { + try { + publish(fileIO, new Path(plan, TABLE_DROPPED), tablePath.toString()); + reclaimTablePlan(fileIO, plan, threads); + } catch (IOException | RuntimeException e) { + LOG.warn("Cannot finish file cleanup for {}", plan, e); + } + } + + /** Retry confirmed table drops, including after the original table directory was removed. */ + public static void retryTableDrops(FileIO fileIO, Path tablePath, int threads) { + try { + Path root = archivePath(tablePath); + if (fileIO.exists(root)) { + for (FileStatus status : fileIO.listStatus(root)) { + Path plan = status.getPath(); + Path marker = new Path(plan, TABLE_DROPPED); + if (status.isDir() + && fileIO.exists(marker) + && tablePath.toString().equals(fileIO.readFileUtf8(marker))) { + reclaimTablePlan(fileIO, plan, threads); + } + } + } + } catch (IOException e) { + LOG.warn("Cannot retry file cleanup for {}", tablePath, e); + } + } + + private static void copyBatches(FileIO fileIO, Path source, TemplateFileDeletionPlan target) + throws IOException { + int count = batchCount(fileIO, source); + for (int i = 0; i < count; i++) { + Path batch = batchPath(source, i); + if (fileIO.exists(batch)) { + for (Path path : readBatch(fileIO, batch)) { + target.add(path); + } + } + } + } + + private static void reclaimTablePlan(FileIO fileIO, Path plan, int threads) throws IOException { + ThreadPoolExecutor executor = createCachedThreadPool(threads, "TEMPLATE_DROP_FILES"); + try { + cleanPlan( + fileIO, + plan, + false, + candidates -> { + AtomicBoolean deleted = new AtomicBoolean(true); + randomlyOnlyExecute( + executor, + path -> { + if (!deleteFile(fileIO, path)) { + deleted.set(false); + } + }, + candidates); + return deleted.get(); + }); + } finally { + executor.shutdownNow(); + } + } + + private static void cleanPlan(FileIO fileIO, Path plan, boolean dryRun, BatchCleaner cleaner) + throws IOException { + boolean complete = true; + int count = batchCount(fileIO, plan); + for (int i = 0; i < count; i++) { + Path batch = batchPath(plan, i); + if (fileIO.exists(batch)) { + if (cleaner.clean(readBatch(fileIO, batch))) { + if (!dryRun) { + fileIO.delete(batch, false); + } + } else { + complete = false; + } + } + } + if (!dryRun && complete) { + fileIO.deleteDirectoryQuietly(plan); + } + } + + static boolean deleteFile(FileIO fileIO, Path path) { + try { + if (fileIO.delete(path, false) || !fileIO.exists(path)) { + return true; + } + LOG.warn("Cannot remove template file {}", path); + } catch (IOException e) { + LOG.warn("Cannot remove template file {}", path, e); + } + return false; + } + + private void flush() throws IOException { + if (!paths.isEmpty()) { + publish( + fileIO, + batchPath(plan, batchCount), + JsonSerdeUtil.toJson( + paths.stream().map(Path::toString).toArray(String[]::new))); + batchCount++; + paths.clear(); + } + } + + private static Set readBatch(FileIO fileIO, Path batch) throws IOException { + Set candidates = new LinkedHashSet<>(); + for (String file : JsonSerdeUtil.fromJson(fileIO.readFileUtf8(batch), String[].class)) { + candidates.add(new Path(file)); + } + return candidates; + } + + private static int batchCount(FileIO fileIO, Path plan) throws IOException { + return Integer.parseInt(fileIO.readFileUtf8(new Path(plan, SEALED))); + } + + private static Path tableCleanupPath(Path tablePath) { + return new Path(tablePath, CLEANUP_DIRECTORY); + } + + private static Path archivePath(Path tablePath) { + Path database = tablePath.getParent(); + Path warehouse = database.getParent(); + return new Path(warehouse == null ? database : warehouse, CLEANUP_DIRECTORY); + } + + private static Path batchPath(Path plan, int index) { + return new Path(plan, "batch-" + index); + } + + private static void publish(FileIO fileIO, Path file, String value) throws IOException { + if (!fileIO.tryToWriteAtomic(file, value) && !fileIO.exists(file)) { + throw new IOException("Cannot publish " + file); + } + } + + @FunctionalInterface + interface BatchCleaner { + boolean clean(Set candidates) throws IOException; + } +} 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 index 97626c91b18d..f3115dda3e0d 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -54,6 +54,7 @@ import java.nio.file.Files; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -230,6 +231,86 @@ protected TableMetadata loadTableMetadata(Identifier identifier) } } + @Test + public void testDropTableKeepsTheFilesWhenTheCatalogRefusesIt() throws Exception { + java.nio.file.Path warehouse = tempPath.resolve("refusing-warehouse"); + try (Catalog refusing = + new FileSystemCatalog(LocalFileIO.create(), new Path("file://" + warehouse)) { + @Override + protected void dropTableImpl(Identifier identifier, List externalPaths) { + throw new RuntimeException("the metastore refuses to drop the table"); + } + }) { + refusing.createDatabase(DATABASE, true); + Identifier id = Identifier.create(DATABASE, "kept"); + refusing.createTable(id, sharedSchema("kept"), false); + write((FileStoreTable) refusing.getTable(id), 1, "a"); + Set files = sharedTableFiles("kept"); + assertThat(files).hasSize(1); + + assertThatThrownBy(() -> refusing.dropTable(id, false)) + .hasMessageContaining("refuses to drop the table"); + + FileStoreTable keptTable = (FileStoreTable) refusing.getTable(id); + TemplateFileDeletionPlan.retryTableDrops(keptTable.fileIO(), keptTable.location(), 1); + assertThat(sharedTableFiles("kept")).isEqualTo(files); + } + } + + @Test + public void testDropPlanSpillsPathsInBatches() throws Exception { + FileStoreTable table = createTable("batched"); + LocalFileIO fileIO = LocalFileIO.create(); + TemplateFileDeletionPlan plan = TemplateFileDeletionPlan.prepare(fileIO, table.location()); + for (int i = 0; i <= 1024; i++) { + plan.add(new Path("file://" + sharedRoot.resolve("file-" + i))); + } + plan.seal(); + try (Stream files = + Files.walk(java.nio.file.Paths.get(table.location().toUri()))) { + assertThat( + files.filter(path -> path.getFileName().toString().startsWith("batch-")) + .count()) + .isEqualTo(2); + } + catalog.dropTable(Identifier.create(DATABASE, "batched"), false); + try (Stream files = Files.walk(tempPath.resolve("warehouse"))) { + assertThat(files.noneMatch(path -> path.getFileName().toString().startsWith("batch-"))) + .isTrue(); + } + } + + @Test + public void testDropTableRetriesFailedTemplateDeletion() 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 (!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"); + try (Catalog retrying = new FileSystemCatalog(failingFileIO, warehouse)) { + retrying.createDatabase(DATABASE, true); + retrying.createTable(identifier, sharedSchema("retry"), false); + write((FileStoreTable) retrying.getTable(identifier), 1, "a"); + + retrying.dropTable(identifier, false); + + assertThat(sharedTableFiles("retry")).hasSize(1); + } + + try (Catalog retrying = new FileSystemCatalog(LocalFileIO.create(), warehouse)) { + retrying.dropTable(identifier, true); + assertThat(sharedTableFiles("retry")).isEmpty(); + } + } + @Test public void testRemoveOrphanFilesIsNotSupported() throws Exception { FileStoreTable table = createTable("t1"); From eab48f997f249fae43cc6e8d421877013719176e Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:48:29 +0800 Subject: [PATCH 7/9] fix(core): prevent template strategy switches - SchemaManagerUtils.java, FileSystemSchemaManager.java, SchemaValidation.java and AbstractCatalog.java: reject switches to and from the template strategy through ALTER, dynamic overrides and in-place replacement. - CoreOptions.java and core_configuration.html: document the strategy constraint. - EntropyInjectTemplateTest.java: cover both directions, option reset and replacement on empty and populated tables. --- docs/generated/core_configuration.html | 2 +- .../java/org/apache/paimon/CoreOptions.java | 3 +- .../paimon/catalog/AbstractCatalog.java | 5 ++ .../schema/FileSystemSchemaManager.java | 3 + .../paimon/schema/SchemaManagerUtils.java | 8 ++ .../paimon/schema/SchemaValidation.java | 9 ++ .../operation/EntropyInjectTemplateTest.java | 85 ++++++++++++++++++- 7 files changed, 111 insertions(+), 4 deletions(-) diff --git a/docs/generated/core_configuration.html b/docs/generated/core_configuration.html index 54d3dcc9d425..d5d6d9e6f1cc 100644 --- a/docs/generated/core_configuration.html +++ b/docs/generated/core_configuration.html @@ -654,7 +654,7 @@

- + 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 69754ce715d8..faaeeb9b7e73 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -6065,7 +6065,8 @@ public enum ExternalPathStrategy implements DescribedEnum { "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."), + + "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", 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 39d9d885c4e5..83cdd9eda2a8 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 @@ -40,6 +40,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; @@ -73,6 +74,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; @@ -597,6 +599,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/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 49f8623a7e0f..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 @@ -452,6 +452,15 @@ public static void validateTableSchema(TableSchema schema, Set dynamicOp 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; 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 index f3115dda3e0d..43cc10fdb63b 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -52,6 +52,7 @@ import java.io.IOException; import java.nio.file.Files; +import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -257,6 +258,84 @@ protected void dropTableImpl(Identifier identifier, List externalPaths) { } } + @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 testDropPlanSpillsPathsInBatches() throws Exception { FileStoreTable table = createTable("batched"); @@ -441,13 +520,15 @@ public void testTemplateRequiresAnExternalPathOnCreateAndAlter() throws Exceptio false)) .rootCause() .hasMessageContaining("requires a non-empty template"); - catalog.createTable(identifier, schemaBuilder().build(), false); + catalog.createTable(identifier, sharedSchema("missing_path"), false); assertThatThrownBy( () -> catalog.alterTable( identifier, Collections.singletonList( - SchemaChange.setOption(strategy, template)), + SchemaChange.removeOption( + CoreOptions.DATA_FILE_EXTERNAL_PATHS + .key())), false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires a non-empty template"); From bb580c574a9e880dd7b8bdf8245a903c26c44d2d Mon Sep 17 00:00:00 2001 From: wzx140 Date: Thu, 19 Nov 2026 10:50:04 +0800 Subject: [PATCH 8/9] fix(core): retain template file references across branch drops - FileSystemBranchManager.java: collect the branch paths into a sealed plan before deleting branch metadata. - TemplateFileDeletionPlan.java: include saved branch plans in the archived table drop plan. - EntropyInjectTemplateTest.java: verify that dropping the table also reclaims files from a previously dropped branch. --- .../operation/TemplateFileDeletionPlan.java | 19 +++++++++++++++++-- .../paimon/utils/FileSystemBranchManager.java | 11 +++++++++++ .../operation/EntropyInjectTemplateTest.java | 18 ++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) 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 index d6e42a63a30e..cdc8207b57ef 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java @@ -43,6 +43,7 @@ public final class TemplateFileDeletionPlan { private static final Logger LOG = LoggerFactory.getLogger(TemplateFileDeletionPlan.class); private static final int BATCH_SIZE = 1024; private static final String CLEANUP_DIRECTORY = ".paimon-template-drops"; + private static final String BRANCH_PREFIX = "branch-"; private static final String TABLE_PREFIX = "table-"; private static final String SEALED = "sealed"; private static final String TABLE_DROPPED = "table-dropped"; @@ -65,6 +66,12 @@ public static TemplateFileDeletionPlan prepare(FileIO fileIO, Path tablePath) { fileIO, tablePath, tableCleanupPath(tablePath), TABLE_PREFIX); } + /** Keeps branch candidates under the table directory until the table is dropped. */ + public static TemplateFileDeletionPlan prepareBranch(FileIO fileIO, Path tablePath) { + return new TemplateFileDeletionPlan( + fileIO, tablePath, tableCleanupPath(tablePath), BRANCH_PREFIX); + } + void add(Path path) throws IOException { paths.add(path); if (paths.size() == BATCH_SIZE) { @@ -88,8 +95,8 @@ void discard() { } /** - * Preserve the table candidates before DROP removes their table directory. Returns an archived - * plan that can be confirmed after the catalog accepts the drop. + * Preserve the table and branch candidates before DROP removes their table directory. Returns + * an archived plan that can be confirmed after the catalog accepts the drop. */ public TemplateFileDeletionPlan archiveForTableDrop() { TemplateFileDeletionPlan archived = @@ -98,6 +105,14 @@ public TemplateFileDeletionPlan archiveForTableDrop() { try { seal(); copyBatches(fileIO, plan, archived); + for (FileStatus status : fileIO.listStatus(tableCleanupPath(tablePath))) { + Path candidate = status.getPath(); + if (status.isDir() + && candidate.getName().startsWith(BRANCH_PREFIX) + && fileIO.exists(new Path(candidate, SEALED))) { + copyBatches(fileIO, candidate, archived); + } + } archived.seal(); return archived; } catch (IOException | RuntimeException e) { 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..a707de484283 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 @@ -26,7 +26,9 @@ import org.apache.paimon.manifest.FileEntry; import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.operation.EntropyInjectTemplateFilesDeletion; 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 +50,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 +182,14 @@ 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() && EntropyInjectTemplateFilesDeletion.isTemplate(schema.get())) { + TemplateFileDeletionPlan plan = + TemplateFileDeletionPlan.prepareBranch(fileIO, tablePath); + EntropyInjectTemplateFilesDeletion.collect( + fileIO, tablePath, branchName, schema.get(), plan); + plan.seal(); + } try { // Delete branch directory fileIO.delete(branchPath(branchName), true); 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 index 43cc10fdb63b..58511b695f5f 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -336,6 +336,24 @@ public void testCannotSwitchTemplateStrategy(boolean withData) throws Exception } } + @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); + catalog.dropTable(Identifier.create(DATABASE, "t1"), false); + assertThat(sharedTableFiles("t1")).isEmpty(); + } + @Test public void testDropPlanSpillsPathsInBatches() throws Exception { FileStoreTable table = createTable("batched"); From 7d507de2d822bade87cd26eb413c895b79259384 Mon Sep 17 00:00:00 2001 From: wzx140 Date: Sun, 22 Nov 2026 21:15:03 +0800 Subject: [PATCH 9/9] refactor(core): consolidate template file cleanup --- .../paimon/catalog/AbstractCatalog.java | 34 +- .../paimon/catalog/FileSystemCatalog.java | 2 + .../org/apache/paimon/jdbc/JdbcCatalog.java | 8 +- .../EntropyInjectTemplateFilesDeletion.java | 127 ------ .../operation/TemplateFileDeletionPlan.java | 394 ++++++++++-------- .../paimon/utils/FileSystemBranchManager.java | 9 +- .../operation/EntropyInjectTemplateTest.java | 171 ++++++-- .../paimon/format/avro/AvroFileFormat.java | 9 + .../org/apache/paimon/hive/HiveCatalog.java | 6 +- .../apache/paimon/hive/HiveCatalogTest.java | 40 ++ 10 files changed, 426 insertions(+), 374 deletions(-) delete mode 100644 paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java 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 83cdd9eda2a8..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 @@ -29,7 +29,6 @@ import org.apache.paimon.fs.cache.LocalCacheManager; import org.apache.paimon.function.Function; import org.apache.paimon.function.FunctionChange; -import org.apache.paimon.operation.EntropyInjectTemplateFilesDeletion; import org.apache.paimon.operation.Lock; import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.options.Options; @@ -86,7 +85,6 @@ import static org.apache.paimon.catalog.CatalogUtils.listPartitionsFromFileSystem; import static org.apache.paimon.catalog.CatalogUtils.validateCreateTable; import static org.apache.paimon.catalog.Identifier.DEFAULT_MAIN_BRANCH; -import static org.apache.paimon.utils.Preconditions.checkState; /** Common implementation of {@link Catalog}. */ public abstract class AbstractCatalog implements Catalog { @@ -384,23 +382,12 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) if (!tableExists(identifier)) { if (ignoreIfNotExists) { - try { - Path tablePath = getTableLocation(identifier); - TemplateFileDeletionPlan.retryTableDrops( - fileIO(tablePath), - tablePath, - Runtime.getRuntime().availableProcessors()); - } catch (RuntimeException e) { - LOG.warn("Cannot retry file cleanup for {}", identifier, e); - } return; } throw new TableNotExistException(identifier); } Set externalPaths = new HashSet<>(); - TemplateFileDeletionPlan plan = null; - int cleanupThreads = 1; Path tablePath = getTableLocation(identifier); if (tableExistsInFileSystem(tablePath, DEFAULT_MAIN_BRANCH)) { CoreOptions options = CoreOptions.fromMap(loadTableSchema(identifier).options()); @@ -418,26 +405,15 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists) Optional latest = branchSchema.latest(); if (!isExternal && latest.isPresent() - && EntropyInjectTemplateFilesDeletion.isTemplate(latest.get())) { - if (plan == null) { - plan = TemplateFileDeletionPlan.prepare(tableFileIO, tablePath); - cleanupThreads = options.fileOperationThreadNum(); - } - EntropyInjectTemplateFilesDeletion.collect( - tableFileIO, tablePath, branch, latest.get(), plan); + && TemplateFileDeletionPlan.isTemplate(latest.get())) { + TemplateFileDeletionPlan.save( + tableFileIO, tablePath, branch, latest.get(), false); } } } } - if (plan != null) { - plan = plan.archiveForTableDrop(); - } dropTableImpl(identifier, new ArrayList<>(externalPaths)); - if (plan != null) { - checkState(!tableExists(identifier), "Table %s still exists after DROP.", identifier); - plan.confirmTableDrop(cleanupThreads); - } } protected boolean tableExists(Identifier identifier) { @@ -454,7 +430,7 @@ private List getSchemaExternalPaths(List schemas) { Map options = schema.toSchema().options(); return Arrays.stream( new String[] { - EntropyInjectTemplateFilesDeletion.isTemplate(schema) + TemplateFileDeletionPlan.isTemplate(schema) ? null : options.get(DATA_FILE_EXTERNAL_PATHS.key()), options.get(GLOBAL_INDEX_EXTERNAL_PATH.key()) @@ -489,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); 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/EntropyInjectTemplateFilesDeletion.java b/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java deleted file mode 100644 index edf9458fead0..000000000000 --- a/paimon-core/src/main/java/org/apache/paimon/operation/EntropyInjectTemplateFilesDeletion.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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.fs.FileIO; -import org.apache.paimon.fs.Path; -import org.apache.paimon.index.IndexFileHandler; -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.utils.DataFilePathFactories; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.LinkedHashSet; -import java.util.Set; - -/** Collects exact file paths for tables with shared hash prefixes. */ -public final class EntropyInjectTemplateFilesDeletion { - - private EntropyInjectTemplateFilesDeletion() {} - - /** Reads one branch's manifests into the drop plan before metadata is removed. */ - public static void collect( - FileIO fileIO, - Path tablePath, - String branch, - TableSchema schema, - TemplateFileDeletionPlan plan) { - try { - forEachFile(branchTable(fileIO, tablePath, branch, schema), plan::add); - } catch (IOException e) { - plan.discard(); - throw new UncheckedIOException("Cannot collect template files for " + tablePath, e); - } catch (RuntimeException e) { - plan.discard(); - throw e; - } - } - - 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); - } - - private static FileStoreTable branchTable( - FileIO fileIO, Path tablePath, String branch, TableSchema schema) { - return FileStoreTableFactory.createWithoutFallbackBranch( - fileIO, - tablePath, - schema, - new Options().set(CoreOptions.BRANCH, branch), - CatalogEnvironment.empty()); - } - - // Include ADD and DELETE entries, even if a file is absent from the latest snapshot. - private static void forEachFile(FileStoreTable table, FileConsumer consumer) - 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()))) { - consumer.accept(file); - } - } - } - - IndexFileHandler indexes = table.store().newIndexFileHandler(); - for (String name : indexManifests) { - if (indexes.existsManifest(name)) { - for (IndexManifestEntry entry : indexes.readManifestWithIOException(name)) { - consumer.accept(indexes.filePath(entry)); - } - } - } - } - - @FunctionalInterface - private interface FileConsumer { - void accept(Path path) throws IOException; - } -} 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 index cdc8207b57ef..8dfc52bc786b 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/TemplateFileDeletionPlan.java @@ -18,257 +18,319 @@ 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.utils.JsonSerdeUtil; +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; -/** Batches the exact paths of template files recorded by DROP operations. */ +/** 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 int BATCH_SIZE = 1024; private static final String CLEANUP_DIRECTORY = ".paimon-template-drops"; private static final String BRANCH_PREFIX = "branch-"; - private static final String TABLE_PREFIX = "table-"; - private static final String SEALED = "sealed"; - private static final String TABLE_DROPPED = "table-dropped"; + 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 final Path plan; - private final Set paths = new LinkedHashSet<>(); - private int batchCount; - private TemplateFileDeletionPlan(FileIO fileIO, Path tablePath, Path directory, String prefix) { + private TemplateFileDeletionPlan(FileIO fileIO, Path tablePath) { this.fileIO = fileIO; this.tablePath = tablePath; - this.plan = new Path(directory, prefix + UUID.randomUUID()); } - /** Collect a table's file paths under its own directory before the table is dropped. */ - public static TemplateFileDeletionPlan prepare(FileIO fileIO, Path tablePath) { - return new TemplateFileDeletionPlan( - fileIO, tablePath, tableCleanupPath(tablePath), TABLE_PREFIX); + 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); } - /** Keeps branch candidates under the table directory until the table is dropped. */ - public static TemplateFileDeletionPlan prepareBranch(FileIO fileIO, Path tablePath) { - return new TemplateFileDeletionPlan( - fileIO, tablePath, tableCleanupPath(tablePath), BRANCH_PREFIX); - } - - void add(Path path) throws IOException { - paths.add(path); - if (paths.size() == BATCH_SIZE) { - flush(); + /** 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; } - } - - /** Complete the plan before deleting any metadata. */ - public void seal() { + Path root = cleanupPath(tablePath); + String prefix = + archive + ? BRANCH_PREFIX + : BRANCH_PREFIX + + UUID.nameUUIDFromBytes(branch.getBytes(StandardCharsets.UTF_8)) + + "-"; try { - flush(); - publish(fileIO, new Path(plan, SEALED), Integer.toString(batchCount)); + 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) { - discard(); - throw new UncheckedIOException("Cannot seal file cleanup plan " + plan, e); + throw new UncheckedIOException("Cannot replace cleanup plan for branch " + branch, e); } } - void discard() { - fileIO.deleteDirectoryQuietly(plan); - } - - /** - * Preserve the table and branch candidates before DROP removes their table directory. Returns - * an archived plan that can be confirmed after the catalog accepts the drop. - */ - public TemplateFileDeletionPlan archiveForTableDrop() { - TemplateFileDeletionPlan archived = - new TemplateFileDeletionPlan( - fileIO, tablePath, archivePath(tablePath), TABLE_PREFIX); + 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 { - seal(); - copyBatches(fileIO, plan, archived); - for (FileStatus status : fileIO.listStatus(tableCleanupPath(tablePath))) { - Path candidate = status.getPath(); - if (status.isDir() - && candidate.getName().startsWith(BRANCH_PREFIX) - && fileIO.exists(new Path(candidate, SEALED))) { - copyBatches(fileIO, candidate, archived); - } - } - archived.seal(); - return archived; - } catch (IOException | RuntimeException e) { - archived.discard(); - throw new IllegalStateException("Cannot archive file cleanup plan " + plan, e); + 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 { - discard(); + if (!saved) { + writer.abort(); + fileIO.deleteDirectoryQuietly(plan); + } } } - /** Call only after the catalog has accepted the table drop. */ - public void confirmTableDrop(int threads) { + public static TemplateFileDeletionPlan init(FileIO fileIO, Path tablePath) { + return new TemplateFileDeletionPlan(fileIO, tablePath); + } + + public static void checkCanCreateTable(FileIO fileIO, Path tablePath) { try { - publish(fileIO, new Path(plan, TABLE_DROPPED), tablePath.toString()); - reclaimTablePlan(fileIO, plan, threads); - } catch (IOException | RuntimeException e) { - LOG.warn("Cannot finish file cleanup for {}", plan, e); + 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); } } - /** Retry confirmed table drops, including after the original table directory was removed. */ - public static void retryTableDrops(FileIO fileIO, Path tablePath, int threads) { + /** Deletes the files recorded in each cleanup manifest, then the manifest itself. */ + public void execute() { + Path root = cleanupPath(tablePath); try { - Path root = archivePath(tablePath); if (fileIO.exists(root)) { - for (FileStatus status : fileIO.listStatus(root)) { - Path plan = status.getPath(); - Path marker = new Path(plan, TABLE_DROPPED); - if (status.isDir() - && fileIO.exists(marker) - && tablePath.toString().equals(fileIO.readFileUtf8(marker))) { - reclaimTablePlan(fileIO, plan, threads); - } - } + reclaimFiles(root); + deleteIfEmpty(root); } - } catch (IOException e) { - LOG.warn("Cannot retry file cleanup for {}", tablePath, e); + } 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 static void copyBatches(FileIO fileIO, Path source, TemplateFileDeletionPlan target) - throws IOException { - int count = batchCount(fileIO, source); - for (int i = 0; i < count; i++) { - Path batch = batchPath(source, i); - if (fileIO.exists(batch)) { - for (Path path : readBatch(fileIO, batch)) { - target.add(path); - } - } + 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 static void reclaimTablePlan(FileIO fileIO, Path plan, int threads) throws IOException { - ThreadPoolExecutor executor = createCachedThreadPool(threads, "TEMPLATE_DROP_FILES"); + 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 { - cleanPlan( - fileIO, - plan, - false, - candidates -> { - AtomicBoolean deleted = new AtomicBoolean(true); - randomlyOnlyExecute( - executor, - path -> { - if (!deleteFile(fileIO, path)) { - deleted.set(false); - } - }, - candidates); - return deleted.get(); - }); + 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 static void cleanPlan(FileIO fileIO, Path plan, boolean dryRun, BatchCleaner cleaner) + private boolean reclaimManifest( + FormatReaderFactory reader, ThreadPoolExecutor executor, FileStatus manifest) throws IOException { - boolean complete = true; - int count = batchCount(fileIO, plan); - for (int i = 0; i < count; i++) { - Path batch = batchPath(plan, i); - if (fileIO.exists(batch)) { - if (cleaner.clean(readBatch(fileIO, batch))) { - if (!dryRun) { - fileIO.delete(batch, false); - } - } else { - complete = false; - } + 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); } - if (!dryRun && complete) { - fileIO.deleteDirectoryQuietly(plan); - } + AtomicBoolean deleted = new AtomicBoolean(true); + randomlyOnlyExecute( + executor, + path -> { + if (!deleteFile(path)) { + deleted.set(false); + } + }, + files); + return deleted.get() && deleteFile(manifest.getPath()); } - static boolean deleteFile(FileIO fileIO, Path path) { + private boolean deleteFile(Path path) { try { - if (fileIO.delete(path, false) || !fileIO.exists(path)) { + 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 void flush() throws IOException { - if (!paths.isEmpty()) { - publish( - fileIO, - batchPath(plan, batchCount), - JsonSerdeUtil.toJson( - paths.stream().map(Path::toString).toArray(String[]::new))); - batchCount++; - paths.clear(); - } - } - - private static Set readBatch(FileIO fileIO, Path batch) throws IOException { - Set candidates = new LinkedHashSet<>(); - for (String file : JsonSerdeUtil.fromJson(fileIO.readFileUtf8(batch), String[].class)) { - candidates.add(new Path(file)); - } - return candidates; - } - - private static int batchCount(FileIO fileIO, Path plan) throws IOException { - return Integer.parseInt(fileIO.readFileUtf8(new Path(plan, SEALED))); - } - - private static Path tableCleanupPath(Path tablePath) { + private static Path cleanupPath(Path tablePath) { return new Path(tablePath, CLEANUP_DIRECTORY); } - private static Path archivePath(Path tablePath) { - Path database = tablePath.getParent(); - Path warehouse = database.getParent(); - return new Path(warehouse == null ? database : warehouse, 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); } - private static Path batchPath(Path plan, int index) { - return new Path(plan, "batch-" + index); - } + // 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()); + } + } - private static void publish(FileIO fileIO, Path file, String value) throws IOException { - if (!fileIO.tryToWriteAtomic(file, value) && !fileIO.exists(file)) { - throw new IOException("Cannot publish " + file); + 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); + } + } } - } - @FunctionalInterface - interface BatchCleaner { - boolean clean(Set candidates) throws IOException; + 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/utils/FileSystemBranchManager.java b/paimon-core/src/main/java/org/apache/paimon/utils/FileSystemBranchManager.java index a707de484283..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 @@ -26,7 +26,6 @@ import org.apache.paimon.manifest.FileEntry; import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; -import org.apache.paimon.operation.EntropyInjectTemplateFilesDeletion; import org.apache.paimon.operation.Lock; import org.apache.paimon.operation.TemplateFileDeletionPlan; import org.apache.paimon.schema.FileSystemSchemaManager; @@ -183,12 +182,8 @@ public void dropBranch(String branchName) { !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() && EntropyInjectTemplateFilesDeletion.isTemplate(schema.get())) { - TemplateFileDeletionPlan plan = - TemplateFileDeletionPlan.prepareBranch(fileIO, tablePath); - EntropyInjectTemplateFilesDeletion.collect( - fileIO, tablePath, branchName, schema.get(), plan); - plan.seal(); + if (schema.isPresent() && TemplateFileDeletionPlan.isTemplate(schema.get())) { + TemplateFileDeletionPlan.save(fileIO, tablePath, branchName, schema.get(), true); } try { // Delete branch directory 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 index 58511b695f5f..47e54269e709 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/EntropyInjectTemplateTest.java @@ -31,9 +31,13 @@ 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; @@ -55,7 +59,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -233,29 +236,14 @@ protected TableMetadata loadTableMetadata(Identifier identifier) } @Test - public void testDropTableKeepsTheFilesWhenTheCatalogRefusesIt() throws Exception { - java.nio.file.Path warehouse = tempPath.resolve("refusing-warehouse"); - try (Catalog refusing = - new FileSystemCatalog(LocalFileIO.create(), new Path("file://" + warehouse)) { - @Override - protected void dropTableImpl(Identifier identifier, List externalPaths) { - throw new RuntimeException("the metastore refuses to drop the table"); - } - }) { - refusing.createDatabase(DATABASE, true); - Identifier id = Identifier.create(DATABASE, "kept"); - refusing.createTable(id, sharedSchema("kept"), false); - write((FileStoreTable) refusing.getTable(id), 1, "a"); - Set files = sharedTableFiles("kept"); - assertThat(files).hasSize(1); - - assertThatThrownBy(() -> refusing.dropTable(id, false)) - .hasMessageContaining("refuses to drop the table"); - - FileStoreTable keptTable = (FileStoreTable) refusing.getTable(id); - TemplateFileDeletionPlan.retryTableDrops(keptTable.fileIO(), keptTable.location(), 1); - assertThat(sharedTableFiles("kept")).isEqualTo(files); - } + 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 @@ -350,40 +338,94 @@ public void testDropTableReclaimsFilesFromDroppedBranch() throws Exception { 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 testDropPlanSpillsPathsInBatches() throws Exception { + 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"); - LocalFileIO fileIO = LocalFileIO.create(); - TemplateFileDeletionPlan plan = TemplateFileDeletionPlan.prepare(fileIO, table.location()); - for (int i = 0; i <= 1024; i++) { - plan.add(new Path("file://" + sharedRoot.resolve("file-" + i))); + 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.seal(); + plan.close(); try (Stream files = Files.walk(java.nio.file.Paths.get(table.location().toUri()))) { assertThat( - files.filter(path -> path.getFileName().toString().startsWith("batch-")) + files.filter(path -> path.getFileName().toString().endsWith(".avro")) .count()) - .isEqualTo(2); + .isGreaterThan(1); } catalog.dropTable(Identifier.create(DATABASE, "batched"), false); - try (Stream files = Files.walk(tempPath.resolve("warehouse"))) { - assertThat(files.noneMatch(path -> path.getFileName().toString().startsWith("batch-"))) - .isTrue(); - } + assertThat(table.fileIO().exists(table.location())).isFalse(); } @Test - public void testDropTableRetriesFailedTemplateDeletion() throws Exception { + 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"); @@ -392,19 +434,60 @@ public boolean delete(Path path, boolean recursive) throws IOException { } }; 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); - write((FileStoreTable) retrying.getTable(identifier), 1, "a"); - - retrying.dropTable(identifier, 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"); } - try (Catalog retrying = new FileSystemCatalog(LocalFileIO.create(), warehouse)) { - retrying.dropTable(identifier, true); - assertThat(sharedTableFiles("retry")).isEmpty(); + 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(); } } 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";
data-file.external-paths.strategy
none

Enum

The strategy of selecting an external path when writing data.

Possible values:
  • "none": Do not choose any external storage, data will still be written to the default warehouse path.
  • "specific-fs": Select a specific file system as the external path. Currently supported are S3 and OSS.
  • "round-robin": When writing a new file, a path is chosen from data-file.external-paths in turn.
  • "entropy-inject": When writing a new file, a path is chosen based on the hash value of the file's content.
  • "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.
  • "weight-robin": When writing a new file, a path is chosen based on configured weights.
The strategy of selecting an external path when writing data.

Possible values:
  • "none": Do not choose any external storage, data will still be written to the default warehouse path.
  • "specific-fs": Select a specific file system as the external path. Currently supported are S3 and OSS.
  • "round-robin": When writing a new file, a path is chosen from data-file.external-paths in turn.
  • "entropy-inject": When writing a new file, a path is chosen based on the hash value of the file's content.
  • "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.
  • "weight-robin": When writing a new file, a path is chosen based on configured weights.
data-file.external-paths.weights